基于Form的Django Form

时间:2018-12-01 14:30:04

标签: django python-3.x

我根据原则编写代码,请不要重复。我一直违反该规则,因为我是Django的新手,但这应该很简单。

下面的代码对于ModelAForm没问题:

model.py

class ModelA(models.Model):
     id = model.AutoField(primary_key=True)
     name1 = models.CharField(max_length=100)
     name2 = models.CharField(max_length=100)
     ...
     right = models.BooleanField(default=True)

class ModelB(models.Model):
     id = model.AutoField(primary_key=True)
     mod = model.ForeignKey(ModelA, on_delete=models.CASCADE)
     above30 = models.BooleanField(default=True)

forms.py

class ModelAForm(forms.ModelForm):
    class Meta:
        model = ModelA
        exclude = ['id']

class ModelBForm(forms.ModelForm):
    class Meta:
        model = ModelB
        exclude = ['id']

但是这样一来,我在ModelBForm中看不到modelA的其他字段。我怎样才能做到这一点? 谢谢!

1 个答案:

答案 0 :(得分:1)

嗯,它不应该。因为它与ModelB和ModelA之间存在FK关系。因此,以ModelB形式,ModelA条目应显示为选择字段。如果要显示ModelA的字段,请尝试如下操作:

首先,从ModelBForm中删除FK参考字段:

def some_view(request):
    if request.method == 'GET':
        return render(request, 'template.html', {'form_a': ModelAForm(), 'form_b': ModelBForm()}) 
    if request.method == 'POST':
        form_a = ModelAForm(request.POST)
        form_a = ModelBForm(request.POST)
        if form_a.is_valid() and form_a.is_valid():
            instance_a = form_a.save()  # get model a instance
            instance_b = form_b.save(commit=False)
            instance_b.mod = instance_a  # set model a instance as FK
            instance_b.save()

现在在视图中同时使用这两种形式:

<form action="." method="post">
    {% csrf_token %}
    {{ form_a.as_p }}
    {{ form_b.as_p }}
    <input type="submit" value="Submit">
</form>

呈现这样的表单:

[
{"name":"Juan","Sex":"Male","ID":"1100"},{"name":"Maria";"Sex":"Female","ID":"2513"},{"name":"Pedro";"Sex":"Male","ID":"2211"}
]