views:

2305

answers:

3

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
+2  A: 

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.

S.Lott
+6  A: 

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

otfrom
+3  A: 

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