Fabrizio A
Fabrizio A

Reputation: 3172

ListView with Form in Django

I'm new to django framework developers, and I have read a lot of documentation of Class-Based View and Forms. Now, I want to create a single page (for test purpose) that contains a list of cars and a Forms, at the bottom page, for create a new Car.

this is my 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

and this is a picture with what I want create.

image

My questions are:

1) this is a "Best-Pratice" for this purpose? 2) The {{ car.name.errors }} in my template are always blank (no validation error shows).

Thanks! … and sorry for my english.

Upvotes: 0

Views: 1575

Answers (1)

Bibhas Debnath
Bibhas Debnath

Reputation: 14939

You could go other way around. Create a FormView and put the list of cars in context. That way form handling becomes easier. Like this -

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)

Upvotes: 2

Related Questions