Django模板中的Django CreateUpdateView实现 [英] Django CreateUpdateView implementation in the django template

查看:62
本文介绍了Django模板中的Django CreateUpdateView实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Django 基于类的视图,尝试将其与我现有的项目集成.我的目标是使用相同的基于类的视图 Create Update 学生申请表.我正在尝试从

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)

这对于 CreateView 来说是完美的工作,但无法理解如何将其用于 UpdateView editview .如果用户点击 editview ,则 {{form | crispy}} 也应显示详细信息,以允许用户编辑表单.

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(我也想将2个以下的URL合并为1,我们可以这样做吗?)

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'), 
...
]

我想在 UpdateView 表单中显示所有学生详细信息-

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

admission.html

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..在这里,我保留了最少的代码,在实际生产中,它的代码很大.(将Django应用1.9迁移到3.0)

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

推荐答案

您正在CreateUpdateView -based-for-the-both-create-and-update>此解决方案继承自 ModelFormMixin ,并希望仅处理一种形式(初始化,form_class,保存等).在您的代码中,您正在重写 get() post()方法,因此从 CreateUpdateView 继承是没有意义的.

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.

以下是使用简单的 View (未经测试)的方法:

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)



这篇关于Django模板中的Django CreateUpdateView实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆