是否有某种方法可以使下列成为可能,或者是否应该在其他地方进行?
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
如果你在view.py中执行此操作:
form = JobRecordForm( initial={'supervisor':request.user} )
然后你不会触发验证.
见http://docs.djangoproject.com/en/dev/ref/forms/api/#dynamic-initial-values
您可能希望在视图函数中处理此问题.由于您的视图函数必须创建初始表单,并且您的视图函数知道用户.
form = JobRecordForm( {'supervisor':request.user} )
这将触发此输入BTW的验证,因此您无法以这种方式提供提示值.
使用中间件和保存重写的另一个解决方案:使用中间件解决方案您可以在任何地方调用"请求".
""中间件"""
# 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
要获得完整的答案,这是CBV解决方案:
class MyFormView(TemplateView, FormMixin): def get_initial(self): self.initial.update({'your_field': self.request.user}) return super(MyFormView, self).get_initial()