简体   繁体   English

改变形式的ModelChoiceField初始值

[英]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... 放在CommentAdmin中的这段代码就是诀窍......

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 或者将此代码放在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. 其中commentinstance是您正在编辑的实例。

(This would be form = CommentForm(request.POST, instance = commentinstance) in case of a POST request) (如果是POST请求form = CommentForm(request.POST, instance = commentinstance)这将是form = CommentForm(request.POST, instance = commentinstance)

EDIT : 编辑

If you want to do this in the form, you can just provide the instance argument from __init__ , like so: 如果你想在表单中这样做,你可以只提供__init__instance参数,如下所示:

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. 如果您从视图中提供一个,则甚至会保留默认instance

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. 重要的是将填充的模型对象放入关键字变量实例中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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