Django表单字段小部件变为隐藏

时间:2016-02-13 10:52:55

标签: python django django-forms django-widget

模型字段将foreign_key链接到另一个具有大量条目的模型。

我决定用简单链接替换foreign_keys的默认选择。

除了字段变得隐藏之外,它还有效!

img

我应该怎么做才能避免这种情况?

admin.py

class SeriesAdmin(ModelLinkAdminFields, admin.ModelAdmin):
    modellink = ['video',]

wdiget_file.py

class ModelLinkWidget(forms.HiddenInput):

    def __init__(self, admin_site, original_object):
        self.admin_site = admin_site
        self.original_object = original_object
        super(ModelLinkWidget,self).__init__()


    def render(self, name, value, attrs=None):
        if self.original_object is not None:
            change_url = urlresolvers.reverse('admin:%s_%s_change' % 
                                              (type(self.original_object)._meta.app_label, 
                                               type(self.original_object)._meta.object_name.lower()),
                                              args=(self.original_object.id,))
            return mark_safe('<a id="%s" name="{name}" href="%s">%s</a>' % 
                             (attrs['id'], change_url , escape(self.original_object)))
        else:
            return None

class ModelLinkAdminFields(object):
    def get_form(self, request, obj=None, **kwargs):

        form = super(ModelLinkAdminFields, self).get_form(request, obj, **kwargs)

        if hasattr(self, 'modellink'):
            for field_name in self.modellink:
                if field_name in form.base_fields:
                    form.base_fields[field_name].widget = ModelLinkWidget(self.admin_site, getattr(obj, field_name, ''))
        return form

1 个答案:

答案 0 :(得分:1)

您的小部件会覆盖forms.HiddenInput

你应该使用正确的小部件,我认为这应该是Select,但有other options available