Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Forms, set an initial value to request.user

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
like image 372
Antonius Common Avatar asked Mar 17 '09 10:03

Antonius Common


2 Answers

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

like image 138
otfrom Avatar answered Nov 04 '22 14:11

otfrom


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.

like image 30
S.Lott Avatar answered Nov 04 '22 15:11

S.Lott