【问题标题】:Profile page getting acess to user object in Django配置文件页面访问 Django 中的用户对象
【发布时间】:2010-03-18 17:50:47
【问题描述】:

我有一个要求,我必须先通过电子邮件注册用户。所以,我选择了 django-registraton,并设法将 tat 模块集成到我的 django 项目中。 成功登录后,页面重定向到“registration/profile.html”。 我需要访问身份验证中使用的用户对象。 我需要此对象来更改包含有关我的用户的自定义配置文件信息的模型。我已经在我的 models.py 中定义了这个

这是我用来重定向到我的模板的 URL..

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

所以我的问题是......登录后,用户必须被带到需要填写的个人资料页面。 关于如何实现这一目标的任何想法?

【问题讨论】:

    标签: django registration


    【解决方案1】:

    我之前已经设置了类似的东西。就我而言,我通过管理界面定义了新用户,但基本问题是相同的。我需要在第一次登录时显示某些页面(即用户设置)。

    我最终在 UserProfile 模型中添加了一个标志 (first_log_in, BooleanField)。我在处理路由的首页的视图功能中设置了一个检查。这是粗略的想法。

    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
    

    在 setting.py 中设置 AUTH_PROFILE_MODULE 以指向模型很重要。即。

    AUTH_PROFILE_MODULE = 'your_app.UserProfile'
    

    应该可以。

    查看this article 以获取有关 UserProfile 的进一步参考。我希望这会有所帮助。 :)

    【讨论】:

    • 所以您的建议是将这些方法添加到自定义 UserOption 模型中是吗?并更改表单的操作参数以调用例如frontpage rgt?我对 django 有点陌生.. 所以如果你能详细说明.. 会很有用..
    • 我稍微扩展了答案。希望现在更清楚了。 :)
    • 哦抱歉.. 错过了views.py 标题... :P 非常感谢.. 你的帮助最大..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-06
    • 2010-09-30
    • 1970-01-01
    • 2017-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多