当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《DjangoForms,为request.user设置初始值》经验,为你挑选了4个好方法。

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

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

otfrom.. 30

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

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

然后你不会触发验证.

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



1> otfrom..:

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

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

然后你不会触发验证.

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



2> S.Lott..:

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

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

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



3> 小智..:

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


""中间件"""

    # 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



4> Hedde van de..:

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

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

推荐阅读
牛尾巴2010
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有