Search code examples
djangodjango-formsdjango-users

Extend UserCreationForm for extended User in Django


I extended my django user and need to create a registration form now.

I got most of it figured out but I don't know how to exclude fields I don't need during registration. Right know I see all fields in the registration form.

Here is the code:

models.py

class Artist(Model):
    user = OneToOneField(User, unique=True)
    address = CharField(max_length=50)
    city = CharField(max_length=30)
    ustid = CharField(max_length=14)
    date_of_birth = DateField()
    bio = CharField(max_length=500)
    def __unicode__(self):
        return self.user.get_full_name()

User.profile = property(lambda u: Artist.objects.get_or_create(user=u)[0])

forms.py

class RegistrationForm(UserCreationForm):
    class Meta:
        model = User

    def __init__(self, *args, **kwargs):
        super(RegistrationForm, self).__init__(*args, **kwargs)
        artist_kwargs = kwargs.copy()
        if kwargs.has_key('instance'):
            self.artist = kwargs['instance'].artist
            artist_kwargs['instance'] = self.artist
        self.artist_form = ArtistForm(*args, **artist_kwargs)
        self.fields.update(self.artist_form.fields)
        self.initial.update(self.artist_form.initial)

    def clean(self):
        cleaned_data = super(RegistrationForm, self).clean()
        self.errors.update(self.artist_form.errors)
        return cleaned_data

    def save(self, commit=True):
        self.artist_form.save(commit)
        return super(RegistrationForm, self).save(commit)

How do I exclude fields?


Solution

  • You can't include or exclude fields that are not a member of the meta model.

    What you can do is doing that in each form. In this case the UserCreationForm is extended by the ArtistForm. Just restrict the fields in the form that belong to the right meta model.