【问题标题】:Edit a django.auth user via ModelForm通过 ModelForm 编辑 django.auth 用户
【发布时间】:2011-12-04 19:12:16
【问题描述】:

我正在尝试通过 ModelForm 使用 django.contrib.auth.models.User 模型创建一个简单的“配置文件编辑”表单。这是我目前拥有的:

表格:

class UserEditForm(ModelForm):
    class meta:
        model = User

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(UserEditForm, self).__init__(*args, **kwargs)

查看:

def edit_user(request, user):
    user = get_object_or_404(User, username__exact = user)

    form = UserEditForm(request.POST or None, request=request, instance=user)

    return render_to_response('forms.html', add_csrf(request, form=form, title='Edit User'), context_instance=RequestContext(request))

从逻辑上讲,这似乎应该可以工作,但是当我加载页面时,用于编辑用户的表单不会显示在我的模板中。我错过了什么?

【问题讨论】:

    标签: django django-models django-authentication


    【解决方案1】:

    Django 已经为此提供了帮助表单;你可以找到in the documentation

    如果您仍想使用自己的,您需要记住登录用户已经是请求的一部分,以便您可以简化视图。由于您已经在使用 RequestContext,因此您无需执行任何其他操作来添加 CSRF 代码 - 只要 CSRF 中间件在您的设置中(正如 U-DON 所指出的那样)。

    from django.contrib.auth.decorators import login_required
    
    @login_required
    def edit(request)
       # This body will only run if the user is logged in
       # and the current logged in user will be in request.user
    
       edit_form = UserEditForm(instance=request.user)
       return render_to_response('forms.html',
                                 {'form':edit_form},
                                 context_instance=RequestContext(request))
    

    【讨论】:

      猜你喜欢
      • 2011-11-16
      • 2012-06-15
      • 2016-08-08
      • 1970-01-01
      • 1970-01-01
      • 2018-05-09
      • 2012-07-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多