0

我是 django 框架开发人员的新手,我已经阅读了很多基于类的视图和表单的文档。现在,我想在底部创建一个包含汽车列表和表单的页面(用于测试目的),用于创建新汽车。

这是我的意见.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

这是一张我想要创建的图片。

图片

我的问题是:

1)这是为此目的的“最佳实践”吗?2) 我模板中的 {{ car​​.name.errors }} 始终为空白(不显示验证错误)。

谢谢!……对不起我的英语。

4

1 回答 1

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)
于 2013-07-30T16:48:57.530 回答