I am making a shopping website, I am trying to initialize my products update form with the product information but I cant get the information from the model into the form.
models function
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
}
)
update form
<form method="POST" action="{% url 'products:update'%}">
{% csrf_token %}
{{ form.name }}
{{ form.description }}
{{ form.price }}
{{ form.qty }}
</form>
You could use ModelForms, which are designed not only to match the fields of the model, but also can easily be initialized with the data from a model.
See here for a general description: https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/
Specifically, if the form is a ModelForm, you can do this:
>>> article = Article.objects.get(pk=1)
>>> form = ArticleForm(instance=article)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.