【问题标题】:Display Django model entries as part of a form将 Django 模型条目显示为表单的一部分
【发布时间】:2018-09-22 15:18:10
【问题描述】:

我想将模型条目显示为表单的一部分,以便更新它们。做这个的最好方式是什么?我正在使用酥脆的表格。

我首先过滤我的对象,然后我想将此对象显示为一个表单,其中仅显示某些模型属性,并更新某些属性。

本质上是一个表,其中包含 obj 的所有无法修改的属性,其中 2 个属性将在表单中更新。

forms.py:

class ReportSampleForm(forms.Form):

    def __init__(self, *args, **kwargs):
        super(ReportSampleForm, self).__init__(*args, **kwargs)

        sample = self.data.get('sample_id', False)
        obj = VariantAnnotationSampleRun.objects.filter(sample_run_id=sample)

        self.helper = FormHelper()

        self.fields['id'] = forms.ChoiceField(
                required=True,
                label='blah:',
                widget=forms.CheckboxSelectMultiple,
                choices=((s.id, (s.variant_annotation_id.variant_id, s.attribute1, s.attribute2)) for s in obj)
            )

        self.helper.form_method = 'POST'

这会显示带有 variant_id、attribute1 和 attribute2 的复选框,但我希望填写模型条目“证据”和“注释”,如果选中该复选框并提交表单,则数据库会针对该特定模型条目进行更新.

models.py:

类 VariantAnnotationSampleRun(models.Model):

    variant_annotation_id = models.ForeignKey(VariantAnnotation,
    attribute1 = models.DecimalField(max_digits=8, decimal_places=3)
    attribute2 = models.IntegerField()

    reported = models.BooleanField(default=False)
    evidence = models.TextField(null=True, blank=True)
    annotation = models.CharField(max_length=80, null=True, blank=True)

在我看来,这是否可能在不构建完全定制的表单的情况下实现?

【问题讨论】:

    标签: django forms


    【解决方案1】:

    使用 ModelForm,选择要在其中使用的模型条目并创建该表单的实例。

    class MyModel (models.Model):
       ...
    
    
    class MyForm (forms.ModelForm):
       model = MyModel
    
    
    def my_view(request):
       obj = myModel.objects.get(id=1)
       variables = {}
       variables['form'] = myForm(instance=obj)
       render (request, 'mypage.html', variables)
    

    然后在 mypage.html 中包含 {{ form }} 任何你想要的地方。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-06
      • 2021-12-19
      • 2014-10-31
      • 1970-01-01
      • 2021-06-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多