Django通用表单集ManytoManyField不是清理数据的一部分

人工智能

我的表单集基于 CRUD 方法。从这里和那里获取代码。现在的问题是我无法保存模型,form_valid没有调用方法。模板如下所示:

<form action="create" method=”POST”>
    {% csrf_token %}
    <div id="formset" data-formset-prefix="{{ formset.prefix }}">
        {{ formset.management_form }}
        <div data-formset-body>
            {% for form in formset %}
            <div data-formset-form>
                {{ form }}                
            </div>
            {% endfor %}
            <hr>
        </div>
</form>

它所基于的Formset类如下:

class Formset(LayoutObject):
    template = "doc_aide/formset2.html"

    def __init__(self, formset_name_in_context, template=None):
        self.formset_name_in_context = formset_name_in_context
        self.fields = []
        if template:
            self.template = template

    def render(self, form, form_style, context, template_pack=TEMPLATE_PACK):
        formset = context[self.formset_name_in_context]
        # for form in formset:
        return render_to_string(self.template, {'formset': formset})

表格和视图如下:

class PrescriptionForm(forms.ModelForm):
    class Meta:
        model = Prescription
        exclude = ['handed_out', ]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_tag = True
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-md-3 create-label'
        self.helper.field_class = 'col-md-9'
        self.helper.layout = Layout(
            Div(
                Field('patient'),
                Field('note'),
                HTML('<hr class="style2">'),
                Fieldset('Add Drug', Formset('line_prescription')),
                HTML('<hr class="style1">'),
                ButtonHolder(Submit('submit', 'save')),
                )
            )

    def clean(self, *args, **kwargs):
        cleaned_data = super().clean(*args, **kwargs)
        print(cleaned_data)
        # cleaned_data.get('line_prescription')
        return cleaned_data


class PrescriptionCreate(generic.CreateView):
    model = Prescription
    template_name = 'doc_aide/write_prescription4.html'
    form_class = PrescriptionForm
    
    def get_context_data(self, **kwargs):
        print('here')
        context = super().get_context_data(**kwargs)
        if self.request.POST:
            context['line_prescription'] = SinglePrescriptionFormset(self.request.POST)
        else:
            context['line_prescription'] = SinglePrescriptionFormset()
        context['form'].fields['patient'].initial = Patient.objects.get(pk=self.kwargs['patient'])
        return context

    def form_valid(self, form):
        print('Ia am here')
        context = self.get_context_data()
        prescriptionlines = context['line_prescription']
        with transaction.atomic():
            form.instance.created_by = self.request.user
            self.object = form.save()
            if prescriptionlines.is_valid():
                prescriptionlines.instance = self.object
                prescriptionlines.save()
        return super().form_valid(form)

    def get_success_url(self):
        return reverse_lazy('doc_aide:prescription_detail', kwargs={'pk': self.object.pk})

到目前为止,我发现验证失败。因为 line_prescription 不是清理数据的一部分。

{'patient': <Patient: HF-1_2020>, 'no_charge': False, 'note': '-'}

如何使 Formset 数据成为清理数据的一部分?

人工智能

ManyToManyField 需要是可选字段。因此,在模型中添加 blank=True 它将起作用。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如果初始makemigrations的一部分,对查询集使用选择的Django表单会导致错误

检查HTML表单表明按钮不是表单的一部分

仅重置表单的一部分

表单的一部分未提交

如何手动呈现Django表单的一部分

使接口的一部分不是可选的

仅锁定Apache Jena TDB中数据集的一部分

渲染大数据集的一部分 - dragToPan

将StandardScaler应用于数据集的一部分

Linq获取数组和求和作为返回数据集的一部分

R BiocCheck:也许它们是装载有data()的数据集的一部分?

Python:努力掩盖数据集的一部分

是否可以仅加载TensorFlow数据集的一部分?

如何仅选择Tensorflow数据集的一部分并更改尺寸

为什么静态数据成员不是c ++中对象的一部分?

选择数据框的一部分以获取视图,而不是副本

如何删除单独的正斜杠而不是属于数据一部分的正斜杠?

Django-替换urlfield的一部分

删除数据帧的一部分

删除数据的最后一部分

解包 Pandas 数据帧的一部分

如何从api的一部分接收数据到另一部分

通用节点是否需要成为通用列表的一部分?

Github - 在合并作为拉取请求的一部分后清理分支

如何在仅连接外部查询集的一部分的Django中创建ForeignKey?

Django:通过“参数具有字段值的一部分”来过滤查询集?

Keras load_data()如何知道训练和测试集的数据的哪一部分?

data.table:在自定义函数中根据条件选择数据集的一部分

如何仅加载AzureML表格数据集的一部分(链接到Azure Blob存储)