0

我有一个允许用户编辑对象描述的表单。如何在表单的隐藏输入值中填充对象 ID。到目前为止,我所做的是在 forms.py 中添加了一个名为 hidden_​​field 的字段,但它只显示 hidden_​​field 。如何将 hidden_​​field 与对象 ID 链接

模型.py

class School(models.Model):


    user = models.ForeignKey(User)
    name = models.CharField(max_length=55)
    description = models.CharField(max_length=300,blank=True)

表格.py

class SchoolDescriptionForm(forms.ModelForm):
        description = forms.CharField(widget=forms.Textarea,max_length=300)
        hidden_field = forms.CharField(widget=forms.HiddenInput())
    class Meta:
        model = School 
        fields = ()

视图.py

def SchoolEditor(request,school_id):


    school = School.objects.get(pk=school_id,user=request.user)
    form = SchoolDescriptionForm(instance=school) # I want to populate the object ID 

    return render(request,'schooleditor.html',{'school':school,'form':form})

模板

 <form method="POST" enctype="multipart/form-data">
     {% csrf_token %}
    {{ form.as_p }}

    <input type = "submit" value= "save" />
{{ form.field.as_hidden }}
 </form>
4

2 回答 2

3

将 hidden_​​field 更改为 id 并告诉 Django 包含 School 的 id。

class SchoolDescriptionForm(forms.ModelForm):
        description = forms.CharField(widget=forms.Textarea,max_length=300)
        id          = forms.CharField(widget=forms.HiddenInput())
    class Meta:
        model = School 
        fields = ('id', 'name', 'description')

编辑:

如果要保存 hidden_​​field 作为名称,则应添加自定义 init 方法:

def __init__(self, *args, **kwargs):
    super(SchoolDescriptionForm, self).__init__(*args, **kwargs)
    if self.instance:
        self.fields['hidden_field'].initial = instance.id
于 2013-05-21T12:25:46.457 回答
1

只需以以下形式传递对象 ID initial

def SchoolEditor(request,school_id):
    initial = {}
    school = School.objects.get(pk=school_id,user=request.user)
    if school:
        initial.update({'hidden_field': school.id})
    form = SchoolDescriptionForm(instance=school, initial=initial) # I want to populate the object ID 

    return render(request,'schooleditor.html',{'school':school,'form':form})
于 2013-05-21T12:29:01.927 回答