views:

647

answers:

2

I have what I think should be a simple problem. I have an inline model formset, and I'd like to make a select field have a default selected value of the currently logged in user. In the view, I'm using Django's Authentication middleware, so getting the user is a simple matter of accessing request.user.

What I haven't been able to figure out, though, is how to set that user as the default selected value in a select box (ModelChoiceField) containing a list of users. Can anyone help me with this?

A: 

I'm not sure how to handle this in inline formsets, but the following approach will work for normal Forms and ModelForms:

You can't set this as part of the model definition, but you can set it during the form initialization:

def __init__(self, logged_in_user, *args, **kwargs):
    super(self.__class__, self).__init__(*args, **kwargs)
    self.fields['my_user_field'].initial = logged_in_user

...

form = MyForm(request.user)
Not sure how this would work with the inline formset. I'm using inlineformset_factory to create my formset and passing it the form class, not an instance. So I'm not directly instantiating a form object anywhere and don't know how I'd pass it that constructor parameter.
Jeff
Hmmm... I believe ModelForms will take the 'default' value, won't they? And standard form fields use initial as you show, but as far as I know there's no reason to go super() on it.
monkut
A: 

Standard Method

In your view do something like this: (Untested)

formset = ArticleFormSet(initial=[{'logged_on_user': request.user}, ...])

Where 'logged_of_user' is the field name of a single form instance.

See:

http://docs.djangoproject.com/en/dev/topics/forms/formsets/#using-initial-data-with-a-formset

post-POST Method

You can also provide the user data via the request once the data is posted. And apply it in your form processing to whatever models you need.

monkut
Not really what the question is asking. You're using static initial values, and I need to set the initial value to the name of the currently logged in user. What you suggest can't be adapted for dynamic values.
Jeff
Sorry about that, did you see 'using-initial-data-with-a-formset'?
monkut
Yeah, I've looked at that. For some reason it doesn't work in my case. Looks like it's a bug for model formsets: http://code.djangoproject.com/ticket/11006 It's highly unusual that this is proving so difficult. I would think that this is a quite common use case. If all else fails, I could hack something together with JavaScript. :/
Jeff
I think something similar to my question on dynamic fields (http://stackoverflow.com/questions/1409192/auto-generate-form-fields-for-a-form-in-django) could provide a hacky workaround, but javascript would probably be cleaner.
monkut