简体   繁体   中英

ModelChoiceField initial value in change form

First the code:

class CommentForm(forms.ModelForm):
    categories = forms.ModelChoiceField(queryset = Category.objects.all(), required = False)

class CommentAdmin(admin.ModelAdmin):
    form    = CommentForm

When I'm editing my comment I'd like it categories field have the initial value of what's been selected when I saved it for the last time. How do I do that?

def get_form(self, *args, **kwargs):
        f = super(CommentAdmin, self).get_form(*args, **kwargs)
        f.base_fields['categories'].initial = 1

        return f

This code placed in CommentAdmin did the trick...

EDIT:

def __init__(self, *args, **kwargs):
        super(CommentForm, self).__init__(*args, **kwargs)

        self.fields['categories'].initial = self.instance.object_id

Or this code placed in CommentForm

You want to have the current model value selected by default in the generated form? If that's the case I think what you are looking for in your view is

form = CommentForm(instance = commentinstance)

Where commentinstance is the instance that you are editing.

(This would be form = CommentForm(request.POST, instance = commentinstance) in case of a POST request)

EDIT :

If you want to do this in the form, you can just provide the instance argument from __init__ , like so:

def __init__(self, *args, **kwargs):
    instance = kwargs.pop('instance', YOUR_DEFAULT_INSTANCE)
    super(CommentForm, self).__init__(instance = instance, *args, **kwargs)

That even leaves the default instance if you do provide one from your view.

I guess there are a few ways to solve this.

Here is how I done before:

class MyForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        if 'ref' in kwargs:
            ref = kwargs['ref']
            item = MyModel.objects.get(pk=ref)
            kwargs['instance'] = item

        super(MyForm, self).__init__(*args, **kwargs)

     class Meta:
         model = MyModel

The important part is to put your populated model object into the keyword variable instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM