Django CreateUpdateView implementation in the django template

只愿长相守 提交于 2021-01-29 17:59:51

问题


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 am trying to integrate CreateUpdateView from the @scubabuddha's answer from the solution.

views.py

from createupdateview import CreateUpdateView

class StudentView(CreateUpdateView):
   template_name="admission.html"
   Model = Student
   form_class = StudentForm
  
  def get(self, request, *args, **kwargs):
    return self.post(request, *args, **kwargs)

  def post(self, request, *args, **kwargs):
    forms = {"userform": UserForm(request.POST or None), 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!')
        return render(request, 'admission.html', forms)
      #-- Logic to validate and save each form
      ...
      return render(request, 'admission.html', forms)  
    return render(request, 'admission.html', forms)

This is perfectly working for CreateView, but not able to understand how to use this for UpdateView or editview. If user hits editview, {{form|crispy}} should also display the details to allow user to edit the form.

urls.py (I also want to merge below 2 urls to 1, can we do this?)

from django.urls import path
from students import views 
from students.views import StudentList, StudentView

urlpatterns = [
    
    path('', StudentList.as_view(), name='students'), 
    path('add/', StudentView.as_view(), name='addview'), 
    path('<int:pk>/edit/', StudentView.as_view(), name='editview'), 
...
]

I want to display, all the student details in the UpdateView forms -

admission.html

<form class="form" name="admissionForm" id="admissionForm" method="post" 
            enctype="multipart/form-data" action="{% url 'addview' %}"> 
 {% csrf_token %}
  <div class="pages">
     <h4 class="mt-2 mb-3">Personal Information</h4>
      {% include "student_errors.html" %}                
      {{userform|crispy}}      #-- It should display student details 
      {{guardian_form|crispy}}    
      {{contact_form|crispy}}    
      ....
      <div class="btn_container">
          <button type="submit" class="btn btn-info float-right btn-next">Submit</button>  
      </div>
 </div>

P.S. I kept minimal code here, in actual production its huge code. (Migrating Django applcation 1.9 to 3.0)


回答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)





来源:https://stackoverflow.com/questions/63590880/django-createupdateview-implementation-in-the-django-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!