Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
- 
        scheduling post request after 2 minutes in djangorestframework?Hello developers I am stuck to post request automatically by using APScheduler in djangoRestFramework each 2 minutes please help to do it main problems is pass request in scheduling job. class LogisticsTruckListView(APIView): def post(self, request): truck_id = request.data.get('truckListId') queryset = LogisticsTruckList.objects.filter(truckListId=truck_id) serializer = LogisticsTruckListSerializer(queryset, many=True) data = serializer.data # get vehicle no vehicle_no = data[0]['vehicle_no'] if vehicle_no: url = "https://track.cxipl.com/api/v2/phone-tracking/doc-latest-location?vehicleNumber="+vehicle_no headers = { "Content-type": "application/json", "authkey": "UB1CNQLKU32LPCFQJ2NGL7YY1E51HYF6" } response = requests.get(url, headers=headers, verify=False) if response.status_code == 200: data = response.json() return Response(data, status=status.HTTP_200_OK) else: return Response(status=status.HTTP_400_BAD_REQUEST) else: return Response(status=status.HTTP_400_BAD_REQUEST) here is my scheduling job code .. def start(): scheduler = BackgroundScheduler() viewSets = LogisticsTruckListViewSet() scheduler.add_job(viewSets.getTrackingDetails(), 'interval', minutes=1, id='tracking_details__001', replace_existing=True) scheduler.start() Help me out soon as possible I want to schedule a task in django rest framework
- 
        Django problem with" python manage.py makemigrations"Hi i'm doing the Mosh Tutorial about Django and when i run the command python manage.py makemigrations i have this in terminal File "C:\Users\Giovanni\PycharmProjects\PyShop\venv\Lib\site-packages\django\db\models \fields\__init__.py", line 1121, in __init__ super().__init__(*args, **kwargs) TypeError: Field.__init__() got an unexpected keyword argument 'max_lenght' (venv) PS C:\Users\Giovanni\PycharmProjects\PyShop> This is my models.py from django.db import models class Product(models.Model): name = models.CharField(max_lenght=255) price = models.FloatField() stock = models.IntegerField() image_url = models.CharField(max_lenght=2083)
- 
        Django: You're accessing the development server over HTTPS, but it only supports HTTP. code 400, message Bad request versionI am trying to access my Django website using python manage.py runserver , which returns me http://127.0.0.1:8000/. However, when I try to access this link using Google chrome, I get this error on chrome This site can’t provide a secure connection 127.0.0.1 sent an invalid On Anaconda prompt, I get this error: Code 400, message Bad request version ('ª') You're accessing the development server over HTTPS, but it only supports HTTP. I notice that Google Chrome always changes my website to http://127.0.0.1:8000/ I am uncertain if this is the issue because. I have been working on the Django project and have been accessing the website on chrome using the same method and there was no issues with it at all. Could it be because of the settings.py configurations that caused the error? import os from pathlib import Path import django_heroku # to host heroku import dj_database_url # to host heroku from decouple import config # to host heroku # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-d44=xloa_ngo&moz%cujtvuqpr7ub)hfbqss6$xnubj031q3!9' # SECURITY WARNING: …
- 
        Group list active item appears 2 times in a listIm writing program that shows static schedule for school organisations and now there is a page of schedule with relevant days-lessons, but the title of the day appears 2 times. Here is a screenshot of my issue: Issue Here is the html code of the page schedule.html {% extends 'app/layout.html' %} {% block body %} <ul class="list-group"> {% for i in subjects %} <li class="list-group-item active" aria-current="true">{{i.day}}</li> <li class="list-group-item " aria-current="true">{{i.title}}</li> {% endfor %} </ul> {% endblock body %} views.py def showSchedule(request, ID): relevant_group = Students.objects.get(id = ID) subjects = relevant_group.students.all().order_by("day") context = {"group": relevant_group, "subjects":subjects} return render(request, "app/schedule.html", context) How to make this blue(active item) Friday appear just 1 time?
- 
        django conditional filteringI have this model of Vehicle: class Vehicle(models.Model): ... driver = models.OneToOneField(Driver, related_name="vehicle", on_delete=models.CASCADE, blank=True, null=True) In my form i want to initialize the queryset of driver so only the driver that have no relations with vehicle appear in list (because its one-to-one relations). So in my forms.__init__: self.fields['driver'].queryset = vendor.drivers.select_related('user').filter(vehicle__isnull=True) but I realize in my edit form (using ModelForm), the driver not initialized in form because i guess, the queryset override it. The initial driver is not vehicle__isnull So what i want is, vehicle__isnull except for this initial driver if there is a driver already. How can I achieve that? Any help would be appreciated.
- 
        Why doesn't models.py get created on running python3 manage.py polls from within a script?I wrote many scripts to help me manage my django projects. One of them, cr_app.py creates a new app: #!/usr/bin/env python3 from subprocess import run def main(): create_app() def create_app(): name = input("The name of the app?\n") run(f"""python3 manage.py startapp {name}""", shell=True) if __name__ == "__main__": main() When I am inside of my virtual envirnment's project directory and, following the tutorial, I run manually python3 manage.py startapp polls then I find models.py already created inside of polls/. But this does not happen when I run cr_app.py and create a new app polls even though I run this script while being in the projects activated virtual environment (although cr_app.py is not, it is located in a different, remote directory). Why so?
- 
        Running django project failing after upgrade to django 3.2.18I upgraded my django project from django 3.0.6 to django 3.2.18. After that I cannot run my project with following command: python -m my_project.manage run server 127.0.0.1:8000 it produces below error message: python.exe: No module named my_project.__main__; 'my_project' is a package and cannot be directly executed However when I run: python manage.py runserver 127.0.0.1:8000 It works perfectly fine. Does anyone has similar issue? I suspected it was related to django app configuration but changes in this field does not help.
- 
        Reverse for 'usecase-details' with no arguments not found. 1 pattern(s) tried: ['usecase\\-details/(?P<ucid>[^/]+)\\Z'] DjangoI have three models user, usecase, and usecase assign: I have two views redirecting to the same page to show the details of the usecase and to assign new users and unassign users: I'm trying to execute the logic of this method: DELETE FROM usecase_assign WHERE usecase_assign.user_email = 'nmbarak'; How can I get the user_email from the template and pass it in the view to delete it? what I tried is to create two views, the first one for showing the usecase details and assign new users, the second one to un-assign and to redirect to the same page. My usecase_assign model: class UsecaseAssign(models.Model): usecase_assign_date = models.DateTimeField(primary_key=True, auto_now_add=True) usecase = models.ForeignKey(Usecase, models.DO_NOTHING) user_email = models.ForeignKey('User', models.DO_NOTHING, db_column='user_email') usecase_role_id = models.CharField(max_length=20) my views: @user_login_required def view_usecase_details(request, ucid): usecase_details = Usecase.objects.filter(usecase_id=ucid).all() usecase_details = usecase_details.prefetch_related("usecaseids") users = User.objects.all() #SELECT user_email FROM usecase_assign WHERE usecase_id LIKE 'NN245'; usecase_assigned = UsecaseAssign.objects.select_related('user_email').values_list('user_email__user_name').filter(usecase_id=ucid) #to show list of users working on uc if request.method=='POST' and 'assignuser' in request.POST: user_email = request.POST['user_email'] userAssignCheck = UsecaseAssign.objects.filter(user_email=user_email, usecase_id=ucid) if userAssignCheck: messages.error(request, "user already added!") return HttpResponseRedirect(reverse('usecase-details', args=[ucid])) else: userAssignObj = UsecaseAssign.objects.create(user_email_id=user_email, usecase_id=ucid) if userAssignObj: messages.success(request, "User was Successfully Assigned with Usecase!") return HttpResponseRedirect(reverse('usecase-details', args=[ucid])) context = {'usecase_details': usecase_details, "users": User.objects.all(), 'usecase_assigned':usecase_assigned, …
- 
        How to use metronic select2 style in django-select2I have a form and i render that in template with django-select2 and also i downloaded one of metronic html templates with css and js files and they have select2 styles in there But select2 its not django-select2 package but i need django-select2 so how can i use their customize on my package? https://preview.keenthemes.com/html/metronic/docs/forms/select2 template.html {% render_field form.contractor_counter|add_class:"form-select" %} thats` how they say i need to use their template of select 2 {# <select class="form-select" data-control="select2" data-placeholder="Select an option">#} {# <option></option>#} {# <option value="1">Option 1</option>#} {# <option value="2">Option 2</option>#} {# </select>#}
- 
        TemplateDoesNotExist at / in pythonanywherewhen i deploy the website to pythonanywhere, it show this Exception. i had checked there was the file but it show (Source does not exist). How can i solve it? i tied 1) add ('learning_logs/templates') to 'DIRS' 2) add (path.join(BASE_DIR, 'templates') to 'DIRS' The problem didnt solve even i tried above solution. Can anyone help? the templates i save in below path: learning_log\learning_logs\templates\learning_logs settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['learning_logs/templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] view.py def index(request): """The home page for Learning Log.""" return render(request, 'learning_logs\index.xhtml')
- 
        DRF - How to generate nested json with serializer?I'm a beginer in DRF and here is a simple illustration of the nested json I want to generate: { "shop_name": "some_text", "shop_intro": "some_text", "swiper_images": [ { "id": "id_num", "swiper_image": "some_url", "swiper_image_alt": "some_text" }, { "id": "id_num", "swiper_image": "some_url", "swiper_image_alt": "some_text" }, { "id": "id_num", "swiper_image": "some_url", "swiper_image_alt": "some_text" } ] } Here is my models.py: from django.db import models class ShopIndexPage(models.Model): shop_name = models.CharField(max_length=128, default="Shop Name") intro_text = models.CharField(max_length=1000, default="Intro Text") def __str__(self): return "Shop text of " + self.shop_name class SwiperImage(models.Model): swiper_image = models.ImageField(upload_to='images/index/swiper-images', default="None") swiper_image_alt = models.CharField(max_length=100, null=True, blank=True) def __str__(self): return self.swiper_image_alt Here is my serializer.py: from rest_framework import serializers from .models import ShopIndexPage, SwiperImage class SwiperImageSerializer(serializers.ModelSerializer): class Meta: model = SwiperImage fields = ['swiper_image', 'swiper_image_alt'] class ShopIndexPageSerializer(serializers.ModelSerializer): swiper_items = SwiperImageSerializer(many=True) class Meta: model = ShopIndexPage fields = ['id', 'shop_name', 'intro_text', 'swiper_items'] Here is my views.py: from .models import ShopIndexPage from .serializers import ShopIndexPageSerializer from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status @api_view(['GET', 'POST']) def index_list(request, format=None): if request.method == "GET": index_queryset = ShopIndexPage.objects.all() serializer = ShopIndexPageSerializer(index_queryset, many=True) return Response(serializer.data) elif request.method == "POST": serializer = ShopIndexPageSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) I got the following error: Got AttributeError when attempting …
- 
        Django Multiselect Filed showing List Index Out Of range Error in WindowI was working with Django and it's throwing an error IndexError: list assignment index out of range and the same code is working fine on Linux production, I used pip install django-multiselectfield for multiselect in Django, I am using this DATA= (('0', 'Small'),('1', 'Medium'),('2', 'Large,) and my field name is clients = MultiSelectField(choices=DATA, null = True, blank= True)this, but this is not working and throwing me list index out of range error on window power shell, please let me know how I can solve this issue.
- 
        Cookies are being sent by Django but not received by frontendI'm attempting to send a cookie to the front end using django middleware. In the middleware I'm seeing that the cookie is getting created and then attached to the response. But once I'm on the frontend (React) I'm not finding the cookies with .get('Set-Cookies') and can't figure out why. Middleware (python) class DeviceCookieMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) new_customer = None if 'device' not in request.COOKIES: new_customer = Customer.objects.create() response['Set-Cookie'] = f'device={new_customer.device}; Max-Age=3600; Secure; HttpOnly; SameSite=None' request.new_customer = new_customer print(response.headers) return response Frontend (Javascript) export async function fetchProductsBySlugs(slugs, setterFunc, startDate, endDate, dateChange) { const [start, end] = parseDates(startDate, endDate) try { const response = await fetch(`${SERVER_ADDRESS}/api/products/products/list/?slugs=${slugs.join(',')}&${datesUrlString(start,end,dateChange)}`); const cookies = response.headers.get('Set-Cookie') console.log(cookies) const products = await response.json(); setterFunc(products); return products; } catch (error) { throw error; } } Things I've Tried: I've looked around and attempted reordering my middleware in Django settings as I've heard that can cause issues based on the order in which it's processed. I've also tried different browsers. Firefox clued me into the fact there was no SameSite setting and that could be the issue. But once I updated that, it still will not appear. I tried using the response.set_cookie() …
- 
        Not Null Constraint Failed in Django DateTime field with auto_now_add=TrueI have a model in which there is datetime field. The structure is similar to the below one class ModelName(models.Model): uid = models.CharField(max_length = 50, default="") ordercreated = models.DateTimeField(auto_now_add = True) So when I am trying to create a entry in this field. Most of the times it is working fine. But sometimes it is throwing a Not Null Constraint Failed error. One more thing to note, more than one entry can be made in this model at the same time as I am using celery. Since, I have set the auto_now_add = True. So I was not expecting this kind of issue on creation.
- 
        Django outputs verbose_name in quotes and parentheses in admin panelMy problem is the following. Code: ... class Meta: verbose_name = 'сайт', verbose_name_plural = '1. Сайт', ... Result: Why Django outputs verbose_name in quotes and parentheses in admin panel?
- 
        Is creating a custom email while extending 1to1 from django's user but not using its own email a bad practice?class Teacher(models.Model): full_name = models.CharField(max_length=90) bio = models.TextField() phone = models.CharField(max_length=16) facebook = models.URLField() twitter = models.URLField() address = models.CharField(max_length=50) image = models.ImageField(default='default_pics/default_teacher.jng', upload_to='teacher_pics') email = models.EmailField(unique=True, null=False) # Using 1-1 with Django's built-in User, instead of creating a custom User user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.full_name This is my teacher model. Now, I know that django's user has an optional email field which I can use but I want to make it required and also unique. I search through the internet and most of it says that if I want to do that I have to create a custom user but imo creating an entire custom user just to accomodate this bit of change is just too much of a hassle. So I create my own email field for the teacher, still take what i need from the built-in user but keep the user's email and teacher's email seperate. Is this bad practice?
- 
        How can I apply VSCode language specific settings to files created in Django projects in virtual environment?When I create django project in virtual environment, language specific settings does not apply to files newly created in the project. Here is relevant part of settings.json: { ... // language specific settings "[html]": { "editor.tabSize": 2, "editor.defaultFormatter": "esbenp.prettier-vscode", }, "[javascript]": { "editor.defaultFormatter": "esbenp.prettier-vscode", "editor.tabSize": 2 }, "[css]": { "editor.suggest.insertMode": "replace", "cSpell.fixSpellingWithRenameProvider": false, "editor.tabSize": 2, }, "[python]": { "editor.tabSize": 4, "editor.insertSpaces": true, "editor.wordBasedSuggestions": false, "editor.formatOnType": true }, ... } Here are the steps that I take when I create project: python -m venv venv . venv/bin/activate pip install django==3.2.18 pip freeze > requirements.txt django-admin startproject TheProject . python manage.py startapp app_1 python manage.py startapp app_2 I add application names to INSTALLED_APPS list, give BASE_DIR / 'templates' for TEMPLATES["DIR"] in settings.py. Then I create an html file : code templates/base.html base.html has 4 spaces for a tab. Trying it without virtual environment didn't work. The setting is properly applied to html files created outside the project: They have 2 spaces for a tab. What is going on? How can I make language specific settings properly applied to files inside django project?
- 
        View class in Django viewsPython always use the DRY approach and also motivates programmers to keep there code DRY. Python also provides support to keep its DRY principle intact. But when we see in API of Django we come across class based view, View which is super class of all the views. But the same View class is defined in two different packages. class django.views.generic.base.View class django.views.View Why? This architecture violates the python DRY principle.
- 
        django library management problem with user modulei have to create library management system where we have to create two different modules first is library where admin can add the book and user module which can issue and return the book in django. how to create two different module and which user we have to take .django provide default auth.user models or we have to create different one. i have to create library management system where we have to create two different modules first is library where admin can add the book and user module which can issue and return the book in django. how to create two different module and which user we have to take .django provide default auth.user models or we have to create different one.
- 
        Prevent creation of new model object if another one was created less than 24 hours ago in DjangoI am trying to prevent a model object to be created, if another one was created say less than 24 hours ago. There is a trick however. This rule does not apply to ALL model objects and will dependent on a set of rule laid out in a different model. To be more specific, if Venue_1 has a RuleModel set to 1, then when creating a new MyModel object the database would check if a previous MyModel object had been created within less than 1 day ago. If true then new MyModel object is not saved, if false MyModel object is saved. However if Venue_2 does not have any rule, then MyModel objects can be created without any time restrictions. After some research on this forum, it looks like I need to override the save function in the model. This is not working at present. Not error message. models.py class Venue(models.Model): name = models.CharField(verbose_name="Name",max_length=100, blank=True) class RuleModel(models.Model): venue = models.ForeignKey(Venue, null = True, blank= True, on_delete=models.CASCADE) points = models.IntegerField(verbose_name="loylaty_points_rule", null = True, blank=True) timestamp = models.DateTimeField(auto_now_add=True) timeframe = models.IntegerField(verbose_name='timeframe during which more points cannot be reclaimed', null=True, blank=True) class MyModel(models.Model): user = models.ForeignKey(UserProfile, blank=True, null=True, on_delete=models.CASCADE) venue = models.ForeignKey(Venue, blank=True, …
- 
        Vue.js does't work in HTML with Django, please assist meThe code run: Here is the code <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Register</title> <!--javascript extensions--> <script src='../static/js/vue.min.js'></script> <script src='../static/js/axios.min.js'></script> <script src="../static/js/jquery-3.6.1.min.js"></script> <!--Css--> <link rel="stylesheet" href='../static/css/home.css'> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Ubuntu&display=swap" rel="stylesheet"> <!--Bootstrap 5--> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/js/bootstrap.bundle.min.js"></script> </head> <body> <div id="register"> <div class="container my-5"> <div class="row justify-content-center"> <div class="col-lg-6"> <div class="card"> <div class="card-body"> <form method="post"> {% csrf_token %} <a href="{% url 'home' %}"> <h2 class="text-center mb-4" style="text-decoration: none; color: black; font-size:2em;"> MoHome </h2> </a> <div class="mb-3"> <label for="username" class="form-label">User Name</label> <input v-bind:value="username" type="text" class="form-control" id="username" required="required"> </div> <h3>{[ 10/2 ]}</h3> <div class="mb-3"> <label for="firstname" class="form-label">First Name</label> <input v-bind:value="firstname" type="text" class="form-control" id="firstname" required="required"> </div> <div class="mb-3"> <label for="lastname" class="form-label">Last Name</label> <input v-bind:value="lastname" type="text" class="form-control" id="lastname" required="required"> </div> <div class="mb-3"> <label for="email" class="form-label">Email</label> <input v-bind:value="email" type="email" class="form-control" id="email" required="required"> </div> <div class="mb-3"> <label for="password" class="form-label">Password</label> <input v-bind:value="password" type="password" class="form-control" id="password" required="required"> </div> <div class="mb-3"> <label for="confirmPassword" class="form-label">Confirm Password</label> <input v-bind:value="confirmPassword" type="password" class="form-control" id="confirmPassword", required="required"> </div> <div class="text-center"> <button type="submit" class="btn btn-primary" v-on:click="register">Register</button> </div> </form> </div> </div> </div> </div> </div> </div> </body> <script> var register = new Vue({ el: '#register', data: { firstname: "", lastname: "", username: "", email: "", password: "", confirmPassword: "", …
- 
        Django Forbidden (CSRF cookie not set.), solve without @csrf_exemptI am getting this error when I call a route in localhost for my django app, http://127.0.0.1:8000/api/calculator/score/. This POST route sends data to a Flask app hosted on aws, and gets back a "score" from there. The route works if I have the decorator @csrf_exempt, but that seems like a bandaid/temporary/bad solution. However, this is the solution that most other similar posts on Stack Overflow suggest. How do I allow the request to process without using @csrf_exempt? I have listed the route in my settings.py like: CSRF_TRUSTED_ORIGINS = [ '<<my flask/amazon url here>>', "http://127.0.0.1:8000", "http://localhost:8000" ] and here is the code for the route in views.py: def post_for_score(request): body_unicode = request.body.decode('utf-8') body_dict = json.loads(body_unicode) flask_url = '<<my flask/amazon url here>>' res = requests.post(flask_url, json=body_dict) if res.status_code == 200: rj = res.json() print("rj: ", rj) return JsonResponse( rj ) else: return JsonResponse({ "error": str(res.content) }) Again, this works with the @csrf_exempt decorator, but I don't want to use that, as it seems unsafe in production. What are other ways to fix the problem?
- 
        How to prevent django fields from being wrapped in a div?If I use the below to generate multiple radio buttons: from django import forms class MCQCollectionForm(forms.Form): user_input = forms.ChoiceField( widget=forms.RadioSelect, label='', choices=enumerate(['option 1', 'option 2']) ) I get: <div id="id_user_input"> <div> <label for="id_user_input_0"><input id="id_user_input_0" name="user_input" required="" type="radio" value="0"> option 1</label> </div> <div> <label for="id_user_input_1"><input id="id_user_input_1" name="user_input" required="" type="radio" value="1"> option 2</label> </div> </div> but I want it to be only the below, nothing else: <label class="user-item"> <input name="user_input" type="radio" ... > <span>Lorem ipsum dolor q1</span> </label> <label class="user-item"> <input name="user_input" type="radio" ... > <span>Lorem ipsum dolor q1</span> </label> is there a simple way to do so without having to use JS and manually make the desired changes?
- 
        Storing access_token and refresh_token in Django from a gapi responseI have an LMS application made with Django REST and Vue.js. To authenticate users, I use Google OAuth2 the following way: on the backend, I use drf-social-oauth2 and Google as my authentication backend on the frontend, I use this wrapper around gapi The way it works is the following: the user clicks on the login button and is redirected to the account selection page in Google which, when completed, returns an access token. The frontend makes a request to an endpoint on the backend which uses the convert-token function provided by drf-social-oauth2 to exchange the Google access token with an in-house token that the frontend can use from then on to authenticate requests. I recently added a Google Classroom integration to my application which makes some requests on the students' behalf to Classroom, which requires using their access tokens. The problem is that with this procedure, I don't actually keep the Google issued token on my backend; I just use it to generate the in-house token. How can I modify the procedure I outlined so that I can keep users' access tokens? I thought I had a plan but apparently it's not quite what I need: I created this model …
- 
        URL in django adminI have problem to display clickable link in django admin panel next to 'icon' field or add help_text witch will be clickable and if i click on it, it must open this 'https://fonts.google.com/icons?icon.set=Material+Icons' website in new window of browther . enter image description here link example : https://fonts.google.com/icons?icon.set=Material+Icons I tried this but nothing happens, it shows just normal models without link and text. **admin.py ** from .models import RaffleGame from django.utils.html import format_html from django.urls import reverse from django.contrib import admin class RaffleGameAdmin(admin.ModelAdmin): 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="{}">{}</a>', url, link_text) link_to_google.short_description = 'Mehr Icons findest du hier' admin.site.register(RaffleGame, RaffleGameAdmin) models.py class RaffleGame(models.Model): class GameStatus(models.TextChoices): scheduled = 'scheduled' announced = 'announced' draw_day = 'draw_day' drawn = 'drawn' finished = 'finished' class IconColor(models.TextChoices): red = 'red' yellow = 'yellow' black = 'black' green = 'green' title = models.CharField(max_length=500, default='PiA-Gewinnspiel', verbose_name='Titel') status = models.CharField(max_length=100, choices=GameStatus.choices, default=GameStatus.scheduled, verbose_name='Status', editable=False) announcement_date = models.DateField(verbose_name='Spiel ankündigen ab') draw_date = models.DateTimeField(verbose_name='Zeitpunkt der Auslosung') finished_date = models.DateField(verbose_name='Gewinner anzeigen bis') icon = models.CharField(max_length=100, default='park', verbose_name='Icon') icon_color = models.CharField(max_length=100, choices=IconColor.choices, default=IconColor.black, verbose_name='Icon Farbe') icon_outlined = models.BooleanField(default=False, verbose_name='Icon outlined') class Meta: db_table = "RaffleGame" def __str__(self): return …