Django Forms,为request.user设置初始值

时间:2009-03-17 10:53:00

标签: python django-forms

是否有某种方法可以使下列成为可能,或者是否应该在其他地方进行?

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

4 个答案:

答案 0 :(得分:30)

如果你在view.py中执行此操作:

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

然后你不会触发验证。

请参阅http://docs.djangoproject.com/en/dev/ref/forms/api/#dynamic-initial-values

答案 1 :(得分:6)

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

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

这将触发此输入BTW的验证,因此您无法以这种方式提供提示值。

答案 2 :(得分:6)

另一个使用中间件并保存重写的解决方案: 使用中间件解决方案您可以在任何地方调用“请求”。


“”“中间件”“”

    # coding: utf-8 
from django.utils.thread_support import currentThread 
_requests = {}

def get_request():
    return _requests[currentThread()]

class GlobalRequestMiddleware(object):
    def process_request(self, request):  
        _requests[currentThread()] = request

“”“保存重新打印”“”

class Production(models.Model):
    creator = models.ForeignKey(User, related_name = "%(class)s_creator")
    creation_date = models.DateTimeField(auto_now_add = True)
    modification_date = models.DateTimeField(auto_now = True)

    def save(self, force_insert = False, force_update = False):

        self.creator = get_request().user
        super(Production, self).save(force_insert = force_insert, force_update = force_update)
        return

答案 3 :(得分:5)

要获得完整的答案,这是CBV解决方案:

class MyFormView(TemplateView, FormMixin):
    def get_initial(self):
        self.initial.update({'your_field': self.request.user})
        return super(MyFormView, self).get_initial()