Wednesday, March 20, 2013

Re: 1.5 custom user model: Add User with default UserCreationForm results in "no such table: auth_user"


On Friday, March 1, 2013 2:51:50 AM UTC-5, Russell Keith-Magee wrote:
The good news is that you can still re-use the form logic in those two forms -- a form is just a class, so you can subclass them. If you User model subclasses AbstractUser, all the core fields have the same name and constraints, so all you need to do is redeclare the Meta portion of the class definition (to bind your subclass to your actual User model). This way you get all the logic for password/username checks, and the custom save() methods, but against your own model and field list.

 
This isn't quite enough, unfortunately. I'm not sure if this is a bug, an oversight, or part of the "little more complicated", but UserCreationForm doesn't use the model from Meta:

class UserCreationForm(forms.ModelForm):
[...]
class UserCreationForm(forms.ModelForm):
    def clean_username(self):
        # Since User.username is unique, this check is redundant,
        # but it sets a nicer error message than the ORM. See #13147.
        username = self.cleaned_data["username"]
        try:
            User._default_manager.get(username=username)
        except User.DoesNotExist:
            return username
        raise forms.ValidationError(self.error_messages['duplicate_username'])

Here's what I had to do in addition to adding a Meta override:

from django import forms
from django.contrib import admin
from django.contrib.auth.forms import UserCreationForm, UserChangeForm

from member.models import Member

from django.contrib.auth.admin import UserAdmin

class MemberCreationForm(UserCreationForm):
    def clean_username(self):
        username = self.cleaned_data["username"]
        try:
            # Not sure why UserCreationForm doesn't do this in the first place,
            # or at least test to see if _meta.model is there and if not use User...
            self._meta.model._default_manager.get(username=username)
        except self._meta.model.DoesNotExist:
            return username
        raise forms.ValidationError(self.error_messages['duplicate_username'])

    class Meta:
        model = Member
        fields = ("username",)

class MemberChangeForm(UserChangeForm):
    class Meta:
        model = Member

class MemberAdmin(UserAdmin):
    form = MemberChangeForm
    add_form = MemberCreationForm

admin.site.register(Member, MemberAdmin)

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

No comments:

Post a Comment