Итак, я новичок в Django, и это стало большой головной болью. Поэтому я пытаюсь создать расширенный профиль пользователя в виде документации. Однако, когда я пытаюсь опубликовать запись через форму, я получаю следующую ошибку:
Тип исключения: IntegrityError в / signup / Значение исключения: (1062,
«Дублирующая запись« 64 »для ключа 2»)
При падении с Внутренней ошибкой сервера я замечаю, что создается новый пользователь с соответствующими полями (имя пользователя, пароль, имя, фамилия), как и запись профиля. Однако в записи профиля отсутствует вся введенная информация, за исключением идентификатора пользователя, с которым связан профиль. Вот соответствующий код:
В views.py:
from django.shortcuts import render_to_response
from django.template import RequestContext
from portalman.models import FnbuserForm, AuthUserForm, Fnbuser
from django.http import HttpResponseRedirect
from django.core.context_processors import csrf
from django.db import IntegrityError
from django.utils.safestring import mark_safe
from django.contrib.auth.models import User
def signup(request):
viewParam = {}
errors = None
profileForm = FnbuserForm()
userForm = AuthUserForm()
if request.method == "POST":
profileForm = FnbuserForm(request.POST)
userForm = AuthUserForm(request.POST)
if userForm.is_valid() and profileForm.is_valid():
newuser = User.objects.create_user(userForm.cleaned_data['username'], userForm.cleaned_data['email'], userForm.cleaned_data['password'])
newuser.first_name = userForm.cleaned_data['first_name']
newuser.last_name = userForm.cleaned_data['last_name']
newuser.save()
newFnbUser = Fnbuser(user = newuser, #other profile elements#)
newFnbUser.save()
return HttpResponseRedirect('/thanks/')
else:
profileForm = FnbuserForm() # An unbound profile form
userForm = AuthUserForm() #An unbound user form
else:
viewParam = {'profileForm': profileForm, 'userForm' : userForm, 'links' : links}
viewParam.update(csrf(request))
return render_to_response('signup.html', viewParam, context_instance=RequestContext(request))
В портале / models.py:
from django.db import models
from django import forms
from django.contrib.auth.models import User, UserManager
from django.db.models.signals import post_save
class Fnbuser(models.Model):
telephone = models.CharField(max_length=20, blank=True, null=True)
additionalNotes = models.TextField(help_text=("Feel free to add additional notes or comments here!"), blank=True,
verbose_name="Notes", null=True)
canCook = models.BooleanField(verbose_name="Can Cook", default=False, blank=True)
canTransport = models.BooleanField(verbose_name="Can Tranport", default=False, blank=True)
canServe = models.BooleanField(verbose_name="Can Serve Food", default=False, blank=True)
canGarden = models.BooleanField(verbose_name="Can Garden", default=False, blank=True)
canProgram = models.BooleanField(verbose_name="Can Program", default=False, blank=True)
canDesign = models.BooleanField(verbose_name="Can Design", default=False, blank=True)
canAlso = models.CharField(verbose_name="Other", max_length=255, blank=True, null=True)
user = models.ForeignKey(User, unique=True)
def __str__(self):
return self.user.username
def create_user_profile(sender, instance, created, **kwargs):
if created:
Fnbuser.objects.create(user=instance)
post_save.connect(create_user_profile, sender=User)
class Meta:
verbose_name = "Food Not Bombs User"
verbose_name_plural = "Food Not Bombs Users"
class AuthUserForm(forms.Form):
username = forms.RegexField(label=("*Username:"), max_length=30, regex=r'^[\w.@+-]+$',
error_messages = {'invalid': ("This value may contain only letters, numbers and @ . + - _ characters."),
'inUse' : ("This username is already in use, try another.")},
help_text = ("Required. 30 characters or fewer. Letters, digits and @ . + - _ only."))
password = forms.CharField(label=("*Password:"), widget=forms.PasswordInput,
help_text = ("Required. 30 characters or fewer. Letters, digits and @ . + - _ only."),
error_messages = {'invalid': ("This value may contain only letters, numbers and @ . + - _ characters.")})
email = forms.CharField(label=("E-Mail Address:"), required=False)
first_name = forms.CharField(label=("First Name:"), required=False)
last_name = forms.CharField(label=("Last Name:"), required=False)
class FnbuserForm(forms.Form):
telephone = forms.CharField(label=("Telephone:"), required=False)
additionalNotes = forms.CharField(label=("Additional Notes about yourself, or general comments."),
widget = forms.widgets.Textarea(), required=False)
canCook = forms.BooleanField(label=("Can Help Cook:"), required=False)
canTransport = forms.BooleanField(label=("Can Help Transport:"), required=False)
canServe = forms.BooleanField(label=("Can Help Serve Food:"), required=False)
canGarden = forms.BooleanField(label=("Can Help Garden:"), required=False)
canProgram = forms.BooleanField(label=("Can Help Program Site:"), help_text=("""If you can help program the site,
note what languages you can program in within the "can also help with" box."""), required=False)
canDesign = forms.BooleanField(label=("Can Help With Design:"), help_text=("""Photography/Video Editing/Web Design/etc. Note
what you can do specifically within the "can also help with" box."""), required=False)
canAlso = forms.CharField(label=("Can Also Help With:"), required=False)
class Meta:
model=Fnbuser
Кто-нибудь может подсказать, что происходит не так? Буду очень признателен!