我正在创建 Django 用户注册表单。但是我无法弄清楚为什么 Django 在我提交注册信息时会返回此错误。
IntegrityError : column user_id is not unique
详细地说,[views.py] 的这一部分在错误页面中突出显示。
uasite1 = UserProfile.objects.get_or_create(user=user, name=form.cleaned_data['name'],major=form.cleaned_data['major'],email=form.cleaned_data['email'])
有人可以告诉我发生此错误的原因吗?这是我的代码:
模型.py
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User)
name = models.CharField(max_length=50)
major = models.CharField(max_length=50)
email = models.EmailField()
def __unicode__(self):
return self.name
表格.py
from django.forms import ModelForm
from uasite1.models import UserProfile
from django import forms
from django.contrib.auth.models import User
class RegistrationForm(ModelForm):
username = forms.CharField(label=('User Name'))
password = forms.CharField(label=('Password'), widget=forms.PasswordInput)
password1 = forms.CharField(label=('Verify Password'), widget=forms.PasswordInput)
class Meta:
model = UserProfile
exclude = ('user',)
def clean_username(self):
username = self.cleaned_data['username']
try:
User.objects.get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError("That username is already taken, please select another.")
def clean_email(self):
data = self.cleaned_data['email']
if "@gmail.com" not in data:
raise forms.ValidationError("Must include @gmail.com")
return data
def clean(self):
password = self.cleaned_data['password']
password1 = self.cleaned_data['password1']
if password and password1 and password != password1:
raise forms.ValidationError("The passwords did not match. Please try again.")
return self.cleaned_data
视图.py
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect,HttpResponse
from uasite1.forms import RegistrationForm
from uasite1.models import UserProfile
from django.template import RequestContext
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
def SecondhandRegistration(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/profile/')
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
user = User.objects.create_user(username= form.cleaned_data['username'],email = form.cleaned_data['email'], password = form.cleaned_data['password1'])
user.save()
uasite1 = UserProfile.objects.get_or_create(user=user, name=form.cleaned_data['name'],major=form.cleaned_data['major'],email=form.cleaned_data['email'])
uasite1.save()
return HttpResponseRedirect('/profile/')
else:
return render_to_response('register.html',{'form': form}, context_instance=RequestContext(request))
else:
form = RegistrationForm()
context = {'form': form}
return render_to_response('register.html', context, context_instance=RequestContext(request))