向django-registration表单添加额外字段

Gar*_*eys 6 python forms django models django-registration

我有一个名为"组织"的模型,我将其设置为用户配置文件,我希望"组织"模型中的字段显示在注册页面上.如何使用django-registration进行此操作.

# models.py
class Organization(models.Model):
    user = models.ForeignKey(User, unique=True)
    logo = models.ImageField(upload_to='organizations')
    name = models.CharField(max_length=100, null=True, unique=True)

    # more fields below etc.

# settings.py
AUTH_PROFILE_MODULE = 'volunteering.organization'
Run Code Online (Sandbox Code Playgroud)

Sim*_*gwi 6

最简单的方法是[测试django-registration0.8]:

在项目的某个地方,比如组织应用中的forms.py

from registration.forms import RegistrationForm
from django.forms import ModelForm
from models import Organization

class OrganizationForm(forms.ModelForm):
    class Meta:
        model = Organization

RegistrationForm.base_fields.update(OrganizationForm.base_fields)

class CustomRegistrationForm(RegistrationForm):
    def save(self, profile_callback=None):
        user = super(CustomRegistrationForm, self).save(profile_callback=None)
        org, c = Organization.objects.get_or_create(user=user, \
            logo=self.cleaned_data['logo'], \
            name=self.cleaned_data['name'])
Run Code Online (Sandbox Code Playgroud)

然后在你的根urlconf [但在正则表达式模式之上,包括registration.urls并假设正则表达式r'^accounts/']添加:

from organization.forms import CustomRegistrationForm

urlpatterns += patterns('',
    (r'^accounts/register/$', 'registration.views.register',    {'form_class':CustomRegistrationForm}),
)
Run Code Online (Sandbox Code Playgroud)

显然,你也可以创建一个自定义后端,但恕我直言这更容易.


Elf*_*erg 2

最好的方法是在您拥有组织的应用程序中创建一个文件(例如“forms.py”),然后执行以下操作:

from registration.forms import RegistrationForm
from forms import *
from models import Organization

class RegistrationFormWithOrganization(RegistrationForm):
    organization_logo = field.ImageField()
    organization_name = field.CharField()

def save(self, profile_callback = None):
    Organization.objects.get_or_create(user = self.cleaned_data['user'],
                                       logo = self.cleaned_data['organization_logo'],
                                       name = self.cleaned_data['organization_name'])

    super(RegistrationFormWithOrganization, self).save(self, profile_callback)
Run Code Online (Sandbox Code Playgroud)

然后在您的基本 URL 中,覆盖现有的注册 URL,并将此表单添加为要使用的表单:

 form organization.forms import RegistrationFormWithOrganization

 url('^/registration/register$', 'registration.views.register', 
     {'form_class': RegistrationFormWithOrganization}),
 url('^/registration/', include('registration.urls')),
Run Code Online (Sandbox Code Playgroud)

请记住,Django 将使用第一个与正则表达式匹配的 URL,因此将匹配您的调用,而不是 django-registration 的调用。它还会告诉注册使用您的表格,而不是它自己的表格。我在这里跳过了很多验证(并且可能还跳过了用户对象的派生......如果是这样,请阅读注册的源代码以查看它来自哪里),但这绝对是获取的正确途径您只需付出最少的努力即可在页面中添加一些内容。