Python/Django django-registration add an extra field

老子叫甜甜 提交于 2019-11-28 07:51:46
geompalik

I have figured out a solution to this problem, and I will post it here in case somebody can use it. It's pretty simple, I suppose.

Step 1 Add a new model, which will be a profile, in the models.py:

#models.py
class user_profile(models.Model):
     user=models.ForeignKey(User, unique=True)
     institution=models.CharField(max_length=200)

     def __unicode__(self):
         return u'%s %s' % (self.user, self.institution)

Step 2 Create the form that will use this model:

#forms.py
from registration.forms import RegistrationForm
from django.forms import ModelForm
from Test.models import user_profile

class UserRegForm(RegistrationForm):
    institution=forms.CharField(max_length=200)

Step 3 Create ragbackend.py and define how the data will be saved:

from Test.models import user_profile
from forms import *

def user_created(sender, user, request, **kwargs):
    form = UserRegForm(request.POST)
    data = user_profile(user=user)
    data.institution = form.data["institution"]
    data.save()

from registration.signals import user_registered
user_registered.connect(user_created)

Step 4 Go to urls.py and make the following changes:

import regbackend 
from registration.views import register

url(r'^accounts/register/$', register, {'backend': 'registration.backends.default.DefaultBackend','form_class': UserRegForm}, name='registration_register'),
(r'^accounts/', include('registration.urls')),

Note that you have to put the URLs in that order. Easy to understand why.

Step 5 Now everything works, but you cannot see the information in the admin site. So you have to go to admin.py and add:

#admin.py
from django.contrib.auth.models import User
from Test.models import user_profile
admin.site.unregister(User)
class UserProfileInline(admin.StackedInline):
    model = user_profile

class UserProfileAdmin(UserAdmin):
    inlines = [ UserProfileInline, ]
admin.site.register(User, UserProfileAdmin)

And that's it. Do not forget the syncdb before runserver. I hope this will help someone.

In addition to Garrett's answer, I was getting a "cannot import name register" error with django-registration version 0.8. I believe this is because of class-based views, so update urls.py accordingly:

from django.conf.urls import patterns, include, url
from registration.backends.default.views import RegistrationView
from abby.apps.accounts.forms import UserRegForm

urlpatterns = patterns('',
    url(r'^register/$', RegistrationView.as_view(form_class=UserRegForm)),
)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!