Antonius Common
Antonius Common

Reputation: 3031

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

Upvotes: 14

Views: 15631

Answers (4)

Hedde van der Heide
Hedde van der Heide

Reputation: 22459

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()

Upvotes: 5

Samuel Martin
Samuel Martin

Reputation:

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

Upvotes: 6

otfrom
otfrom

Reputation: 454

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

Upvotes: 30

S.Lott
S.Lott

Reputation: 391952

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.

Upvotes: 6

Related Questions