2017-02-02 40 views
0

我想提出一個購物網站初始化值的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> 
+0

你有沒有看着[更新視圖](https://開頭的文檔。 djangoproject.com/en/1.10/ref/class-based-views/generic-editing/#updateview)?它處理表單處理的很大一部分你,如果你是剛剛更新的模式。另外'select_related'只有幫助,如果您選擇的關係 - 看起來像您選擇非關係領域。 –

+0

我只是從一個表 – thomaSmith

+0

越來越場不,我是新來的Django我沒有看過的的UpdateView – thomaSmith

回答

4

你可以使用ModelForms,其目的不僅是爲了匹配模型的領域,也可以很容易地從模型中的數據初始化。

在這裏看到的一般描述:https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/

具體而言,如果形式是的ModelForm,你可以這樣做:

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

感謝您的幫助,我真的很感激 – thomaSmith

相關問題