1👍
You can add a custom widget
class that will extend the default TextInput
widget for Icon fields and adds the icon link next to the text box.
Here is the custom widget class you need to add to your admin.py
file.
#import TextInput class
from django.forms import TextInput
#Custom Widget Class
class IconTextInput(TextInput):
def render(self, name, value, attrs=None, renderer=None):
html = super().render(name, value, attrs, renderer)
return html + ' <a href="https://fonts.google.com/icons?icon.set=Material+Icons&icon.query='+value+'&selected=Material+Icons+Outlined:'+value+':" target="_blank">' + value + '</a>'
In this custom widget class, I have inherited the Django TextInput class and updated the render method as per your need.
Next, You need to add this custom widget class with your RaffleGameAdmin class. You need to import models from django.db before that.
from django.db import models
class RaffleGameAdmin(admin.ModelAdmin):
formfield_overrides = {
models.CharField: {'widget': IconTextInput},
}
...
So here is the full code you need to add on your admin.py file
from django.contrib import admin
from django.db import models
from .models import RaffleGame
from django.utils.html import format_html
from django.forms import TextInput
class IconTextInput(TextInput):
def render(self, name, value, attrs=None, renderer=None):
html = super().render(name, value, attrs, renderer)
return html + ' <a href="https://fonts.google.com/icons?icon.set=Material+Icons&icon.query='+value+'&selected=Material+Icons+Outlined:'+value+':" target="_blank">' + value + '</a>'
class RaffleGameAdmin(admin.ModelAdmin):
formfield_overrides = {
models.CharField: {'widget': IconTextInput},
}
list_display = ('icon', 'link_to_google')
def link_to_google(self, obj):
url = 'https://fonts.google.com/icons?icon.set=Material+Icons'
link_text = 'click me for more info'
return format_html('<a href="{}" target="_blank">{}</a>', url, link_text)
link_to_google.short_description = 'Mehr Icons findest du hier'
admin.site.register(RaffleGame, RaffleGameAdmin)
With this, you will achieve your goal what you wanted.
Also note, I displayed the icon name aside the textfield and when click it will go to specific icon page with dynamic URL. For example if the icon name is home it will go to: https://fonts.google.com/icons?icon.set=Material+Icons&icon.query=home&selected=Material+Icons+Outlined:home:
And here is a screenshot how it will look after implementing the code above.
Please note the browser hover URL it’s dynamic which will open in a new tab when click and works for any valid icon added to the Raffle games
Table.