django 带有表单集的多种表单

Posted

技术标签:

【中文标题】django 带有表单集的多种表单【英文标题】:django multiple forms with formsets 【发布时间】:2014-12-27 09:36:38 【问题描述】:

我有一个模型:

class HospitalDoctor(models.Model):
    hospital = models.ForeignKey(Hospital)
    full_name = models.CharField(max_length=100, unique=True)
    expertization = models.CharField(max_length=50)
    nmc_no = models.CharField(max_length=20)
    timings = models.ManyToManyField('Timing',related_name='shift_timing')
    appointment = models.IntegerField(default=0)

    def __unicode__(self):
        return self.full_name

class Timing(models.Model):
    hospital = models.ForeignKey(Hospital)
    doctor = models.ForeignKey(HospitalDoctor)
    day = models.CharField(max_length=20)
    mng_start = models.IntegerField()
    mng_end = models.IntegerField()
    eve_start = models.IntegerField()
    eve_end = models.IntegerField()

    def __unicode__(self):
        return self.day

我为此创建了表单:

class HospitalDoctorInfoForm(forms.ModelForm):

    class Meta:
        model = HospitalDoctor
        fields = ('hospital','full_name', 'expertization', 'nmc_no')

class TimingForm(forms.ModelForm):
    class Meta:
        model = Timing
        fields = ('day','mng_start', 'mng_end', 'eve_start', 'eve_end')

在这里,我想创建有关医生的信息,例如 HospitalDoctorInfoForm 中的个人信息和 TimingForm 中的一周时间表。

我认为我应该在 TimingForm 中使用表单集进行 7 天计划的计时,初始值为星期天、星期一...

我写过观点:

class HospitalDoctorAddView(CreateView):

    template_name = "hospital_doctor_add.html"
    model = HospitalDoctor

    def post(self, request, *args, **kwargs):

        info_form = HospitalDoctorInfoForm(request.POST)
        formset = modelformset_factory(request.POST, Timing, form=TimingForm, extra=7)

        if formset.is_valid() and info_form.is_valid():
            self.formset_save(formset)
            self.info_form_save(info_form)

        context['formset'] = formset

        return render(request, self.template_name, context)

    def formset_save(self, form):
        frm = Timing()
        frm.hospital = self.request.user
        frm.mng_start = form.cleaned_data['mng_start']
        frm.mng_end = form.cleaned_data['mng_end']
        frm.eve_start = form.cleaned_data['eve_start']
        frm.eve_end = form.cleaned_data['eve_end']
        frm.save()

    def info_form_save(self, form):
        info = HospitalDoctor()
        info.hospital = self.request.user
        info.full_name = form.cleaned_data['full_name']
        info.expertization = form.cleaned_data['expertization']
        info.nmc_no = form.cleaned_data['nmc_no']
        info.save()

当我这样做时,它会给出错误消息“创建没有 'fields' 属性或 'exclude' 属性的 ModelForm 已被弃用 - 表单 TimingForm 需要更新 “。我需要帮助。我正在做的事情是正确的还是有其他方法可以实现这一点。

【问题讨论】:

【参考方案1】:

https://docs.djangoproject.com/en/dev/ref/forms/models/#django.forms.models.inlineformset_factory

from django.core.urlresolvers import reverse
from django.forms.models import inlineformset_factory

TimingFormSet = inlineformset_factory(HospitalDoctor, Timing, form=TimingForm, extra=7)

class HospitalDoctorAddView(CreateView):
   ...

    def get_context_data(self, **kwargs):
        context = super(HospitalDoctorAddView, self).get_context_data(**kwargs)
        context['formset'] = TimingFormSet(instance=Timing())

        return context

    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST)
        formset = TimingFormSet(request.POST, request.FILES)  # request.FILES for files, remove if don't send files

        if form.is_valid() and formset.is_valid():
            return self.form_valid(form, formset)
        else:
            return self.form_invalid(form, formset)

    def form_valid(self, form, formset):
        self.object = form.save()
        formset.instance = self.object
        formset.save()

        return HttpResponseRedirect(self.get_success_url())

    def form_invalid(self, form, formset):
        return self.render_to_response(
            self.get_context_data(
                form=form,
                formset=formset
            )
        )

    def get_success_url(self):
        return reverse('some_app:url_name')

【讨论】:

以上是关于django 带有表单集的多种表单的主要内容,如果未能解决你的问题,请参考以下文章

Django 动态表单,带有 HTML 数组的表单集

带有 HTML 表单的 Django

已解决:如何在 Django 中的表单错误中重新显示带有选定值的表单集和 Select2 字段

django 内联表单集的单选按钮

如何使用 django-extra-views 将请求传递到内联表单集中

带有普通 Django 表单和引导程序的 Django-CKEditor