注册期间复制密钥oiolates唯一约束

时间:2017-06-23 09:28:07

标签: django

  

重复键值违反了唯一约束" auth_user_username_key"   详细信息:密钥(用户名)=()已存在。

models.py

class Profile(User):
    user = models.OneToOneField(User)
    mobile = models.CharField(max_length=100, null=True, blank=True)
    country_code = models.CharField(max_length=100, null=True, blank=True)
    shipping_street_1 = models.CharField(max_length=100, null=True, blank=True)
    shipping_street_2 = models.CharField(max_length=100, null=True, blank=True)
    shipping_city = models.CharField(max_length=100, null=True, blank=True)
    shipping_state = models.CharField(max_length=100, null=True, blank=True)
    shipping_country = models.CharField(max_length=100, null=True, blank=True)
    shipping_zip = models.CharField(max_length=100, null=True, blank=True)
    shipping_tel = models.CharField(max_length=100, null=True, blank=True)
    billing_street_1 = models.CharField(max_length=100, null=True, blank=True)
    billing_street_2 = models.CharField(max_length=100, null=True, blank=True)
    billing_city = models.CharField(max_length=100, null=True, blank=True)
    billing_state = models.CharField(max_length=100, null=True, blank=True)
    billing_country = models.CharField(max_length=100, null=True, blank=True)
    billing_zip = models.CharField(max_length=100, null=True, blank=True)
    billing_tel = models.CharField(max_length=100, null=True, blank=True)

views.py

class SignUpView(FormView):
    model = models.User
    template_name = "registration/signup.html"
    form_class = forms.SignupForm
    success_url = "/"

    @method_decorator(csrf_exempt)
    def dispatch(self, request, *args, **kwargs):
        return super(SignUpView, self).dispatch(request, *args, **kwargs)

    def form_valid(self, form):
        e = models.User.objects.filter(email=self.request.POST.get("signup_email")).first()
        if e is None:
            user_obj, created = \
                u = models.User.objects.get_or_create(
                email=self.request.POST.get("signup_email"),
                username=self.request.POST.get("signup_email"),
            )
            user_obj.set_password(self.request.POST.get("signup_password"))
            user_obj.save()
            login(self.request, user_obj)

            models.Profile.objects.create(
                user=user_obj,
                mobile=self.request.POST.get("signup_mobile"),
                country_code=self.request.POST.get("signup_country_code")
            )
        return super(SignUpView, self).form_valid(form)

它第一次工作但数据库条目为空。第二次它给出了这个错误。

forms.py

class SignupForm(forms.Form):
    signup_email = forms.EmailField(required=True)
    signup_password = forms.CharField(widget=forms.PasswordInput, required=True)
    signup_confirm_password = forms.CharField(widget=forms.PasswordInput, required=True)
    signup_first_name = forms.CharField(required=True)
    signup_last_name = forms.CharField(required=True)
    signup_country_code = forms.CharField(required=True)
    signup_mobile = forms.CharField()

    def __init__(self, *args, **kwargs):
        super(SignupForm, self).__init__(*args, **kwargs)
        self.fields['signup_email'].widget.attrs.update({'placeholder': "Email"})
        self.fields['signup_password'].widget.attrs.update({'placeholder': 'Password'})
        self.fields['signup_confirm_password'].widget.attrs.update({'placeholder': 'Confirm Password'})
        self.fields['signup_first_name'].widget.attrs.update({'placeholder': "First Name"})
        self.fields['signup_last_name'].widget.attrs.update({'placeholder': "Last Name"})
        self.fields['signup_country_code'].widget.attrs.update({'placeholder': "Country Code"})
        self.fields['signup_mobile'].widget.attrs.update({'placeholder': "Mobile Number"})

    def clean_signup_confirm_password(self):
        if self.cleaned_data.get('signup_password') and self.cleaned_data.get('signup_password'):
            if self.cleaned_data.get('signup_password') != self.cleaned_data.get('signup_confirm_password'):
                raise forms.ValidationError("The two password fields must match.")
        return self.cleaned_data['signup_confirm_password']

1 个答案:

答案 0 :(得分:0)

尝试按照这样的方式编辑视图,

def form_valid(self, form):
    email = form.cleaned_data['signup_email']
    password = form.cleaned_data['signup_password']
    user, created = models.User.objects.get_or_create(username=email, email=email)           
    if created: 
        user.set_password(password)
        user.save()
        models.Profile.objects.create(
            user=user,
            mobile=form.cleaned_data["signup_mobile"],
            country_code=form.cleaned_data["signup_country_code"]
        )
    user_obj = authenticate(username=user.username, password=user.password)
    if user is not None:
        login(self.request, user_obj)            
    return super(SignUpView, self).form_valid(form)