我想在 django 管理界面的字段旁边添加一个文本。

警告需要在运行时在 python 方法中创建。我非常了解 python 和 django ORM,但我不知道如何获取字段旁边的文本。

文字应该是警告。在 clean() 中引发 ValidationError 不是解决方案,因为
用户无法再编辑页面。它应该只是一个警告信息。

最佳答案

您可以为管理员使用自定义 ModelForm 子类,在初始化时为相关字段添加 help_text 属性,并适本地设置样式。

# forms.py

class YourModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(YourModelForm, self).__init__(*args, **kwargs)
        self.fields['field_in_question'].help_text = generate_warning()

# admin.py

class YourModelAdmin(admin.ModelAdmin):
    form = forms.YourModelForm

    # And here you can specify custom CSS / JS which would make
    # `help_text` for that particular field look like a warning.
    # Or you can make it generic--say, style (and maybe reposition w/js) all tags
    # like <span class="warning"> that occur within the help text of any field.

    class Media:
        css = {"all": ("admin_warning.css", )}
        js = ("admin_warning.js", )

关于Django 管理员 : Add text at runtime next to a field,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6304176/

10-10 22:10
查看更多