0

用户注册后,会显示以下 IntegrityError:

IntegrityError at /users/signup
(1062, "Duplicate entry '1' for key 2")

即使用户收到错误,他也可以定期登录。用户与用户配置文件一起创建。

这是导致错误的 /users/signup 视图:

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

这是我的 /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)

我已多次删除 MySQL 数据库中的所有表并运行 python manage.py syncdb,但每次创建新用户后我仍然会遇到相同的错误。

编辑:我没有在我的本地主机上收到此错误,仅在我的远程主机上。我在本地主机上使用 sqlite,在远程主机上使用 mysql。

4

1 回答 1

1

我将猜测一下,并建议它可能是您的 post_save 信号被多次注册,因为 models.py 被多次加载。您没有以安全的方式注册您的信号。也许它试图在 save() 上多次快速创建配置文件并收到错误。

查看有关防止重复信号的文档

尝试将最后一行更改为:

post_save.connect(create_user_profile, sender=User, 
                    dispatch_uid="user_create_profile")

拥有调度 uid 将导致它只注册一次,即使它由于导入而被多次调用。

于 2012-05-02T04:42:34.303 回答