Django Error ::异常类型:IntegrityError异常值:列user_id不是唯一的

时间:2013-06-10 22:07:30

标签: django django-models django-forms django-views

我不明白我做错了什么!!每次点击提交我都会收到此错误。这是一个简单的注册表单

    Request Method: POST
    Request URL:    http://127.0.0.1:8000/register/
    Django Version: 1.5.1
    Exception Type: IntegrityError
    Exception Value:    
    column user_id is not unique
    Exception Location: /home/xxxx/Desktop/forfte/local/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py in execute, line 362
    Python Executable:  /home/xxx/Desktop/forfte/bin/python
    Python Version: 2.7.3

我的模特::

      from django.db import models
      from django.db.models.signals import post_save
      from django.contrib.auth.models import User


      class Vendor(models.Model):
        user= models.OneToOneField(User)
        def __unicode__ (self):
         return self.user   


     def create_vendor_user_callback(sender, instance, **kwargs):
          vreg, new=Vendor.objects.get_or_create(user=instance)

      post_save.connect(create_vendor_user_callback,User, )

查看::

# Create your views here.
from django.http import HttpResponseRedirect
from django.contrib.auth.models import User
from django.shortcuts import render_to_response
from django.template import RequestContext
from vreg.forms import RegistrationForm
from vreg.models import Vendor
from django.contrib.auth import authenticate

def VendorRegistration(request):
    if request.user.is_authenticated():
        return HttpRequestRedirect('/profile/')
    if request.method=='POST':
        form= RegistrationForm(request.POST)
        if form.is_valid():
            print "i am in"
            print type(form.cleaned_data['emailadd'])
            print type(form.cleaned_data['username'])
            user=User.objects.create_user(username=form.cleaned_data['username'], email= form.cleaned_data['emailadd'], password= form.cleaned_data['password'])
            user.save()
            vreg=Vendor(user=user)
            vreg.save()
            return HttpResponseRedirect('/profile/')
        else:
            return render_to_response('register.html', {'form':form}, context_instance=RequestContext(request))

    else:
        ''' user is not submitting form show them blank registration form'''
        form= RegistrationForm()
        context={'form':form}
        return render_to_response('register.html', context, context_instance=RequestContext(request))

如果我能得到一些帮助,那真是太好了!提前致谢

1 个答案:

答案 0 :(得分:3)

您的表单处理方法会创建用户和匹配的供应商。但是在用户上有一个保存后信号,为该用户创建供应商。这意味着您最终尝试创建两个供应商,而OneToOne字段意味着每个用户一个供应商的唯一关系。

要么摆脱信号,要么从表单处理视图中取出供应商创建代码。