How to remove the "Currently:" tag and a link of a FileInput widget in Django?
I made a ModelForm from a Model in Django, the model have an ImageField field on it. When I render the info of the开发者_开发知识库 form in a template for editing it, it show this:
How I can remove the 'Currently' tag and link??
The Django Admin uses AdminFileWidget
to render ImageFields. AdminFileWidget
merely inherits from the standard FileInput
widget and adds the extra "Currently" stuff. So just use FileInput
instead:
from django.db import models
from django import forms
class MyModelAdmin(admin.ModelAdmin):
formfield_overrides = {
models.ImageField: {'widget': forms.FileInput },
}
You can use forms.FileInput to remove Currently:
and a link.
For example, there is Image
model below:
# "models.py"
from django.db import models
class Image(models.Model):
image = models.ImageField()
def __str__(self):
return self.image.url
Then, there is Image
admin below:
# "admin.py"
from django.contrib import admin
from .models import Image
@admin.register(Image)
class ImageAdmin(admin.ModelAdmin):
pass
Then, Currently:
and a link are displayed as shown below:
Now, if assigning forms.FileInput
to formfield_overrides as shown below:
# "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}}
Then, Currently:
and a link are removed as shown below:
In addition, if you override forms.FileInput
and assign CustomFileInput
to formfield_overrides
as shown below. (*</p>
can be removed because </p>
is automatically added in 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}}
You can change Currently:
to Presently:
as shown below:
精彩评论