-1

I am trying to make a simple user registration form for a django site. Here is the goods

models.py

from django.db import models
from django import forms
from django.conf import settings
from taggit.managers import TaggableManager
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser

class UserManager(BaseUserManager):
    def create_user(self, email, username_input, password=None):
        if not email:
            raise ValueError('Users must have an email address')
        user = self.model(
            email=self.normalize_email(email),
            username=username_input,    
        )
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, username, password):
        user = self.create_user(email,
            password=password,
            username=username,
        )
        user.is_admin = True
        user.save(using=self._db)
        return user

class CustomUser(AbstractBaseUser):
    # Last login, is active, and password are included automatically
    username                        =       models.CharField(max_length=30, blank=False, unique=True, )
    email                           =       models.EmailField(max_length=150, blank=False)
    join_date                       =       models.DateTimeField(auto_now_add=True)

    objects = UserManager()

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email']

class UserForm(forms.Form):
    email                       =           forms.EmailField(max_length=150, required=True)
    username                    =           forms.CharField(max_length=30, required=True)
    password1                   =           forms.CharField(label='Password', widget=forms.PasswordInput(), max_length=30, required=True)
    password2                   =           forms.CharField(label='Password confirmation', widget=forms.PasswordInput(), max_length=30, required=True)

views.py

from django.http import HttpResponse
from django.template import RequestContext, loader
from django.shortcuts import render
from myapp.models import *

def signup(request):
    if request.method == 'POST': # If the form has been submitted...
        if not request.POST['password1'] == request.POST['password2']:
            return HttpResponse("HOLY JESUS BATMAN YOUR PASSWORDS DONT MATCH!")
        form = UserForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            password = request.POST['password1']
            username = request.POST['username']
            email = request.POST['email']
            manager = UserManager()
            manager.create_user(
                email,
                username,
                password,
            )
            return HttpResponse('Huzzah! Success!')
    else:
        form = UserForm() # An unbound form
    return render(request, 'signup.html', {
        'form': form,
    })

Trace

Environment:


Request Method: POST
Request URL: http://10.0.1.25:8000/signup/

Django Version: 1.5.1
Python Version: 2.7.3
Installed Applications:
('django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'taggit',
 'bild',
 'bildloguser')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware')


Traceback:
File "/home/bildlog/virtenv/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  115.                         response = callback(request, *callback_args, **callback_kwargs)
File "/home/user/myapp/myapp/views.py" in signup
  19.                 password,
File "/home/user/myapp/myapp/models.py" in create_user
  13.             username=username_input,    

Exception Type: TypeError at /signup/
Exception Value: 'NoneType' object is not callable

So, I have been pulling my hair out for awhile now, trying all sort of stuff, looking at all sorts of tutorials, and I am still getting the same error. I know its alot, but the thing to focus on I think is the create_user function. Any help would be SUPER appreciated, seeing as this will eventually drive me to insanity.

Thanks

dirtshell
  • 161
  • 2
  • 12

1 Answers1

1

The manager is set when you define the class

class CustomUser(AbstractBaseUser):
    ...
    objects = UserManager()

Then in your view, call CustomUser.objects.create_user().

        CustomUser.objects.create_user(
            email,
            username,
            password,
        )

It is invalid to instantiate a manager in the view, as below.

        manager = UserManager()
        manager.create_user(
            email,
            username,
            password,
        )

See the Django docs on Managers for more information.

Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • Thanks that makes a lot of sense, but when I try your suggestion I get an `type object 'UserManager' has no attribute 'objects'` error. I also updated the code to accurately show the true code (replaced the BildLogUserManager with UserManager). – dirtshell Jul 28 '13 at 02:20
  • Your updated code still instantiates a manager in the view ( `manager = UserManager()`). Don't do this, it's invalid. Nobody will be able to help you if you continue to use that code. – Alasdair Jul 28 '13 at 08:57