使用Django中的ModelForm创建多步骤表单

时间:2018-02-09 18:33:23

标签: python django django-formwizard

我正在尝试使用名为FormWizard的库创建一个多步骤的ModelForm。但是,我很难得到我想要的结果。

  

工作流程

User clicks on create patient link
User opens patient form
User inserts patient data
User submits form
if form is invalid:
    redisplay form with error 
if form is valid:
    move to next form 
    enter symptom data
    submit form
if form is invalid:
    redisplay form with error 
if form is valid:
    move to next form 
    enter disease data
    submit form
if form is invalid:
    redisplay form with error
if form is valid:
    User is redirected to general form that has patient + symptom + disease information.
  

查看将创建多步骤ModelForm

class ConsultationCreate(SessionWizardView):

    instance = None

    def get_form_instance(self, step):
        if self.instance is None:
            self.instance = Patient
        return self.instance

    template_ = 'data/multi_form.html'

    def done(self, form_list, **kwargs):
        self.instance.save()


def process_form_data(form_list):

    form_data = [form.cleaned_data for form in form_list]

    logr.debug(form_data[0]['NIS'])
    logr.debug(form_data[1]['identity'])
    logr.debug(form_data[2]['identity'])

    return form_data
  

这是它产生的错误

ValidationError at /patient/create
['ManagementForm data is missing or has been tampered.']

代码

  

urls.py

from django.conf.urls import url
from data.views import IdentityList, IdentityCreate, IdentitySpecific, ConsultationCreate, MultiStep
from data.forms import  SymptomForm, DiseaseForm, IdentityForm

urlpatterns = [
        url(r'^patient/$', IdentityList.as_view(),  name = 'data_patient_list'),

        url(r'^patient/create$', ConsultationCreate.as_view([IdentityForm, SymptomForm, DiseaseForm]),  name = 'data_patient_create'),

]
  

models.py

    from django.db import models
    from django.utils import timezone
    from django.shortcuts import reverse
    import datetime
  

创建患者数据库

class Patient(models.Model):

    NIS =models.CharField(max_length = 200, primary_key = True)
    timestamp = models.DateTimeField(auto_now = True)
    first_name = models.CharField(max_length = 80, null = True)
    last_name = models.CharField(max_length = 80, null = True )
    contact = models.CharField(max_length = 15, null = True)
    location  = models.CharField(max_length = 100, blank = True)
    email_address = models.EmailField()

    CHOOSE = 'The patient is'
    MALE = 'M'
    FEMALE = 'F'
    personGender = ((CHOOSE,'The patient is'),(MALE, 'Male'),(FEMALE,'Female'),)
    gender = models.CharField(max_length=2,choices=personGender,default=CHOOSE)

    born = models.DateField(auto_now = False, auto_now_add = False, blank = True, null = True)
  

创建症状数据库

class Symptom(models.Model):

    identity = models.CharField('Name of symptom', max_length = 80, default = '')
    description = models.TextField(max_length = 1000, default = '')
    patient = models.ManyToManyField(Patient,  through = 'Consultation')

    def __str__(self):
        return '%s' % ( self.identity )
  

创建疾病数据库

class Disease(models.Model):

    identity = models.CharField('Name of disease', max_length = 80, default = '')
    description = models.TextField(max_length = 5000, default = '')
    symptom = models.ManyToManyField(Symptom)

    def __str__(self):
        return '%s' % ( self.identity )
  

咨询模型是中间模型

class Consultation(models.Model):
    patient_identity = models.ForeignKey(Patient)
    patient_condition = models.ForeignKey(Symptom)
    patient_disease = models.ForeignKey(Disease)
    patient_treatment = models.ForeignKey(Treatment)
    consultation_date_and_time = models.DateTimeField('visitation date and time', auto_now = False, auto_now_add = False, blank = True, null = True)

    # Use get_absolute_url to access single page model objects that possess a Canonical Uniform resource locator
    def get_absolute_url(self):
        return reverse('data_patient_detail', kwargs={'pk':self.pk})
  

views.py

from data.models import Treatment, Symptom, Disease, Consultation, Patient
from django.shortcuts import get_object_or_404, render, redirect, render_to_response
from django.views.generic import View
from data.forms import IdentityForm
from formtools.wizard.views import SessionWizardView
  

患者列表的基于类的视图

class IdentityList(View):
    template_ = 'data/patient_list.html'
    def get(self, request):
        patient_list = Consultation.objects.all()
        return render(request, self.template_, {'patient_list':patient_list})
  

基于分类的患者详细信息视图

class IdentitySpecific(View):
    model = Consultation
    template_ = 'data/patient_detail.html'
    def get(self, request, pk):
        patient_consult = Consultation.objects.filter(pk=pk)
        return render(request, self.template_, {'patient_consult':patient_consult})
  

多步模型的基于类的视图

class ConsultationCreate(SessionWizardView):
    instance = None
    def get_form_instance(self, step):
        if self.instance is None:
            self.instance = Patient
        return self.instance

    template_ = 'data/multi_form.html'

    def done(self, form_list, **kwargs):
        self.instance.save()
  

函数process_form_data用于处理表单数据   咨询创建视图

def process_form_data(form_list):
    form_data = [form.cleaned_data for form in form_list]
    logr.debug(form_data[0]['NIS'])
    logr.debug(form_data[1]['identity'])
    logr.debug(form_data[2]['identity'])
    return form_data

0 个答案:

没有答案