Django Forms,设置一个初始值为request.user [英] Django Forms, set an initial value to request.user

查看:196
本文介绍了Django Forms,设置一个初始值为request.user的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 类JobRecordForm(forms.ModelForm )
supervisor = forms.ModelChoiceField(
queryset = User.objects.filter(groups__name ='Supervisors'),
widget = forms.RadioSelect,
initial = request.user #有没有办法让这个可能?

class Meta:
model = JobRecord


解决方案

您可能希望在您的视图功能中处理此问题。由于您的视图函数必须创建初始窗体,并且您的视图函数知道用户。

  form = JobRecordForm({'supervisor' :request.user})

这将触发此输入的验证,BTW,所以你不能以这种方式提供提示值。


Is there some way to make the following possible, or should it be done elsewhere?

class JobRecordForm(forms.ModelForm):
    supervisor = forms.ModelChoiceField(
        queryset    = User.objects.filter(groups__name='Supervisors'), 
        widget      = forms.RadioSelect,
        initial     = request.user # is there some way to make this possible?
    )    
    class Meta:
        model = JobRecord

解决方案

You might want to handle this in your view function. Since your view function must create the initial form, and your view function knows the user.

form = JobRecordForm( {'supervisor':request.user} )

This will trigger validation of this input, BTW, so you can't provide hint values this way.

这篇关于Django Forms,设置一个初始值为request.user的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆