Question

I have a simple question. This is my profile:

class Profile(models.Model):

    user = models.ForeignKey(User, unique=True)
    born = models.DateTimeField('born to')    
    photo = models.ImageField(upload_to='profile_photo')

I want to create a registration form with these fields (from User and Profile models):

  • username
  • first_name
  • last_name
  • born
  • photo

These fields are required.

How do I do that?

How does get_profile() work in a template for this issue?

Thank you :)

Was it helpful?

Solution

Setup

Are you using the django-profiles and django-registration projects? If not, you should—much of this code has already been written for you.

Profile

Your user profile code is:

class Profile(models.Model):
    user = models.ForeignKey(User, unique=True)
    born = models.DateTimeField('born to')    
    photo = models.ImageField(upload_to='profile_photo')

Have you correctly setup this profile in your Django settings? You should add this if not, substituting yourapp for your app's name:

AUTH_PROFILE_MODULE = "yourapp.Profile"

Registration Form

django-registration comes with some default registration forms but you specified you wanted to create your own. Each Django form field defaults to required so you should not need to change that. The important part is just making sure to handle the existing registration form fields and adding in the profile creation. Something like this should work:

from django import forms
from registration.forms import RegistrationForm
from yourapp.models import Profile
from registration.models import RegistrationProfile

class YourRegistrationForm(RegistrationForm):
    born = forms.DateTimeField()
    photo = forms.ImageField()

    def save(self, profile_callback=None):
        new_user = RegistrationProfile.objects.create_inactive_user(username=self.cleaned_data['username'],
        password=self.cleaned_data['password1'],
        email = self.cleaned_data['email'])
        new_profile = Profile(user=new_user, born=self.cleaned_data['born'], photo=self.cleaned_data['photo'])
        new_profile.save()
        return new_user

Bringing it together

You can use the default django-registration templates and views, but will want to pass them your form in urls.py:

from registration.backends.default import DefaultBackend
from registration.views import activate
from registration.views import register

# ... the rest of your urls until you find somewhere you want to add ...

url(r'^register/$', register,
    {'form_class' : YourRegistrationForm, 'backend': DefaultBackend},
    name='registration_register'),
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top