Is there some way to make the following possible, or should it be done elsewhere?
class JobRecordForm(forms.ModelForm):
supervisor = forms.ModelChoiceField(
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
For a complete answer, here's the CBV solution:
class MyFormView(TemplateView, FormMixin):
def get_initial(self):
self.initial.update({'your_field': self.request.user})
return super(MyFormView, self).get_initial()
If you do this in your view.py instead:
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
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.