After a user signs up, the following IntegrityError is displayed:
IntegrityError at /users/signup
(1062, "Duplicate entry '1' for key 2")
Even though the user gets an error, he can log in regularly. The User gets created, along with the UserProfile.
Here is the /users/signup view that causes the error:
def signup(request):
signup_form = SignupForm(request.POST)
#goal = request.POST.get('goal')
goal = None
if signup_form.is_valid():
username = signup_form.cleaned_data['username']
email = signup_form.cleaned_data['email']
password = signup_form.cleaned_data['password']
user = User.objects.create_user(username, email, password)
user = authenticate(username=username, password=password)
login(request, user)
return HttpResponseRedirect("/")
else:
return render_to_response("authorize.html", {'signup_form': signup_form, 'goal': goal}, context_instance=RequestContext(request))
Here is my /user/models.py:
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from main.models import Goal
class UserProfile(models.Model):
user = models.OneToOneField(User)
joined_goals = models.ManyToManyField(Goal, related_name="joined_goals")
followingGoals = models.ManyToManyField(Goal, related_name="following_goals")
def __unicode__(self):
return self.user.username
def get_goals(self):
try:
goals = Goal.objects.filter(user=self.user)
return goals
except Goal.DoesNotExist:
return []
def create_user_profile(sender, instance, created, **kwargs):
if created:
userProfile = UserProfile.objects.create(user=instance)
post_save.connect(create_user_profile, sender=User)
I’ve dropped all of the tables in my MySQL database multiple times and run python manage.py syncdb, but I still get the same error everytime after creating a new user.
Edit: I do not get this error on my localhost, only on my remote host. I use sqlite on my localhost and mysql on my remote host.
I’m going to take a guess and suggest it could be your post_save signal being registered multiple times as a result of the models.py being loaded more than once. You aren’t registering your signal in a safe manner. Maybe its trying to create the profile more than once rapidly on save() and getting the error.
Take a look at the docs on Preventing Duplicate Signals
Try changing the last line to something like:
Having the dispatch uid will cause it only to be registered once, even if its called many times as a result of imports.