如何在Django中移除FileInput小部件的“Currently:“标签和链接?

gxwragnw  于 2023-01-18  发布在  Go
关注(0)|答案(2)|浏览(135)

我在Django中从一个模型创建了一个ModelForm,模型上有一个ImageField字段。当我在一个模板中呈现表单的信息以编辑它时,它显示如下:

如何删除“当前”标记和链接??

ioekq8ef

ioekq8ef1#

Django Admin使用AdminFileWidget来渲染ImageFields。AdminFileWidget只是从标准的FileInput小部件继承而来,并添加了额外的“当前”属性。因此,只需使用FileInput

from django.db import models
from django import forms

class MyModelAdmin(admin.ModelAdmin):
    formfield_overrides = {
        models.ImageField: {'widget': forms.FileInput },
    }
8xiog9wr

8xiog9wr2#

可以使用forms.FileInput删除Currently:和一个链接。
例如,下面有**Image型号**:

# "models.py"

from django.db import models

class Image(models.Model):
    image = models.ImageField()

    def __str__(self):
        return self.image.url

然后,下面是**Image管理员**:

# "admin.py"

from django.contrib import admin
from .models import Image

@admin.register(Image)
class ImageAdmin(admin.ModelAdmin):
    pass

然后,显示Currently:和一个链接,如下所示:

现在,如果将forms.FileInput赋值给formfield_overrides,如下所示:

# "admin.py"

from django.contrib import admin
from .models import Image
from django import forms

@admin.register(Image)
class ImageAdmin(admin.ModelAdmin): # Here               # Here
    formfield_overrides = {models.ImageField: {"widget": forms.FileInput}}

然后,删除Currently:和一个链接,如下所示:

另外,如果你重写forms.FileInput并将CustomFileInput赋值给formfield_overrides,如下所示。(* </p>可以被移除,因为</p>在Django中是自动添加的):

# "admin.py"

from django.contrib import admin
from .models import Image
from django import forms
from django.utils.html import format_html
from django.db import models
                     # Here
class CustomFileInput(forms.FileInput): 
    def render(self, name, value, attrs=None, renderer=None):
        result = []
        if hasattr(value, "url"):
            result.append(
                f'''<p class="file-upload">
                      Presently: <a href="{value.url}">"{value}"</a><br>
                      Change:'''
            )
        result.append(super().render(name, value, attrs, renderer))
        # result.append('</p>') # Here
        return format_html("".join(result))

@admin.register(Image)
class ImageAdmin(admin.ModelAdmin):                      # Here
    formfield_overrides = {models.ImageField: {"widget": CustomFileInput}}

您可以将Currently:更改为Presently:,如下所示:

相关问题