开发者

Profile page getting acess to user object in Django

I have a requirement where I have to register users first via email. So, I went with django-registraton and I managed to integrate tat module into my django project. After a successful login, the page redirects to 'registra开发者_如何转开发tion/profile.html'. I need to get access to the user object which was used in the authentication. I need this object to make changes to a model which holds custom profile information about my users. I have already defined this in my models.py

Here is the URL I am using to re-direct to my template..

url(r'^profile/$',direct_to_template,{'template':'registration/profile.html'}),

So my question is this... after login, the user has to be taken to a profile page that needs to be filled up. Any thoughts on how I can achieve this?


I have set up something similar earlier. In my case I defined new users via the admin interface but the basic problem was the same. I needed to show certain page (ie. user settings) on first log in.

I ended up adding a flag (first_log_in, BooleanField) in the UserProfile model. I set up a check for it at the view function of my frontpage that handles the routing. Here's the crude idea.

views.py:

def get_user_profile(request):
    # this creates user profile and attaches it to an user
    # if one is not found already
    try:
        user_profile = request.user.get_profile()
    except:
        user_profile = UserProfile(user=request.user)
        user_profile.save()

    return user_profile

# route from your urls.py to this view function! rename if needed
def frontpage(request):
    # just some auth stuff. it's probably nicer to handle this elsewhere
    # (use decorator or some other solution :) )
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/login/')

    user_profile = get_user_profile(request)

    if user_profile.first_log_in:
        user_profile.first_log_in = False
        user_profile.save()

        return HttpResponseRedirect('/profile/')

    return HttpResponseRedirect('/frontpage'')

models.py:

from django.db import models

class UserProfile(models.Model):
    first_log_in = models.BooleanField(default=True, editable=False)
    ... # add the rest of your user settings here

It is important that you set AUTH_PROFILE_MODULE at your setting.py to point to the model. Ie.

AUTH_PROFILE_MODULE = 'your_app.UserProfile'

should work.

Take a look at this article for further reference about UserProfile. I hope that helps. :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜