2

首先是代码:

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

class CommentAdmin(admin.ModelAdmin):
    form    = CommentForm

当我编辑我的评论时,我希望它的类别字段具有我上次保存时选择的初始值。我怎么做?

4

3 回答 3

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

        return f

放置在 CommentAdmin 中的这段代码起到了作用......

编辑:

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

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

或者这段代码放在 CommentForm 中

于 2012-12-06T20:12:04.497 回答
1

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.

于 2012-12-06T18:50:11.177 回答
0

我想有几种方法可以解决这个问题。

这是我之前的做法:

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

重要的部分是将填充的模型对象放入关键字变量实例中。

于 2012-12-06T21:23:03.427 回答