python Django Forms,为 request.user 设置一个初始值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/653735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Django Forms, set an initial value to request.user
提问by Antonius Common
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
采纳答案by S.Lott
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.
这将触发此输入的验证,顺便说一句,因此您不能以这种方式提供提示值。
回答by otfrom
If you do this in your view.py instead:
如果您在 view.py 中执行此操作:
form = JobRecordForm( initial={'supervisor':request.user} )
Then you won't trigger the validation.
那么你就不会触发验证。
See http://docs.djangoproject.com/en/dev/ref/forms/api/#dynamic-initial-values
请参阅http://docs.djangoproject.com/en/dev/ref/forms/api/#dynamic-initial-values
回答by S.Lott
An Another solution with Middleware and save rewriting : With middleware solution You can call "request" everywhere.
使用中间件并节省重写的另一种解决方案:使用中间件解决方案您可以在任何地方调用“请求”。
""" Middleware """
"""中间件"""
# 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
""" save Rewrinting """
"""保存重写"""
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
回答by Hedde van der Heide
For a complete answer, here's the CBV solution:
要获得完整的答案,这里是 CBV 解决方案:
class MyFormView(TemplateView, FormMixin):
def get_initial(self):
self.initial.update({'your_field': self.request.user})
return super(MyFormView, self).get_initial()