Home > Back-end >  None typeobject in success_url django
None typeobject in success_url django

Time:10-31

I have a user registration form as shown by the code below. The error occurs once the form has been submitted and the row is successfully added in the database.

views.py

class UserCreateView(CreateView):
    form_class = UserCreateForm
    model = User
    template_name = 'internethq/user_form.html'
    success_url = '/internethq/login'

forms.py

class UserCreateForm(UserCreationForm):
    first_name = forms.CharField(required=True)
    last_name = forms.CharField(required=True)
    email = forms.EmailField(required=True)

    class Meta:
        model = User
        fields = [
            'first_name',
            'last_name',
            'username',
            'email',
            'password1',
            'password2'
        ]

    def clean_password1(self):
        exp = re.compile("^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$")
        if exp.match(self.cleaned_data['password1']):
            return self.cleaned_data['password1']
        else:
            raise ValidationError('Must contain one uppercase letter, one lowercase letter, one number and one special character.')
    
    def save(self, commit = True):
        user = super().save(commit = False)

        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        user.email = self.cleaned_data['email']

        if commit:
            user.save()

The Error

Internal Server Error: /internethq/signup/

AttributeError at /internethq/signup/ 'NoneType' object has no attribute '__dict__'  Traceback (most recent call last): 

bit of trimming here...


File "/home/togi/atollaviation/env/lib/python3.6/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) 
File "/home/togi/atollaviation/env/lib/python3.6/site-packages/django/python3.6/site-packages/django/views/generic/edit.py", line 113, in get_success_url url = self.success_url.format(**self.object.__dict__)

I thought success_url looked correct but is there an error I'm missing?

This codes runs fine in the development server.

Thanks for your help.

CodePudding user response:

You need to return the created object from the Form.save method

class UserCreateForm(UserCreationForm):
    
    ...
    
    def save(self, commit = True):
        user = super().save(commit = False)

        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        user.email = self.cleaned_data['email']

        if commit:
            user.save()
        return user

The returned object is used in a lot of places, including the generic form handling views. It's often just to return the created object, sometimes it's to alter the object before saving, similar to below

obj = form.save(commit=False)
obj.attr = value
obj.save()
  • Related