我以前使用过这个代码,它工作正常,我被建议使用另一个成员的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? 在此先感谢您的帮助。