str' object has no attribute

时间:2019-03-06 11:40:41

标签: python django django-2.1

when i want to create a new user i got this error

Exception Value:    
'str' object has no attribute 'get'

here is a full code of view.py

    from .forms import LoginForm, RegisterForm
    from django.shortcuts import render, redirect
    from django.contrib.auth import authenticate, login, get_user_model
    from django.http import HttpResponse
    def register_page(request):
        signup_form = RegisterForm(request.POST or None)
        context = {"signup_form": signup_form}
        if signup_form.is_valid():
            print(signup_form.cleaned_data)
            username = signup_form.cleaned_data.get("username")
            email = signup_form.cleaned_data.get("email")
            password = signup_form.cleaned_data.get("password")
            new_user = user.objects.create_user(username, email, password)
            print(new_user)
        return render(request, "auth/signup.html", context)

here is a code of forms.py

class RegisterForm(forms.Form):
    username = forms.CharField(widget=forms.TextInput(
        attrs={"class": "form-control","placeholder": "your username"}))
    email = forms.CharField(widget=forms.EmailInput(
        attrs={'class': 'form-control',"placeholder": "your Password"}))
    password = forms.CharField(widget=forms.PasswordInput(
        attrs={'class': 'form-control',"placeholder": "your Password"}))
    password2 = forms.CharField(label='Confirm possword', 
    widget=forms.PasswordInput(attrs={'class': 'form-control',
    "placeholder": "your Password"}))
    def clean(self):
        data = self.cleaned_data
        username = self.cleaned_data.get('username')
        qs = user.objects.filter(username=username)
        if qs.exists():
            raise forms.ValidationError('username already exists')
        return username
        email = self.cleaned_data.get('email')
        qs = user.objects.filter(email=email)
        if qs.exists():
            raise forms.ValidationError('email already exists')
        return email
        password = self.cleaned_data.get('password')
        password2 = self.cleaned_data.get('password2')
        if password2 != password:
            raise forms.ValidationError("Password must be matched")
        return data

here is all the code now please help to to solve this error. but when i remove validation from email fields the code run successfully

1 个答案:

答案 0 :(得分:1)

return email行是否有错?您有两次return

qs = user.objects.filter(email=email)
if qs.exists():
    raise forms.ValidationError('email already exists')
return email # <--- THIS LINE!
password = self.cleaned_data.get('password')
password2 = self.cleaned_data.get('password2')
if password2 != password:
   raise forms.ValidationError("Password must be matched")
return data

这可能是您的问题,因为您返回的是一个字符串,而不是clean()方法期望的对象。