我在我目前正在进行的项目中使用django-newsletter 。我需要从订阅者那里获得一些额外的信息,所以我扩展了模型。但是,当我保存表单时,我收到以下异常:/newsletter/newsletter_subscription.newsletter_id处的 IntegrityError 可能不是 NULL,我将非常感谢帮助解决我面临的问题。
我的模型构造如下:
from django.db import models
from newsletter.models import Subscription
from datetime import datetime
class Subscriber(Subscription):
fname = models.CharField(max_length=100)
lanme = models.CharField(max_length=100)
dob = models.DateField(default=datetime.today)
postcode = models.CharField(max_length=8)
phone = models.CharField(blank=True, max_length=100)
def __unicode__(self):
return self.email
我的表格:
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from myapp.apps.mjnewsletter.models import Subscriber
from newsletter.forms import SubscribeRequestForm
class NewsletterSubForm(forms.ModelForm):
class Meta:
model = Subscriber
exclude = ('user',
'name_field',
'newsletter',
'create_date',
'activation_code',
'subscribed',
'subscribe_date',
'unsubscribed',
'unsubscribe_date')
labels = {
'fname': 'First Name',
'lanme': 'Last Name',
'email_field': 'Email',
'dob': 'Date of Birth',
'postcode': 'Post Code',
'phone': 'Phone',
}
def __init__(self, *args, **kwargs):
super(NewsletterSubForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_method ='post'
self.helper.add_input(Submit('submit', 'Subscribe'))
self.fields.keyOrder = [
'fname',
'lanme',
'email_field',
'dob',
'postcode',
'phone',
]
而我的观点:
from django.http import HttpResponseRedirect
from django.shortcuts import render
from myapp.apps.mjnewsletter.models import Subscriber
from myapp.apps.mjnewsletter.forms import NewsletterSubForm
def subscribe(request):
if request.method =='POST':
form = NewsletterSubForm(request.POST)
if form.is_valid():
fname, lname, email_field, dob, postcode, phone = (form.cleaned_data['fname'],
form.cleaned_data['lanme'],
form.cleaned_data['email_field'],
form.cleaned_data['dob'],
form.cleaned_data['postcode'],
form.cleaned_data['phone'])
subscriber = Subscriber.objects.create(fname=fname,
lanme=lname,
email_field=email_field,
dob=dob,
postcode=postcode,
phone=phone)
subscriber.save()
messages.add_message(request, message.SUCCESS, 'Thank you for subscribing to our newsletter.')
else:
form = NewsletterSubForm()
return render(request, 'mjnewsletter/subscribe.html', {'form': form})