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

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-29 07:00:52

问题


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?


回答1:


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



回答2:


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)



回答3:


I'm using Rune Kaagaard's idea above, except I noticed that formsets provide an extra_forms property: django.forms.formsets code

@property
def extra_forms(self):
    """Return a list of all the extra forms in this formset."""
    return self.forms[self.initial_form_count():]

So, sticking with the example above:

formset = MyFormset(instance=myinstance)
user = request.user
for form in formset.extra_forms:
    form.initial['user'] = user.pk

Saves having to test any initial forms, just provide default for extra forms.



来源:https://stackoverflow.com/questions/1500121/django-how-to-set-initial-values-for-a-field-in-an-inline-model-formset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!