2013-07-30 29 views
0

我是django框架開發人員的新手,我已經閱讀了很多基於類的視圖和表單的文檔。 現在,我想創建一個包含汽車和表單的頁面(用於測試目的),在底部頁面創建一個新車。ListView與Django中的表單

這是我的views.py

class IndexView(ListView): 
template_name = "index.html" 
context_object_name = "cars" 

def get_context_data(self, **kwargs): 
    context = super(IndexView, self).get_context_data(**kwargs) 
    context["form"] = CarForm 
    return context 

def get_queryset(self): 
    self.brand = self.kwargs.pop("brand","") 
    if self.brand != "": 
     return Car.objects.filter(brand__iexact = self.brand) 
    else: 
     return Car.objects.all() 

def post(self, request): 
    newCar = CarForm(request.POST) 
    if newCar.is_valid(): 
     newCar.save() 
     return HttpResponseRedirect("") 
    else: 
     return render(request, "index.html", {"form": newCar}) 

class CarForm(ModelForm): 
class Meta: 
    model = Car 
    delete = True 

,這是什麼,我想創建一個圖片。

image

我的問題是:

1)這是一個 「最佳初步實踐」 爲了這個目的? 2)我的模板中的{{car.name.errors}}總是空白的(沒有驗證錯誤顯示)。

謝謝! ...併爲我的英語感到抱歉。

回答

1

你可以用其他方法。創建一個FormView並將汽車列表放在上下文中。這種形式的處理變得更容易。像這樣 -

class CarForm(ModelForm): 
    class Meta: 
     model = Car 
     delete = True 

class IndexView(FormView): 
    template_name = "index.html" 
    form_class = CarForm 

    def get_context_data(self, **kwargs): 
     context = super(IndexView, self).get_context_data(**kwargs) 
     # Pass the list of cars in context so that you can access it in template 
     context["cars"] = self.get_queryset() 
     return context 

    def get_queryset(self): 
     self.brand = self.kwargs.pop("brand","") 
     if self.brand != "": 
      return Car.objects.filter(brand__iexact = self.brand) 
     else: 
      return Car.objects.all() 

    def form_valid(self, form): 
     # Do what you'd do if form is valid 
     return super(IndexView, self).form_valid(form)