0

我有两个模型,一个学生和一个代理。因为学生模型有一些选择字段,所以我将 ModelForm 用于 Form,这很棒。每个学生都有一个代理:

class Student(models.Model):
    ncode = models.CharField(max_length=12)
    name = models.CharField(max_length=40)
    family = models.CharField(max_length=60)
    father = models.CharField(max_length=40)
    telephone = models.CharField(max_length=18, blank=True)
    address = models.CharField(max_length=256)
    reagent = models.ForeignKey(Reagent)
    state = models.IntegerField(choices=STUDYING_STATUS)
    degree = models.IntegerField(choices=DEGREE_STATUS)

class Reagent(models.Model):
    name = models.CharField(max_length=40)
    family = models.CharField(max_length=60)
    telephone = models.CharField(max_length=18)

这些是表格:

class Student_Form(ModelForm):
    class Meta:
        model = Student

class Reagent_Form(ModelForm):
    class Meta:
        model = Reagent

但是我打算将代理和学生都放在一个表格中,所以我将它们放在模板中的一个表格中:

<form action="" method="POST"> {% csrf_token %}
    <table>
        {{ student_form.as_table}}
        {{ reagent_form.as_table }}
    </table>
    <input type="submit" value="Add">
</form>

我的问题是如何在学生和代理表格的不同实例中获取输入的信息? 如果模板中只是一种表单信息,我会使用f = StudentForm(request.POST)!但在这种情况下形式是混合的

4

1 回答 1

1

你仍然可以做

f = Student_Form(request.POST)
r = Reagent_Form(request.POST)

django 将分配适当的字段。

要隐藏 FK 字段,

class Student_Form(ModelForm):
    class Meta:
        model = Student
        exclude = ('reagent', )

class Reagent_Form(ModelForm):
    class Meta:
        model = Reagent

在视图中保存时,

def myview(request):
    reagent_form = Reagent_Form(prefix='reagent')
    student_form = Student_Form(prefix='student')
    if request.POST:            
         reagent_form = Reagent_Form(request.POST, prefix='reagent')
         student_form = Student_Form(request.POST, prefix='student')
         if reagent_form.is_valid() and student_form.is_valid():
             reagent = reagent_form.save() #first create the object
             student = student_form.save(commit=False) 
             student.reagent = reagent #then assign to student. 
             student.save()

         #rest of the code. 
于 2013-06-21T20:13:28.877 回答