[英]Django Crispy form will not save/submit
我無法使“提交”與crisp-froms一起使用。 帶有引導程序的普通django形式可以正常工作。 我已經嘗試了所有可以找到的教程,但目前無法找到代碼的問題。
單擊sumbit時,它將打開我的客戶概述頁面,但未添加任何新客戶。 此處未顯示所有字段,但所有字段設置均設置為允許空值。
我的models.py
from django.db import models
from django.utils.encoding import smart_unicode
class CustomerType(models.Model):
customer_type = models.CharField(max_length=120, null=True, blank=True)
timestamp_created = models.DateTimeField(auto_now_add=True, auto_now=False)
timestamp_updated = models.DateTimeField(auto_now_add=False, auto_now=True)
def __unicode__(self):
return smart_unicode(self.customer_type)
class Customer(models.Model):
customer_type = models.ForeignKey(CustomerType, null=True, blank=True)
customer_name = models.CharField(max_length=120, null=True, blank=True)
我的views.py
def customercrispy(request):
form = ExampleForm()
return render_to_response("customer-crispy.html",
{"example_form": form},
context_instance=RequestContext(request))
我的forms.py
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Fieldset, ButtonHolder, Submit, Div, Field
from crispy_forms.bootstrap import TabHolder, Tab, FormActions
from .models import Customer
class CustomerAddForm(forms.ModelForm):
class Meta:
model = Customer
class ExampleForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ExampleForm, self).__init__(*args, **kwargs)
self.helper = FormHelper(self)
self.helper.form_method = 'post'
self.helper.form_action = '/customeroverview/'
self.helper.add_input(Submit('submit', 'Submit'))
class Meta:
model = Customer
編輯:打開表單時,CMD輸出
[08/Oct/2014 12:45:12] "GET /customercrispy/ HTTP/1.1" 200 11203
[08/Oct/2014 12:45:12] "GET /customercrispy/static/js/ie-emulation-modes-warning.js HTTP/1.1" 404 3118
[08/Oct/2014 12:45:12] "GET /assets/js/ie10-viewport-bug-workaround.js HTTP/1.1" 404 3079
保存時的CMD輸出
[08/Oct/2014 12:46:52] "POST /customeroverview/ HTTP/1.1" 200 5129
[08/Oct/2014 12:46:52] "GET /customeroverview/static/js/ie-emulation-modes-warning.js HTTP/1.1" 404 3124
[08/Oct/2014 12:46:52] "GET /assets/js/ie10-viewport-bug-workaround.js HTTP/1.1" 404 3079
您的看法不正確。 目前,您僅創建並渲染表單。 發布表單后,什么也沒做,只是再次呈現。 因此,如果是POST,請檢查該表單是否有效並保存。 這樣就可以使它類似於:
def customercrispy(request):
if request.method == 'POST':
form = ExampleForm(request.POST)
if form.is_valid():
form.save()
return redirect('customercripsy') # name of view stated in urls
else:
form = ExampleForm()
return render_to_response("customer-crispy.html",
{"example_form": form},
context_instance=RequestContext(request))
這也避免了將“ / customeroverview /”設置為表單操作。 如果您確實要發布到此URL,則將customeroverview
視圖添加到您的問題中。 順便說一句,我建議您使用Django的reverse
功能創建您的網址。 ( https://docs.djangoproject.com/en/dev/ref/urlresolvers/#reverse )。
您視圖中有關模型形式的更多文檔: https : //docs.djangoproject.com/en/dev/topics/forms/modelforms/#using-a-model-formset-in-a-view
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.