ade desmond
ade desmond

Reputation: 486

Django TypeError at /signup/ create_user() missing 1 required positional argument: 'username'

I am doing according to the django's docs which say:

If your user model defines username, email, is_staff, is_active, is_superuser, last_login, and date_joined fields the same as Django’s default user, you can just install Django's UserManager...

My intentions are i do not want to use username for creating a user, i want to use but an email so when i do that i keep getting this error:

"TypeError at /signup/ create_user() missing 1 required positional argument: 'username'". 

Here is my code:

models.py

from django.db import models
from django.contrib.auth.models import AbstractBaseUser, UserManager


 class User(AbstractBaseUser):
    email = models.EmailField(unique=True, blank=False)
    date_joined = models.DateTimeField(auto_now_add=True)
    is_active = models.BooleanField(default=True)
    is_superuser = models.BooleanField(default=False)

    USERNAME_FIELD = 'email'

    objects = UserManager()

views.py

def signup(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            if form.cleaned_data['password'] != form.cleaned_data['repeat_password']:
                context['form'] = SignUpForm(request.POST)
                context['error'] = 'Passwords did not match'
                return render(request, 'shopapp/signup.html', context)
            else:
                # Creating the user here 
                email = form.cleaned_data['email']
                password = form.cleaned_data['password']
                user = User.objects.create_user(email=email)
                user.set_password(password)
                return HttpResponse('{} {}'.format('User created succesfully', User.objects.all()))

        return HttpResponse('Form is not ok')
    else:
        form = SignUpForm()
        context['title'] = 'Signup'
        context['form'] = form
        return render(request, 'shopapp/signup.html', context)

Upvotes: 0

Views: 3875

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599610

But the bit you quote from the docs explicitly states the UserManager class assumes that you have both username and email fields. Since you don't, you would need to create your own subclass that defines the create_user method but doesn't expect a username parameter.

However, in your code you don't actually need to call this method. The main reason for doing so is that it sets the password; but you actually do that separately anyway. So you could just create the user like a normal model instance:

user = User(email=email)
user.set_password(password)
user.save()

Also note, your validation of passwords should go into the form's clean() method, not the view.

Upvotes: 1

Related Questions