我對Django非常陌生,我試圖創建一個註冊表單。這是我的模式的相關部分:Django中的UserCreationForm當存在外鍵時帶有額外字段
class UserProfile(models.Model):
user = models.OneToOneField(User)
university = models.ForeignKey('University')
course_title = models.ForeignKey('Course_Title')
class Meta:
db_table = 'user_profile'
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
post_save.connect(create_user_profile, sender=User)
這是我使用的形式:
from django.contrib.auth.forms import UserCreationForm
from django import forms
from django.contrib.auth.models import User
from shelf.models import University, Course_Title, UserProfile
class RegistrationForm(UserCreationForm):
error_messages = {
'duplicate_email': "A user with that e-mail already exists.",
'email_mismatch': "The two e-mail fields didn't match.",
}
# An e-mail is being used instead of the usual Django username.
username = forms.EmailField(label="E-mail")
username2 = forms.EmailField(label="Confirm E-mail")
university = forms.ModelChoiceField(queryset=University.objects.all(), empty_label="Please choose a university")
course_title = forms.ModelChoiceField(queryset=Course_Title.objects.all(), empty_label="Please choose a course title")
class Meta:
model = User
fields = ("first_name", "last_name", "university", "course_title", "username", "username2")
.
.
.
def save(self, commit=True):
user = super(RegistrationForm, self).save(commit=False)
user.save()
user_profile = UserProfile(user=user, university=self.cleaned_data["university"], course_title=self.cleaned_data["course_title"])
if commit:
user_profile.save()
return user_profile
而且,這是我的觀點:
def index(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
new_user = form.save()
return HttpResponseRedirect("/")
else:
form = RegistrationForm()
return render(request, "shelf/register.html", {'form': form, })
我得到錯誤user_profile.university_id可能不是NULL。我已經看了很多爲什麼發生這種情況,我明白爲什麼會發生。但我似乎無法解決它。
在此先感謝。
太謝謝你了。這工作。我不明白爲什麼這是。我讀過我需要添加此信號處理程序,如果我使用用戶配置文件(向用戶添加字段)。有什麼我可以添加到信號處理程序讓它回來? –