Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Meicki Jeldal
Meicki Jeldal
1,446 Points

Django user registration with extra fields from another model? [Help]

So im trying making a user register on my site but the default info Django's creation form asks for isn't enough I would like to get 2 more fields.

A phone number field and a postal code. And they are in a model called Extendeduser.

I've tried a lot of things but im feeling im getting closer every second just need the last bit of help =)

So far I've made 2 forms. One with the user creation and one with the other two fields. (Please note that there are many more fields in the Extendeduser model. but this is the only 2 that is required for registration)

Forms.py

from django import forms
from django.contrib.auth.models import User
from .models import ExtendedUser

class RegisterForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ('username','first_name', 'last_name', 'email')

class ExtendedRegisterForm(forms.ModelForm):
    class Meta:
        model = ExtendedUser
        fields = ('phone_number', 'postal_code')

I've now been trying to display and saving the form but it seems it doesn't want to do that.

Views.py

def register(request):
    if request.method == 'POST':
        register_form = RegisterForm(request.POST, instance=request.user)
        extendedregister_form = ExtendedRegisterForm(request.POST, instance=request.user.profile)
        if register_form.is_valid() and extendedregister_form.is_valid():
            register_form.save()
            extendedregister_form.save()
            return redirect('index')
    else:
        register_form = RegisterForm(instance=request.user)
        extendedregister_form = ExtendedRegisterForm(instance=request.user.ExtendedUser)
    return render(request, 'register.html', {
        'register_form': register_form,
        'extendedregister_form': extendedregister_form
    })

And the error I get is this 'AnonymousUser' object has no attribute '_meta'

So I hope there is a kindly soul that would like to help me in this troubled issue. Also thanks for the help in advance.