繁体   English   中英

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

[英]How to Initialize a django form with values from a model

我正在建立一个购物网站,我正在尝试使用产品信息来初始化我的产品更新表格,但是我无法从模型中获取信息。

模型功能

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>

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

有关一般说明,请参见此处: https : //docs.djangoproject.com/en/1.10/topics/forms/modelforms/

具体来说,如果表单是ModelForm,则可以执行以下操作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM