开发者

Django Extended User Profile Sign Up Form Returns IntegrityError

So, I'm new to Django and this has become a major headache. So I'm trying to create an extended user profile a la the documentation. However, when I attempt to post an entry through the form I receive the following error:

Exception Type: IntegrityError at /signup/ Exception Value: (1062, "Duplicate entry '64' for key 2")

Upon crashing with an Internal Server Error, I notice that a new user with the relevant fields (username, password, first name, last name) is created and so is the profile entry. However the profile entry is devoid of all the information entered, with the exception of the id of the user the profile is ass开发者_如何转开发ociated with. Here is the relevant code:

In 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))

In portalman/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

Could anyone suggest what is going wrong? I would be very grateful!


You can't use:

Fnbuser.objects.create(user=instance)

after the object has already been created with:

newFnbUser.save()

That's why the call to the create method in the QuerySet (objects) will raise IntegrityError.

see doc

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜