2012-10-03 26 views
3

我以前使用过这个代码,它工作正常,我被建议使用另一个成员的ModelForm,它确实有意义使用form.is_valid()函数等..所以想给它一个尝试。使用Django ModelForms保存数据

我在互联网上经历了一些其他例子,但我似乎没有工作出于某种原因,或者可能是我做得不对,当我在视图中打印表单时,我得到以下内容,到else语句,所以我的状态不会被保存

<input id="id_product" type="text" name="product" value="aassddf" maxlength="250" /> 
FAIL 

我model.py

from django.db import models 
from django.forms import ModelForm 

class Category(models.Model): 
    name = models.CharField(max_length=250) 

    def __unicode__(self): 
     return self.name 

class Product(models.Model): 
    category = models.ForeignKey(Category) 
    product = models.CharField(max_length=250) 
    quantity = models.IntegerField(default=0) 
    price = models.FloatField(default=0.0) 

    def __unicode__(self): 
     return self.product 

class ProductForm(ModelForm): 
    class Meta: 
     model = Product 

我views.py

from models import * 
from django.shortcuts import render_to_response 
from django.http import HttpResponseRedirect 

def index(request): 
    ... 
    ... 

def add_product(request): 
    if request.method == 'POST': 
     form = ProductForm(request.POST) 
     print form['product'] 
     if form.is_valid(): 
      form.save() 
      return HttpResponseRedirect('/product') 
     else: 
      print 'FAIL' 
    return HttpResponseRedirect('/product') 

我的HTML

<form method="post" action="add_product/"> 
     {% csrf_token %} 
     <label for="category">Category</label> 
     <select name="category" id="category"> 
     {% for category in category_list %} 
      <option> {{ category.name }} </option> 
     {% endfor %} 
     </select> 

     <label for="product">Product</label> 
     <input type="text" name="product" id="product"> 

     <label for="quantity">Quantitiy</label> 
     <input type="text" name="quantity" id="quantity"> 

     <label for="price">Price</label> 
     <input type="text" name="price" id="price"> 

     <input type="submit" value="Add New product" id="create"> 
    </form> 

有没有更好的办法可以保存数据,使用ModelForms? 在此先感谢您的帮助。

回答

2

感谢Daniel Roseman和Anuj Gupta,我想我最终重新对我的代码进行了重新编写,以标准方式工作,因此它将生成html表单并验证错误。

因此,对于正在尝试工作的任何其他人而言,这里的django表单是我工作的代码。

model.py是几乎是同一个我张贴的问题,但我删除

class ProductForm(ModelForm): 
    class Meta: 
     model = Product 

我创建了一个新的形式。PY这里是代码 -

from django import forms 
from models import Category 

class ProductForm(forms.Form): 
    # Put all my Categories into a select option 
    category = forms.ModelChoiceField(queryset=Category.objects.all()) 
    product = forms.CharField() 
    quantity = forms.IntegerField() 
    price = forms.FloatField() 

views.py改变有很大的变化 -

def add_product(request): 
    success = False 

    if request.method == "POST":   
     product_form = ProductForm(request.POST) 

     if product_form.is_valid():    
      success = True 

      category = Category.objects.get(name=product_form.cleaned_data['category']) 
      product = product_form.cleaned_data['product'] 
      quantity = product_form.cleaned_data['quantity'] 
      price = product_form.cleaned_data['price'] 

      new_product = Product(category = category, product = product, quantity = quantity, price = price) 
      new_product.save() 

      new_product_form = ProductForm() 

      ctx2 = {'success':success, 'product_form':new_product_form} 
      return render_to_response('product/add_product.html', ctx2 , context_instance=RequestContext(request)) 
    else: 
     product_form = ProductForm() 
    ctx = {'product_form':product_form} 
    return render_to_response('product/add_product.html', ctx , context_instance=RequestContext(request)) 

最后,在我的HTML页面我用{{ product_form.as_p }}所以它创建的形式动态

{% if success %} 
    <h3> product added successfully </h3> 
{% endif %}   
<form method="post" action="."> 
    {% csrf_token %} 

    {{ product_form.as_p }} 

    <input type="submit" value="Add New product" id="create"> 
    <input type="reset" value="reset" id="reset"> 
</form> 

这可能不是完美的解决方案,但对于一个sta像我这样听起来不错,有时你在阅读docs时就迷路了,希望它能帮助一些人。

干杯

3

您应该阅读the documentation。如果表单无效,它将会有一组与其相关的错误,它会告诉你到底是什么原因。但是,您只需将其丢弃,然后重定向到/product。该文档显示了如何重新显示带有错误的表单。

而且你不应该直接在你的模板写HTML表单字段标签:使用表单对象从视图 - {{ form.product }},等等 - 这些将与重新显示相应的值来填充。

1

尝试:

<form method="post" action="add_product/"> 
    {% csrf_token %} 
    {{ form.as_p }} 
</form> 
在你的模板

,而不是手工编码形式的输入标签。这个快捷方式将为您生成表单html以及打印验证错误。

确保您的form对象返回到模板时:

  1. 没有request.POST(形式尚未提交)
  2. form.is_valid()失败(形式​​有验证错误)

当然,这只是为了让你开始。你真的应该read the docs