Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: How to set initial values for a field in an inline model formset?

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?

like image 722
Jeff Avatar asked Sep 30 '09 19:09

Jeff


People also ask

What is inline formset in Django?

Django formset allows you to edit a collection of the same forms on the same page. It basically allows you to bulk edit a collection of objects at the same time.

How do you exclude a specific field from a ModelForm?

Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.

What is ModelForm in Django?

Django Model Form It is a class which is used to create an HTML form by using the Model. It is an efficient way to create a form without writing HTML code. Django automatically does it for us to reduce the application development time.

How can we make field required in Django?

Let's try to use required via Django Web application we created, visit http://localhost:8000/ and try to input the value based on option or validation applied on the Field. Hit submit. Hence Field is accepting the form even without any data in the geeks_field. This makes required=False implemented successfully.


2 Answers

This does the trick. It works by setting the initial values of all "extra" forms.

formset = MyFormset(instance=myinstance)
user = request.user
for form in formset.forms:
    if 'user' not in form.initial:
        form.initial['user'] = user.pk
like image 96
Rune Kaagaard Avatar answered Oct 13 '22 15:10

Rune Kaagaard


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)
like image 27
Billy Herren Avatar answered Oct 13 '22 15:10

Billy Herren