如何使用模型中的值初始化django表单

时间:2017-02-02 20:53:42

标签: python django

我正在建立一个购物网站,我正在尝试使用产品信息初始化我的产品更新表单,但我无法将模型中的信息输入到表单中。

模型功能

def get_product_details(product_id):
    product_details = Products.objects.filter(name=rproduct_id).select_related('name', 'description','price','qty')
    return product_details

form.py

class UpdateProductForm(forms.Form):

        name = forms.CharField(
        max_length=200,
        required=True,
        label="* name:",
        widget=TextInput(attrs={'class' : 'span6 small-margin-top small-margin-bottom'}),
    )
        description = forms.CharField(
        max_length=200,
        required=True,
        label="* description:",
        widget=TextInput(attrs={'class' : 'span6 small-margin-top small-margin-bottom'}),
    )
        price = forms.IntegerField(
        label="* price:",
        widget=TextInput(attrs={'class' : 'span6 small-margin-top small-margin-bottom'}),
    )
        qty = forms.IntegerField(
        label="* Qty:",
        widget=TextInput(attrs={'class' : 'span6 small-margin-top small-margin-bottom'}),
    )

view.py

def update_risk(request,product_id):

    product_details = get_product_details(product_id)


    name = form.cleaned_data['name'] 
    description = form.cleaned_data['description']
    price = form.cleaned_data['price']
    qty = form.cleaned_data['qty']

    form = UpdateProductForm(product_details)



    return render(
        request,
        template_name = 'products/forms/update_product_form.html',
        dictionary = {
            'form':form,
            'instr_text':instr_text
        }
    )

更新表格

<form method="POST" action="{% url 'products:update'%}">
    {% csrf_token %}
{{ form.name }}
{{ form.description }}
{{ form.price }}
{{ form.qty }}
</form>

1 个答案:

答案 0 :(得分:4)

您可以使用ModelForms,它不仅可以匹配模型的字段,还可以使用模型中的数据轻松初始化。

请参阅此处以获取一般说明:https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/

具体来说,如果表单是ModelForm,您可以这样做:

>>> article = Article.objects.get(pk=1)
>>> form = ArticleForm(instance=article)