我已閱讀每個「InterityError」+「可能不是NULL」後,仍然無法追查是什麼導致此錯誤。Django IntegrityError signup_simplesubscriber.date_created可能不是NULL
我有一個兩部分註冊表單。第一部分只是選擇一種產品。它將產品ID作爲URL的一部分傳遞到下一頁,在其中輸入個人信息。我可以讓表單正常工作,直到我開始刪除字段 - 我正在使用模型表單 - 因爲某些字段不需要顯示。
這裏是我的模型,和的ModelForm:
class SimpleSubscriber(models.Model):
name = models.CharField(max_length=255)
address = models.CharField(max_length=200)
city = models.CharField(max_length=100)
state = models.CharField(max_length=2)
zipcode = models.CharField(max_length=9)
phone = models.CharField(max_length=10)
email = models.EmailField()
date_created = models.DateTimeField(null=True)
sub_type = models.ForeignKey(Product)
def __unicode__(self):
return self.name
class SubscriberForm(ModelForm):
class Meta:
model = SimpleSubscriber
fields = ('name', 'address', 'city', 'state', 'zipcode', 'phone', 'email', 'sub_type',)#'date_created',
這是我的觀點:
def select_product(request):
title = "get yourself an e-edition. wurd."
pform = Product.objects.order_by('product_active')
if request.method == 'POST': # If the form has been submitted...
pform = ProductForm(request.POST) # A form bound to the POST data
if pform.is_valid(): # All validation rules pass
# ...
return HttpResponseRedirect('signup/%i' % pform.id) # Redirect after POST
else:
form = ProductForm() # An unbound form
return render_to_response('signup/index.html', {'title': title, 'pform': pform}, context_instance=RequestContext(request))
def subscriber_signup(request, product_id):
productchoice = Product.objects.get(id=product_id)
now = datetime.datetime.now()
title = "We need some information."
if request.method == 'POST': # If the form has been submitted...
sform = SubscriberForm(request.POST) # A form bound to the POST data
if sform.is_valid(): # All validation rules pass
sform.date_created = now
sform.sub_type = productchoice
sform.save()
return HttpResponseRedirect('thankyou/') # Redirect after POST
else:
sform = SubscriberForm() # An unbound form
return render_to_response('signup/detail.html', {'title': title, 'sform': sform, 'productchoice': productchoice, 'now': now.date(),}, context_instance=RequestContext(request))
我覺得它有什麼做的的ModelForm,但我很新的,所以我真的不知道。如果我將所有字段添加到SubscriberForm中,則它們會被填寫並且一切正常。但是我不希望用戶在填寫表單時不得不說,所以我把sform.date_created = now並且我希望product_id能夠通過他們在前一頁選擇的選項自動填充。但是如果我從表單中排除這些字段,則會拋出IntegrityError,這對解釋要更改的內容不是很有幫助。
任何提示我搞亂了什麼?
感謝,
太棒了。絕對修復了錯誤。爲什麼commit = False?那是幹什麼的,這些命令的順序很重要?我會假設sform.save(提交= False)必須先去和subscriber.save()持續? – 2012-04-13 20:48:34
表單的保存方法的工作是處理它的數據並返回一個對象。如果您告訴它不要提交,那就意味着它會這樣做,但沒有數據庫同步部分。 – fceruti 2012-04-14 00:26:52