我是django的初学者(使用django 1.7)并尝试使用crispy-forms创建表单以便向db添加新产品。问题是,表单正在运行,但它没有在数据库中创建新产品。
当我记录时,如果我点击保存按钮没有任何反应,请在地址栏中显示如下。
http://127.0.0.1:8000/add_product/?csrfmiddlewaretoken=kfGpEA6ZC32Lad9m9uwWZEhElwBGLHPA&csrfmiddlewaretoken=kfGpEA6ZC32Lad9m9uwWZEhElwBGLHPA&Category_IDCategory=66&DealType=Rent&Title=kkjkj&Price=78&Description=kjjk&save=Save
如果我退出并点击保存按钮,它会将我引导至主页,因为我提供的是表单,但数据库中仍然没有新产品。
问题看起来与用户和csrf有关,但即使我搜索到了需要你的帮助,仍然无法找出确切的问题。
models.py
class Product(models.Model):
DealType_Choice = (
("Sale", "Sale"),
("Rent", "Rent"),
("Swap", "Swap"),
("Free", "Free"),
("Announ", "Announ"),
)
DealType = models.CharField(max_length=11, blank=True, choices=DealType_Choice)
Title = models.CharField(max_length=70)
Description = models.TextField(blank=False)
Price = models.IntegerField(max_length=11, null=True)
User_IDUser = models.ForeignKey(User)
Category_IDCategory = models.ForeignKey(Category)
PubDate = models.DateField("Publication Data")
def __str__(self):
return self.Title
views.py
def add_product(request):
product_form= ProductForm(request.POST)
if product_form.is_valid():
form=product_form.save(commit=False)
form.User_IDUser= request.user
form.save()
return HttpResponseRedirect('/')
else:
product_form= ProductForm()
return render(request, 'add_productts.html', {'product_form':product_form})
forms.py
class ProductForm(forms.ModelForm):
Category_IDCategory=forms.ModelChoiceField(queryset=Category.objects.all(), label="Category")
DealType=forms.ChoiceField(widget=forms.Select, choices=Product.DealType_Choice, label="DealType")
Title=forms.CharField(label='Title', max_length=70)
Price=forms.IntegerField(min_value=0, label='Price')
Description=forms.CharField(widget=forms.Textarea(), label="Description")
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.form_method = "POST"
self.helper.form_action= "/"
self.helper.layout= Layout(
Field('Category_IDCategory',css_class='input-sm'),
Field('DealType',css_class='input-sm'),
Field('Title',css_class='input-sm'),
Field(PrependedText('Price', 'TL', '.00'),css_class='input-sm'),
Field('Description',css_class='input-sm', rows=5),
FormActions(
Submit('save', 'Save', css_class='btn btn-labeled btn-info'))
)
super(ProductForm, self).__init__(*args, **kwargs)
class Meta:
model=Product
fields= ['Category_IDCategory','DealType', 'Title','Price', 'Description']
模板
{% extends "index.html" %}
{% load crispy_forms_tags %}
{% block content %}
<h1>Add Product</h1>{% csrf_token %}
{% crispy product_form %}
{% endblock %}
urls.py
urlpatterns = patterns('',
...
url(r'^add_product/$', add_product),
...
)
答案 0 :(得分:0)
我认为这是错误的:
self.helper.form_action= "/"
form_action
应该引用add_product函数:
self.helper.form_action= "/add_product/"