Programming in almost language

This is the site where you may share your knowledge and experience to eachother..

  • Categories

  • LinkedIn

  • Tweet Me

  • My footsteps

django-registration and django-profile save together at once

Posted by Praveen Kumar on April 21, 2009

models.py

class UserProfile(models.Model):

user = models.ForeignKey(User, unique=True, verbose_name=_(‘user’)) gender = models.CharField(_(‘gender’), max_length=10)
dob = models.DateField(_(‘dob’), max_length=10)
city = models.CharField(_(‘res_city’), max_length=30)
pincode = models.IntegerField(_(‘pincode’), max_length = 10)
mobile = models.CharField(_(‘mobile’), max_length = 15)

objects = ProfileManager()

def __unicode__(self):

return u”%s” % self.user

def get_absolute_url(self):

return (‘profiles_profile_detail’, (), { ‘username’: self.user.username })

views.py

def register(request, success_url=None,form_class=RegistrationForm, profile_callback=None,
template_name=’registration/registration_form.html’,
extra_context=None):

pform_class = utils.get_profile_form()
if request.method == ‘POST’:

profileform = pform_class(data=request.POST, files=request.FILES)
form = form_class(data=request.POST, files=request.FILES)
if form.is_valid():

new_user = form.save()
profile_obj = profileform.save(commit=False)
profile_obj.user = new_user

profile_obj.save()

return HttpResponseRedirect(‘/accounts/register/complete/’) #return HttpResponseRedirect(success_url or reverse(‘registration_complete’))

else:

form = form_class()

profileform = pform_class()

if extra_context is None:

extra_context = {}

context = RequestContext(request)

for key, value in extra_context.items():

context[key] = callable(value) and value() or value

return render_to_response(template_name,{‘form’: form,’profileform’:profileform,,context_instance=context)

urls.py

———–

url(r’^accounts/register/$’,register, {‘form_class’: RegistrationForm, ‘profile_callback’:UserProfile.objects.profile_callback},name = ‘registration_register’),

here we are rendering form and profileform to generate fields on registration_form.htm

Advertisements

15 Responses to “django-registration and django-profile save together at once”

  1. What does the following line do?

    objects = ProfileManager()

    Where is ProfileManager defined?

  2. Hi Joseph,
    Creates user profile while registering new user registration/urls.py

    I just write the class for ProfileManager

    class ProfileManager(models.Manager):
    “”” Custom manager for the “Profile“ model. “””
    def profile_callback(self, user):
    “”” Creates user profile while registering new user registration/urls.py “””
    new_profile = Profile.objects.create(user=user,)

    Thanks

  3. Praveen,

    Thank you for clarifying and cleaning up the code.
    I think this can be a useful and well-needed tutorial for many people.
    I am still trying to understand some details:

    When I try to submit my registration, the system just hangs. How can I
    figure out why?

    In views.py, I think the first else clause should correspond to the first if,
    not the second? Otherwise form is not defined if there is no POST.

    Do you mean UserProfile, not Profile, in ProfileManager?

    Do you put ProfileManager in models.py?

    This line needs an extra right curly bracket:
    return render_to_response(template_name,{‘form’: form,’profileform’:profileform,,context_instance=context)

    In urls.py, you need quotes around register.

    Need to add
    from registration.forms import RegistrationForm
    to urls.py and views.py

    In views.py, I would change utils.get_profile_form() to profiles.utils.get_profile_form() for clarity,
    and import profiles.utils

    In registration/registration_form.html, you will need to add:
    {{ profileform.as_p }}
    so that profile information is asked for when you register.

  4. My server hangs on the following line: new_user = form.save()

  5. Hi Joseph, Thanks for appreciation
    Now come to your question

    >> When I try to submit my registration, the system just hangs. How can I
    figure out why?
    I think there would be some thing wrong in your view.py.. that you have to debug line by line..

    >> In views.py, I think the first else clause should correspond to the first if,
    not the second? Otherwise form is not defined if there is no POST.

    Here we are defining the form using POST only

    >>Do you mean UserProfile, not Profile, in ProfileManager?

    yeah i mean UserProfile, not Profile in ProfileManager

    >>Do you put ProfileManager in models.py?

    Yeah, That ProfileManager class inside models.py which is Custom manager for the “UserProfile“ model

    >>This line needs an extra right curly bracket:
    return render_to_response(template_name,{’form’: form,’profileform’:profileform,,context_instance=context)

    yeah, thats was my typing mistake, sorry

    >>In urls.py, you need quotes around register.

    no, that is the function name (not string variable) which we define in views.py which is responsible to register new user

    >>Need to add
    from registration.forms import RegistrationForm
    to urls.py and views.py

    Yeah, other wise we will get an module error

    >>In views.py, I would change utils.get_profile_form() to profiles.utils.get_profile_form() for clarity,
    and import profiles.utils

    In registration/registration_form.html, you will need to add:
    {{ profileform.as_p }}
    so that profile information is asked for when you register.

    thanks for writing the remain code for other’s for more clarification.

  6. Asinox said

    Hi Praveen Kumar, thanks for u nice tutorial.

    Now im trying to follow , and i have this error:

    File “/home/iosira05/lib/python2.5/registration/urls.py”, line 73, in
    url(r’^accounts/register/$’,register, {‘form_class’: RegistrationForm, ‘profile_callback’:UserProfile.objects.profile_callback},name = ‘registration_register’),

    NameError: name ‘UserProfile’ is not defined

    What i have wrong?

    Thanks

  7. Asinox said

    Hi, im sorry with my last comment, my error is this one:

    File “/home/iosira05/lib/python2.5/registration/urls.py”, line 74, in
    url(r’^accounts/register/$’,register, {‘form_class’: RegistrationForm, ‘profile_callback’:UserProfile.objects.profile_callback},name = ‘registration_register’),

    AttributeError: ‘Manager’ object has no attribute ‘profile_callback’

    Thanks

  8. Asinox said

    ejej im sorry man 🙂 im fixed 😀

    Thanks

  9. Any ideas how I would translate this into admin.py under

    def save_model()

    Think I might just need some coffee

  10. Hi Alvin,
    class UserProfileAdmin( admin.ModelAdmin ):
    fields = [ ”, ” ] #depends on
    form = UserProfileAdminForm

    def save_model(self, request, obj, form, change):
    obj.user = “name Here”
    obj.save()

    for more reference
    http://docs.djangoproject.com/en/dev/ref/contrib/admin/#modeladmin-methods
    Thanks
    Praveen

  11. Andy said

    HI Praveen as your post says I have my urls.py as

    from django.conf.urls.defaults import *

    # Uncomment the next two lines to enable the admin:
    from django.contrib import admin
    admin.autodiscover()

    urlpatterns = patterns(”,
    # Example:
    # (r’^xped/’, include(‘xped.foo.urls’)),
    (r’^accounts/’, include(‘registration.backends.default.urls’)),
    # Uncomment the admin/doc line below and add ‘django.contrib.admindocs’
    # to INSTALLED_APPS to enable admin documentation:
    # (r’^admin/doc/’, include(‘django.contrib.admindocs.urls’)),
    #(r’^accounts/’, include(‘xped.newapp.urls’)),
    # Uncomment the next line to enable the admin:
    (r’^admin/’, include(admin.site.urls)),
    (r’^accounts/register/$’,register,{‘form_class’:RegistrationForm,’profile_callback’:UserProfile.objects.profile_callback},name = ‘registration_register’),
    )

    but when I try looking under accounts/register I get this error
    “”
    SyntaxError at /accounts/logout/

    (‘invalid syntax’, (‘/home/andy/src/python/django/xped/../xped/urls.py’, 17, 132, ” (r’^accounts/register/$’,register,{‘form_class’:RegistrationForm,’profile_callback’:UserProfile.objects.profile_callback},name = ‘registration_register’),\n”))

    “”

    Can You help me with this.
    Thanks

  12. Hi Andy, Please avoid copy paste from blog and write yourself. you copied the ( “” ) which is not the correct quotes.
    Regards,
    Praveen.

  13. Andy said

    Hi Praveen,
    I typed the code and don’t have any “” quotes in my urls.
    my urls.py is

    from django.conf.urls.defaults import *

    # Uncomment the next two lines to enable the admin:
    from django.contrib import admin
    admin.autodiscover()

    urlpatterns = patterns(”,
    # Example:
    # (r’^xxxx/’, include(‘xxxx.foo.urls’)),
    (r’^accounts/’, include(‘registration.backends.default.urls’)),
    # Uncomment the admin/doc line below and add ‘django.contrib.admindocs’
    # to INSTALLED_APPS to enable admin documentation:
    # (r’^admin/doc/’, include(‘django.contrib.admindocs.urls’)),
    #(r’^accounts/’, include(‘xxxx.newapp.urls’)),
    # Uncomment the next line to enable the admin:
    (r’^admin/’, include(admin.site.urls)),
    (r’^accounts/register/$’,register,{‘form_class’:RegistrationForm,’profile_callback’:UserProfile.objects.profile_callback}, name=’registration_register’),
    )
    and the error is invalid syntax.
    I posted the same question on google django groups too and this was what I got from there, try the link…it says a space in prof ile_callback which is wrong as i have typed it myslef and havnt made that error…the worry from that post is the name error which is userprofile is not defined.
    can you please check this and provide me with some help…
    http://groups.google.com/group/django-users/browse_thread/thread/d83ad417ded37bb6

  14. Andy said

    Hi Praveen,
    Its been resolved. And sorry for being a pain.
    Thanks

  15. Pankaj Singh said

    Hey after submitting the form I am getting this error

    ‘RegistrationForm’ object has no attribute ‘save’

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: