django registration form custom field

Июнь 1, 2010

In most cases when a user registers in your django application you need to know more than just user name, password and e-mail. To add custom fields to the registration form you should pass form_class parameter to the register view function — it’s easy, but saving additional data could be rather complex. There are solutions that show how to use a custom django registration backend —  http://stackoverflow.com/questions/2601487/django-registration-django-profile-using-your-own-custom-form or http://groups.google.com/group/django-users/browse_thread/thread/00389648750c5867/59eef5c315b47f9b?lnk=raot&pli=1. G! This is so complicated! Likely, django has signals that are sent during the registration process and we can use them — http://docs.b-list.org/django-registration/0.8/signals.html#signals (the version of the doc is 0.8, however, it works with 1.2). We need user_registered signal.

In my case I needed to add just one field to the registration form — user’s City.

from models import City
import strings
from registration.forms import RegistrationForm

class UserRegistrationForm(RegistrationForm):
    city = forms.ModelChoiceField(queryset=City.objects, label=strings.city, empty_label=strings.notDefined)

Then pass this form to the register view in urls.py — register records should go before (r’^accounts/’, include(regUrls)),

from registration.views import register
import registration.backends.default.urls as regUrls
import regbackend

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

Now we need to add a subscription to the user_registered signal. Assume that we have a custom profile with city information:

# regbackend.py
import profile

def user_created(sender, user, request, **kwargs):
	form = UserRegistrationForm(request.POST)
	data = profile.Profile(user=user)
	data.city_id = form.data["city"]
	data.save()

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

That’s it — much easier, right? :)

UPDATE:

I’ve made a really simple and not so well-formed sample application that can be a good starting point in resolving your problems http://dmitko.ru/samples/sample_user_registration.zip
It assumes that you have Python26 folder with installed django 1.2.2 on c:\
There are 2 users: test with password test without city information and test2 with password 1 with city one set in its profile,
You may want to check the settings.py file to setup email settings so that it could send activation letters.
Just launch start.cmd and follow http://127.0.0.1:8000/accounts/register/ and http://127.0.0.1:8000/accounts/login/ links.

tags:
posted in Web by dmitko

Follow comments via the RSS Feed | Оставить комментарий | Trackback URL

42 Comments to "django registration form custom field"

  1. owca wrote:

    I was trying to use your method, but still I’m getting only base User saved, without the aditional data : my post on stackoverflow.

  2. dmitko wrote:

    ok. I’ll check your post and will try to help.

  3. Arno Smit wrote:

    Hi.

    I have been having a few headaches with the new django-registration.

    I have pretty much done the same thing as you have shown above.

    Created the UserRegistrationForm
    made sure the url goes before the other regUrl imports

    altered my regbackend.py to look the same.

    question though. does the user_created function go at the top after all your imports, or does it not matter?

  4. dmitko wrote:

    Here I posted code from the production. user_created function is defined in regbackend.py and there is no other code which I skipped in this post.

    http://stackoverflow.com/questions/3114976/extending-django-registration-using-signals/3124006#3124006

  5. Djangoman wrote:

    How change regexp field in username? Need unicode symbols.

  6. Asinox wrote:

    Hi, i have problem’s with this, i cant understand

    In regbackend.py from where come «profile» ?
    You have a model named «profile» ?

    Im lost

    thanks

  7. Djangoman wrote:

    small error in code
    url(r’^accounts/register/$’, register, {‘backend’: ‘registration.backends.default.DefaultBackend’,'form_class’: UserRegistrationForm}, name=’registration_register’),

    must not default backend, need regbackend

  8. Asinox wrote:

    Thanks, super easy :)

  9. dmitko wrote:

    Guys, sorry I’m on vacation now. As soon as I’m back I’ll answer your questions.

  10. tpm wrote:

    Hi,
    I am new to django/python and I have problems with the regbackend.py. The additional data is not being saved. I posted here:

  11. tpm wrote:

    for some odd reason, the link didn’t work:
    http://stackoverflow.com/questions/3740793/adding-extra-field-to-django-registration-using-signals

    link

  12. dmitko wrote:

    answered

  13. dazzi wrote:

    dmitko, got into a bit of problem on the signal part. Posted on stackoverflow. Great if you could have a look.

    http://stackoverflow.com/questions/3114976/extending-django-registration-using-signals

    Thanks

  14. dazzi wrote:

    dmitko, got into a bit of problem on the signal part. Posted on stackoverflow. Great if you could have a look.

    http://stackoverflow.com/questions/3807551/django-registration-0-8-signal-not-working

    Thanks

  15. dazzi wrote:

    Sorry double post. The first link was a TYPO. Sorry again

  16. dazzi wrote:

    Solved!

  17. eli wrote:

    I tried to create a sample application using the code you provided but could not get it to work.

    I created a test project named sample then created an app called profile

    #####Inside sample/profile/forms.py:

    from models import City
    import strings
    from registration.forms import RegistrationForm

    class UserRegistrationForm(RegistrationForm):
    city = forms.ModelChoiceField(queryset=City.objects, label=strings.city, empty_label=strings.notDefined)

    #####Inside sample/urls.py

    from registration.views import register
    import registration.backends.default.urls as regUrls
    import regbackend

    urlpatterns = patterns(»,
    url(r’^accounts/register/$’, register, {‘backend’: ‘registration.backends.default.DefaultBackend’,'form_class’: UserRegistrationForm}, name=’registration_register’),
    (r’^accounts/’, include(regUrls)),

    )

    #####Inside sample/regbackend.py

    # regbackend.py
    import profile

    def user_created(sender, user, request, **kwargs):
    form = UserRegistrationForm(request.POST)
    data = profile.Profile(user=user)
    data.city_id = form.data["city"]
    data.save()
    from registration.signals import user_registered
    user_registered.connect(user_created)

    ###
    ###What do I put inside sample/profile/models.py ?
    ###I tried putting:
    from django.db import models
    from django.contrib.auth.models import User

    class City(models.Model):
    user = models.ForeignKey(User, unique=True)
    locale = models.CharField(max_length=2)

    ###in settings.py I include registration and profile app

    But I got a bunch of errors. I tried to fix but I am not sure.

    First, ‘import strings’ does not work. Did you mean import string?

    It did not accept the city value above.
    Exception Value:

    ‘module’ object has no attribute ‘city’

    Exception Location: /home/emajic/dm/../dm/account/forms.py in UserRegistrationForm, line 7

    What am I doing wrong? I was hoping you could tell me if my models.py and structure of the other values are correct. A lot of people reference your post, perhaps it would be useful if you included a basic sample app or more code. I spent an entire day trying to do this and reading all the stack overflow posts where people post their issues with extending django registrations but I cannot find any working examples, just those that don’t. I am stumped. Can you please offer a suggestion?

    Thanks!

  18. dmitko wrote:

    will try to upload a sample application during this week or so.

  19. Ask From Octopus » Answers Archive » django-registration creating blank django-profiles using signals wrote:

    [...] here and Shacker’s django-profiles: The Missing Manual and subsequent signals solution by Dmitko and answers here and many [...]

  20. Afrowave wrote:

    Hi Dmitko,

    I have been playing around with your sample-user-registration app. It seems I cannot get it to create a profile from a new registered user. The only thing i have not done is configure the email host. I have set it to local host. Is there a problem with this setup?

  21. dmitko wrote:

    Hi! I don’t think so :) However I did not recieve any feedback from eli. If you send be your app with some configured e-mail account I’ll be able to look at it. Mine was working for me at least.

  22. Afrowave wrote:

    How do I send it to you, by email?

  23. dmitko wrote:

    Yes. kopylovd gmail com

  24. Angel Tiet wrote:

    Hi! Someone in my Myspace group shared this website with us so I came to take a look. I’m definitely loving the information. I’m book-marking and will be tweeting this to my followers! Terrific blog and terrific design and style.

  25. Jeremy Hunt wrote:

    Thank you for the post, your example worked perfectly for me! Not sure why so many comments are indicating problems. very useful

  26. dmitko wrote:

    Good to hear that! Thank you.

  27. Marcin wrote:

    Hi
    I’m trying to use this sample code on my site to enable filling out first_name and last_name. However I’m unable to get those signals (user_registered) correctly handled. Could you please look into it? I’ve asked a question on this on stackoverflow (http://stackoverflow.com/questions/6011512/debugging-django-signals-problems)

    Thanks in advance,
    Marcin

  28. dmitko wrote:

    Hello, have you taken a look at the sample application? http://dmitko.ru/samples/sample_user_registration.zip — I believe that works.

  29. gesk1206 wrote:

    Thanks this really help me understand both extending the user profile AND signals.

  30. dmitko wrote:

    welcome!

  31. Crt wrote:

    First of all — Thank you for this great code, I manage to get it working, what I can’t figure(stupid questions I guess) is how to be able to save first_name and last_name for the user is.

  32. dmitko wrote:

    Can you explain a bit more? Are you talking about some other extra fields like city?

  33. Crt wrote:

    dmitko — Thanks for the prompt response, now is working, I don’t know if there is a better way to do this without touching the files inside registration module.
    Here is what i’ve done, I added the following in registration/backends/default/__init__
    before «return new_user» in def register()

    u = User.objects.get(username=new_user.username)
    u.first_name = kwargs['first_name']
    u.last_name = kwargs['last_name']
    u.save()

  34. dmitko wrote:

    Ok, good to hear that!

  35. beseda.mscom.ru wrote:

    Hi there! Would you mind if I share your blog with my myspace group?

    There’s a lot of folks that I think would really appreciate your content.
    Please let me know. Many thanks

  36. http://www.huntermania.ru wrote:

    I’m curious to find out what blog system you’re working
    with? I’m experiencing some minor security problems with my latest blog
    and I would like to find something more secure. Do you have any recommendations?

  37. декоративные накладки wrote:

    Hello there, You’ve done a fantastic job. I’ll definitely digg
    it and personally suggest to my friends. I am confident they’ll be benefited from this site.

  38. дебетовые карты хоум кредит wrote:

    Thank you for sharing your thoughts. I really appreciate your efforts and I am waiting for your
    further write ups thanks once again.

  39. 5stroi.ru wrote:

    I was pretty pleased to uncover this web site.
    I need to to thank you for your time for this particularly fantastic read!!
    I definitely enjoyed every bit of it and i also have you saved to fav to see new stuff in your blog.

  40. http://bleacherreport.com wrote:

    I like it when folks come together and share ideas.
    Great site, stick with it!

  41. DouglaskamI wrote:

    Добрый день.
    Дайте совет
    Прямо сейчас ищу деньги на покупку машины.
    Где оформить займ в сети?

    icq: 694940086

  42. mobile games wrote:

    Excellent items from you, man. I’ve have in mind your stuff previous to and you are
    just too great. I really like what you have bought here, really like what you’re stating and the best way
    wherein you are saying it. You make it enjoyable and you continue to
    care for to stay it sensible. I can’t wait to read much more from you.
    That is really a great website.

Leave Your Comment

 
Powered by Wordpress and MySQL. Theme by Shlomi Noach, openark.org