3

我有一个简单的问题。这是我的个人资料:

class Profile(models.Model):

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

我想使用这些字段(来自和模型)创建一个注册表单:UserProfile

  • 用户名
  • 出生
  • 照片

这些字段是必需的。

我怎么做?

get_profile()这个问题的模板是如何工作的?

谢谢 :)

4

1 回答 1

9

设置

你在使用django-profilesdjango-registration项目吗?如果没有,你应该——大部分代码已经为你编写好了。

轮廓

您的用户资料代码是:

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

您是否在 Django 设置中正确设置了此配置文件?如果没有,您应该添加它,替换yourapp您的应用程序名称:

AUTH_PROFILE_MODULE = "yourapp.Profile"

报名表格

django-registration带有一些默认的注册表单,但您指定要创建自己的注册表单。每个Django 表单字段默认为必需,因此您不需要更改它。重要的部分是确保处理现有的注册表单字段并添加配置文件创建。像这样的东西应该工作:

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

把它放在一起

您可以使用默认django-registration模板和视图,但希望将它们传递给您的表单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'),
于 2010-01-06T04:07:52.970 回答