Skip to content Skip to sidebar Skip to footer

Django CreateUpdateView Implementation In The Django Template

I am very new to django Class based views, trying to integrate it with my existing project. My goal is to use same Class based view to Create and Update student application form. I

Solution 1:

The CreateUpdateView you are using from this solution inherits from ModelFormMixin and expect to handle only one form (initialization, form_class, saving, ...). And in your code your are rewriting get() and post() method so it make no sense to inherit from CreateUpdateView.

Here is how you can do it using a simple View (untested) :

from django.http import Http404
from django.views.generic import View
from django.shortcuts import render

class StudentView(View):
    template_name = "admission.html"

    def get_object(self):
        if self.kwargs.get('pk'):
            try:
                obj = Student.objects.get(pk=pk)
            except Student.DoesNotExist:
                raise Http404("No student found matching the query")
            else:
                return obj
        return None # create view

    def get_view(self, request, *args, **kwargs):
        forms = {"userform": UserForm(request.POST or None, instance=self.object), guardian..., contact...} # other 5-6 forms}
        if request.POST:
            invalid_forms = [form.is_valid() for form in self.forms.values()]
            if not all(invalid_forms):
                messages.error(request,'You must fill up all the valid mandatory form fields!')
            else:
                #-- Logic to validate and save each form
        return render(request, self.template_name, forms)  

    def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        return self.get_view(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        self.object = self.get_object()
        return self.get_view(request, *args, **kwargs)




Post a Comment for "Django CreateUpdateView Implementation In The Django Template"