Registration form with profile's field

孤街浪徒 提交于 2019-12-05 04:29:44

问题


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 :)


回答1:


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'),


来源:https://stackoverflow.com/questions/2010653/registration-form-with-profiles-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!