Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to list a model inside another in Django admin?
Having these models: class Country(models.Model): name = models.CharField(max_length=200) class Company(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) name = models.CharField(max_length=200) class Category(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) name = models.CharField(max_length=200) How to list the companies inside country and add/edit in another page? And the same with Company and Category. -
Concurrency management in django?
not knowing the competition in databases someone told me to be careful not to have a corrupted database I searched a little bit everywhere for information about competition in Django, but I didn't find a favorable answer. Should I be careful about competition when updating the database with a celery task? I have a person who is connected to two different places and uses the same view in Django to change his first name, for example, there is a risk of crashing the database? What are the best ways to manage competition in Django? What should we be aware of? Do you have any documentation a little more precise for in which case we should use it? I take the example I have a task that updates a data in a user's row it contains his first name and a number of users, the user changes his name and the task changes his name or simply the view of Django, now I have an appendix task that will update the number of users that has it. The tasks will it queue up in the database or they'll try to modify the line at the same time. Thank you in advance -
How to reduce the amount of code written when all 'meta' for each view is the same (structure)?
Recently I started refacturing/rewriting my code. I noticed that some parts of my code show alot of similarity, and I'm wondering if I could reduce the amount of code required to get the same functionality. I would like to generate views based on model names I have and give them the same meta attributes where the only difference is the model naming. Currently I have: from finfor import (models, serializers) class clientOrganizationsListCreate(generics.ListCreateAPIView): class meta: queryset = models.clientOrganizations.objects.all() serializer = serializers.clientOrganizationsSerializer class financialSystemsListCreate(generics.ListCreateAPIView): class meta: queryset = models.financialSystems.objects.all() serializer = serializers.financialSystemsSerializer As you can see, the only difference between the two is clientOrganizations <> financialSystems. I have tried the following: from finfor import (models, serializers) from django.apps import apps for model in apps.get_app_config('finfor').models.values(): class f'{model}ListCreate'(generics.ListCreateAPIView): queryset = model.objects.all() serializer_class = serializers[f'{model}Serializer'] and: from finfor import (models, serializers) from django.apps import apps for model in apps.get_app_config('finfor').models.values(): type(f'{model}Serializer', (generics.ListCreateAPIView, ), type('meta', (object, ), { 'queryset': model.objects.all(), 'serializer_class': serializers[f'{model}Serializer'] }) ) I think I'm not using type() properly. Is there a way to generate the classes by iterating a list ['financialSystems', 'clientOrganizations'] or something similiar? -
Use a JWT token auth mechanism from restframework-jwt to access django-admin
i have the following setup: I have Django and vueJS app in a frontend. When user logs in a frontend he gets a jwt and next requests have token in a headers and everything is fine here. But when I point to app which has an admin interface /admin/filer/ It appears that I'm not logined, and i need to login using default login mechanism. Here is my config Even if i send request with signed with jwt - still not works REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', # 'rest_framework.authentication.SessionAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticatedOrReadOnly', ], 'DEFAULT_FILTER_BACKENDS': [ 'django_filters.rest_framework.DjangoFilterBackend' ], 'ORDERING_PARAM': 'sort', } MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'reversion.middleware.RevisionMiddleware', ] JWT_AUTH = { 'JWT_EXPIRATION_DELTA': timedelta(days=7), 'JWT_VERIFY_EXPIRATION':False, 'JWT_REFRESH_EXPIRATION_DELTA': timedelta(days=7), 'JWT_RESPONSE_PAYLOAD_HANDLER': 'apps.auth_module.utils.jwt_response_payload_handler', } -
How to raise error in django model's save instance before storing in database?
I have registered this model into my admin site. What I want to do is that before pressing the save button, I want to validate the email and phone numbers via the 2 validation functions which uses PyPI packages. However, when I enter a invalid email that is non-existent, and then save, the data is still saved in the database. I want to be able to raise an error such that the user will know that he/she entered invalid fields. This is an image of how I am adding data currently: adding data on admin site Here is my code: /* models.py */ import re import phonenumbers from django.db import models from phonenumbers import carrier from validate_email import validate_email from django.core.exceptions import ValidationError class Please(models.Model): emailplus = models.EmailField() country = models.CharField(max_length=2) phone_number = models.CharField(max_length=100) def clean_email(self): email = self.cleaned_data.get("emailplus") if not validate_email(email, check_mx=True, verify=True): raise ValidationError("Invalid email") return email def clean_phone_number(self): phone_number = self.cleaned_data.get("phone_number") clean_number = re.sub("[^0-9&^+]", "", phone_number) alpha_2 = self.cleaned_data.get("country") z = phonenumbers.parse(clean_number, "%s" % (alpha_2)) if len(clean_number) > 15 or len(clean_number) < 3: raise ValidationError( "Number cannot be more than 15 or less than 3") if not phonenumbers.is_valid_number(z): raise ValidationError( "Number not correct format or non-existent") if … -
How can I paginate sql query result in html page?
I need to paginate sql query results from my database in html page. views.py: def test(request): db = MySQLdb.connect(host="localhost", # your host, usually localhost user="pc", # your username passwd="12345678", # your password db="mc") cur = db.cursor() cur.execute('''SELECT * FROM hello left join hell on hello.Id=hell.Id ''') row = cur.fetchone() name = row[1] sur = row[2] id = row[0] context = {"name": name, "sur": sur, "id": id} return render(request, 'test.html', context) test.html: <div class="row"> <div class="col-md-3"> <span style="color:white;font-size:14px">{{ name }}</span> </div> <div class="col-md-3"> <span style="color:white;font-size:14px">{{ sur }}</span> </div> <div class="col-md-3"> <span style="color:white;font-size:14px">{{ id }}</span> </div> <div class="col-md-3"> <span style="color:white;font-size:14px">{{ name }}</span> </div> </div> Per now yes, it just prints out first values from sql query, I'm working on looping through result. I stucked in pagination of this. Because results will be more than 1000 and it's good to display 50 per page. -
How to import a model in a script?
I am new to Django, and I'm trying to import one of my models in a script as we do it in views.py. I'm getting an error: Traceback (most recent call last): File "CallCenter\make_call.py", line 3, in from .models import Campaign ModuleNotFoundError: No module named 'main.models'; 'main' is not a package My file structure is like: MyApp\CallCenter\ CallCenter contains init.py, make_call.py, models.py, views.py and MyApp has manage.py from twilio.rest import Client from twilio.twiml.voice_response import VoiceResponse, Say, Dial, Number, VoiceResponse from .models import Campaign def create_xml(): # Creates XML response = VoiceResponse() campaign = Campaign.objects.get(pk=1) response.say(campaign.campaign_text) return response xml = create_xml() print(xml) -
Deploying a Mezzanine site on DigitalOcean with Fabric - Deploy_tool error
Very relevant question to this one, which sadly has no answers: Deploying mezzanine site on DigitalOcean with Fabric [1xx.xx.xxx.xxx] out: Using base prefix '/usr' [1xx.xx.xxx.xxx] out: New python executable in /home/adm1/.virtualenvs/project/bin/python3 [1xx.xx.xxx.xxx] out: Also creating executable in /home/adm1/.virtualenvs/project/bin/python [1xx.xx.xxx.xxx] out: Installing setuptools, pip, wheel... [1xx.xx.xxx.xxx] out: done. [1xx.xx.xxx.xxx] out: [1xx.xx.xxx.xxx] rsync_project: rsync --exclude "*.pyc" --exclude "*.pyo" --exclude "*.db" --exclude ".DS_Store" --exclude ".coverage" --exclude "local_settings.py" --exclude "/static" --exclude "/.git" --exclude "/.hg" -pthrvz --rsh='ssh -p 22 ' C:\Users\User\Desktop\blog\project\ adm1@1xx.xx.xxx.xxx:/home/adm1/mezzanine/project [localhost] local: rsync --exclude "*.pyc" --exclude "*.pyo" --exclude "*.db" --exclude ".DS_Store" --exclude ".coverage" --exclude "local_settings.py" --exclude "/static" --exclude "/.git" --exclude "/.hg" -pthrvz --rsh='ssh -p 22 ' C:\Users\User\Desktop\blog\project\ adm1@1xx.xx.xx.xxx:/home/adm1/mezzanine/project rsync is not recognized as an internal or external command, executable program or batch file. Fatal error: local() encountered an error (return code 1) while executing 'rsync --exclude "*.pyc" --exclude "*.pyo" --exclude "*.db" --exclude ".DS_Store" --exclude ".coverage" --exclude "local_settings.py" --exclude "/static" --exclude "/.git" --exclude "/.hg" -pthrvz --rsh='ssh -p 22 ' C:\Users\User\Desktop\blog\project\ adm1@1xx.xx.xxx.xxx:/home/adm1/mezzanine/project' Aborting. Disconnecting from 1xx.xx.xxx.xxx... done. This is the above error I get after running "fab create". There seems to be an issue with rsync, and sadly I can't find any information on how to set up Git as the Deploy_tool. All other steps … -
How i can create front that user can create connected tree diagram with drop and drag in python or django?
i want create app in pyqt5 or Django that user can design his own tree diagram with drop and drag class into page , i know about diagram class and ... but i want create app in pyqt5 or Django that allow user to design his diagram and save it on app and again load it to app ! what framework i should use ? -
guys help me cant fix it i have tried many tutorials but they dont work like they showed
my json setting is c:/Users/user/Desktop/hellodjango/myenv4/Scripts/python.exe but when i try to run python manage.py runserver the error is(myenv4) C:\Users\user\Desktop\hellodjango\web_project\src>python manage.py runserver C:\python\Python37-32\python.exe: can't open file 'manage.py': [error] No such file or directory though my path for virtual environment is c:/Users/user/Desktop/hellodjango/myenv4/Scripts/python.exe i have properly installed the django why does this happenenter image description here this is my file -
Django Multiple Forms from differents models
i m quite new with Django but i m stuck since a day on a problem that i can t solve. I have to create forms with a lot of fields. The fields comes from different models and i want to save them all at once. I want to display it with a slick so the user experience will be better and not overwhelmed by the amout of fields to fill. The slick part is not a problem. My problem is to render multiple form separated in different div on the same page. In this i want to display the candidateDetails form not only the candidate one. here my actual code for only one form that is working. The forms : class CandidateApplicationForm(ModelForm): position = forms.ChoiceField(choices=POSITION, widget=forms.RadioSelect) class Meta: model = Candidate fields = ['firstName', 'lastName', 'mailAddress', 'address', 'city', 'country', 'nationality', 'position', ] widgets = { 'firstName': forms.TextInput(attrs={'class': 'input'}), 'lastName': forms.TextInput(attrs={'class': 'input'}), 'address': forms.TextInput(attrs={'class': 'input'}), 'city': forms.TextInput(attrs={'class': 'input'}), 'nationality': forms.TextInput(attrs={'class': 'input'}), 'Type of programme': forms.TextInput(attrs={'class': 'input'}), } class CandidateDetailsForm(ModelForm): class Meta: model = CandidatesDetail fields = ['birthPlace', 'birthDate', 'nationality', ] The Views : class RegisterCandidate: def __init__(self): self.method = None def candidateapply(request): apply = candidateregistrationform.CandidateApplicationForm() if request.method == 'POST': form_candidate … -
What do these arguments mean in swagger_auto_schema (Django)?
The project uses a swagger. There is the following code. @swagger_auto_schema( manual_parameters=[ Parameter('download', IN_QUERY, 'Set `Content-Disposition=attachment` to make browser to download file' 'instead of showing it.', type='bool'), Parameter('share_id', IN_PATH, type='uuid') ], security=[], responses={'400': 'Validation Error (e.g. base64 is wrong)', '200': VideoSerializer} ) Please explain what each argument is responsible for. I read the documentation, but understood little ... Particularly interested in '200': VideoSerializer -
ProgrammingError: 1064 while executing inspectdb with django and mysql database
I have two databases configured in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'password', 'HOST': '127.0.0.1', 'PORT': '5432', }, 'db2': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'database', 'USER': 'user', 'PASSWORD': 'password', 'HOST': 'ip address', 'PORT': 'port', } } The server which hosts db2 uses mysql 4.1.2. I am using Python 3.7.3 + django 2.2.5 + mysqlclient 1.4.4. When I run python manage.py inspectdb --database db2 I get the following error: django.db.utils.ProgrammingError: (1064, "You have an error in your SQL >syntax; check the manual that corresponds to your MySQL server version for >the right syntax to use near 'TABLES' at line 1") I have printed the 'query' and it is: SHOW FULL TABLES I have tried to manually connect to the database (MySQLdb.connect + cursor) and retrieve data from a table and it worked fine. My problem is basically the same as (Error 1064 Django inspectdb), but that guy didn't get any help. Hopefully I will. What I am trying to accomplish is use data from db2 as foreign keys in the default. For example, I have some items described in the default database and some persons defined in db2. I would like to associate a person … -
Heroku aggregate metrics from JSON logs
I have a Django application running on Heroku with json logs outputted to papertrail in the following format (examples): {"message_type":"profile", "method":"a", "runtime":1000, "timestamp: 1570524933} {"message_type":"profile", "method":"b", "runtime":1020, "timestamp: 1570524934} {"message_type":"profile", "method":"a", "runtime":2020, "timestamp: 1570524934} For instance, I want to construct a chart on Grafana that can show the mean runtime of methods a and b across the day but am unsure as to how I can run select or run aggregation functions such as (mean, max, min, etc.) using data from papertrail. So far I have looked at setting up an alert on papertrail for certain log criteria that will then ping Graphite Grafana, however this only gives the summed number of events. Does anyone have any input on this can be achieved? -
how can i use ckeditor feature Real-time collaborative in django
can i use ckeditor feature Real-time collaborative in django ? ckeditor Documentaion Link here -
How To Provide A Class To Fields In A Django Template?
I was working a project on mine, in which I needed to provide a class to a field in form which is a input box, but don't know how to do so. My Template: {% extends 'diary/base.html' %} {% block title %}Register{% endblock title %} {% block content %} {% load staticfiles %} <link rel= "stylesheet" type= "text/css" href = "{% static 'users/register.css' %}"> <div id="login-box"> <div class="left-box"> <h1>Register</h1> <form action="{% url 'register' %}" method="post"> {% csrf_token %} {% for non_field_error in form.non_field_errors %} <p>{{ non_field_error }}</p> {% endfor %} {% for field in form %} {{ field }} {% for error in field.errors %} <p>{{ error }}</p> {% endfor %} {% endfor %} <input type="submit" value="SIGN UP" name="signup-button" class="signup-btn"> </form> </div> <div class="right-box"> </div> </div> {% endblock content %} In this specific part: {% for field in form %} {{ field }} {% for error in field.errors %} I want to provide a class to {{ field }}. I tried this: {{ field(class="txtb") }} This is how I use to provide a class in Flask, but in Django this didn't worked. Any Help Would Be Appreciated! -
Django Storages: use 2 media sources
In my Django APP I use Dropbox API for media files. This are the settings. MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "media") DEFAULT_FILE_STORAGE = 'storages.backends.dropbox.DropBoxStorage' DROPBOX_OAUTH2_TOKEN = 'my_token' DROPBOX_ROOT_PATH = '/my_app/' I want to ADD another storage in Google CDN, keeping Dropbox. Is it possible? Should be something like overriding the DEFAULT_FILE_STORAGE? MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "media") DEFAULT_DROPBOX_STORAGE = 'storages.backends.dropbox.DropBoxStorage' DROPBOX_OAUTH2_TOKEN = 'my_token' DROPBOX_ROOT_PATH = '/my_app/' MEDIA_URL = '/media_2/' MEDIA_ROOT = os.path.join(BASE_DIR, "media_2") DEFAULT_DROPBOX_STORAGE = 'storages.backends.google.GoogleStorage' GOOGLE_OAUTH2_TOKEN = 'my_token' DROPBOX_ROOT_PATH = '/my_app/' I couldn´t find much info about this dual Django Storages use. Any advice welcome! -
Using celery worker in Heroku causes timeout
I'm using Heroku for my Django project which runs on the daphne server. And also I have a celery worker to run tasks parallelly to reduce response time. Below is my Procfile web: daphne myproject.asgi:application --port $PORT --bind 0.0.0.0 -v 0 worker: celery worker -A myproject --loglevel=debug --concurrency=8 Scenario: I need to generate a statement using the last 24 months of balance data. For that, I have two endpoints GET BALANCE - Fetch the 24 months of balance ( each month is considered as a task and 24 tasks are run using celery worker ) GENERATE STATEMENT - Generate the statement for 24 months of data ( This API is called immediately after GET BALANCE API ) If I test for a single company it takes 15 - 20 seconds for the first API. But if I test for 2 or more companies (using load testing) it first company alone passes and others are failed due to HEROKU 30 Seconds Timeout problem For example for 5 companies: C1 - takes 15 seconds to complete - Pass C2 - takes 27 seconds to complete - Pass C3 - takes 43 seconds to complete - Timeout C4 - takes 48 seconds to … -
CRUD table / view not refreshing after form save
Django App Refresh Issue After submitting form for updating/deleting/creating items, view (CRUD table) does not refresh. The problem started after i have added the filtering of the model Here are the relevant code pieces: views.py: def item_list(request):`enter code here` user_list = item.objects.all() user_filter = UserFilter(request.GET, queryset=user_list) return render(request, 'items/item_list.html', {'filter': user_filter}) def search(request): user_list = item.objects.all() user_filter = UserFilter(request.GET, queryset=user_list) return render(request, 'items/item_list.html', {'filter': user_filter}) def save_item_form(request, form, template_name): data = dict() if request.method == 'POST': if form.is_valid(): form.save() print('x') data['form_is_valid'] = True user_list = item.objects.all() user_filter = UserFilter(request.GET, queryset=user_list) data['html_item_list'] = render_to_string('items/includes/partial_item_list.html', {'filter': user_filter}) else: data['form_is_valid'] = False context = {'form': form} data['html_form'] = render_to_string(template_name, context, request=request) return JsonResponse(data) def item_create(request): if request.method == 'POST': form = itemform(request.POST) else: form = itemform() return save_item_form(request, form, 'items/includes/partial_item_create.html') def item_update(request, pk): Item = get_object_or_404(item, pk=pk) if request.method == 'POST': print('postx') form = itemform(request.POST, instance=Item) else: form = itemform(instance=Item) print('postitem') return save_item_form(request, form, 'items/includes/partial_item_update. Once adding a new item in the model it should also refresh the view. -
Accessing request.body and request.FILES from mailgun forwarding route
My goal is to read the contents of a forwarded mail with an attachment using mailgun's route. When the email doesnt include an attachment, i can freely grab other attributes like the sender,subject and text but when i try to access request.FILES i get error saying You cannot access body after reading from request's data stream even though i have added @csrf_exempt decorator to my view function data =urllib.parse.parse_qs(raw_request_body.decode()) subject = data['subject'] sender = data['sender'] date = data['Date'] text = data['stripped-text'] but when i try to even get request.FILES after this block of code, it throws an error -
Reverse for 'user-posts' with arguments '('',)' not found
i got this Exception : Reverse for 'user-posts' with arguments '('',)' not found. 2 pattern(s) tried: ['user/(?P[^/]+)(?P\.[a-z0-9]+/?)$', 'user/(?P[^/]+)$'] and i don't know what is the problem here is my urls.py urlpatterns = [ path('', PostListView.as_view(), name='blog-home'), path('user/<str:username>', UserPostListView.as_view(), name='user-posts') and this is my home {% for post in posts %} <article class="media content-section"> <img class="rounded-circle article-img" src="{{ post.author.image.url }}"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{ post.author }}</a> <small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small> </div> <h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2> <p class="article-content">{{ post.content }}</p> </div> </article> why do i get this Exception ? -
502 Bad gateway nginx with gunicorn & django
I'm deploying django project using gunicorn and nginx. My nginx setting is, server { listen 8000; server_name 0.0.0.0; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/gagan/saporawebapp; } location / { include proxy_params; proxy_pass http://unix:/home/gagan/saporawebapp/saporawebapp.sock; } } when i run sudo nginx -t It shows that setup is correct . Then i started gunicorn using gunicorn --daemon --workers 3 --bind unix:/home/gagan/saporawebapp/saporawebapp.sock saporawebapp.wsgi Then nginx is showing 502 bad gateway. Corresponding error log is, 2019/10/08 07:51:34 [emerg] 3988#3988: open() "/etc/nginx/sites-enabled/saporawebapp" failed (2: No such file or directory) in /etc/nginx/nginx.conf:62 2019/10/08 07:59:54 [crit] 4278#4278: *1 connect() to unix:/home/ubuntu/myproject/myproject.sock failed (2: No such file or directory) while connecting to upstream, client: 42.108.169.252, server: 0.0.0.0, request: "GET /signup/ HTTP/1.1", upstream: "http://unix:/home/ubuntu/myproject/myproject.sock:/signup/", host: "157.245.108.160:8000" 2019/10/08 08:05:19 [crit] 4278#4278: *5 connect() to unix:/home/ubuntu/myproject/myproject.sock failed (2: No such file or directory) while connecting to upstream, client: 42.108.169.252, server: 0.0.0.0, request: "GET /signup/ HTTP/1.1", upstream: "http://unix:/home/ubuntu/myproject/myproject.sock:/signup/", host: "157.245.108.160:8000" 2019/10/08 08:06:24 [crit] 4744#4744: *1 connect() to unix:/home/ubuntu/myproject/myproject.sock failed (2: No such file or directory) while connecting to upstream, client: 42.108.169.252, server: 0.0.0.0, request: "GET /signup/ HTTP/1.1", upstream: "http://unix:/home/ubuntu/myproject/myproject.sock:/signup/", host: "157.245.108.160:8000" 2019/10/08 08:14:47 [alert] 5279#5279: 768 worker_connections are not enough 2019/10/08 08:14:47 [error] 5279#5279: *763 … -
how to seperate the each image individual?
'UploadSliderImage': [<InMemoryUploadedFile: squash-40790_640.png (image/png)>, <InMemoryUploadedFile: iconfinder_document_image_add_103475.png (image/png)>, <InMemoryUploadedFile: human_ubuntu-wallpaper-1600x900.jpg (image/jpeg)>] I need a = squash-40790_640.png,iconfinder_document_image_add_103475.png,human_ubuntu-wallpaper-1600x900.jpg Because I need to store the multiple images in single row one column like id | Images | 1 | squash-40790_640.png,iconfinder_document_image_add_103475.png,human_ubuntu-wallpaper- | | 1600x900.jpg | -
Javascript nested quotes with django tags
Hi i know this question get asked alot but i haven't found any answer related to Django tag and i have tried alot of method using ' in \" in " but no result, i still got console format error for my javascript My current line of code: <button type="button" class="btn btn-icon icon-left btn-info" onclick="location.href='{% url 'search_filter_by_id' filter_id=filter.id %}'"><i class="fas fa-search"></i>Search</button> The problem is the 'search_filter_by_id' cause escape quotes problem for me And i can't put it in a separate script tags due to filter.id only show on the line (for loop to output data each line) The django tag: {% url 'search_filter_by_id' filter_id=filter.id %} will output a url string but it required 'search_filter_by_id' to be in a quote for the tag to output the url string. Any help would be appreciate :D! -
Setting header name in list_filter when referencing foreign key in Django
I have a ProductType and Transaction model. The Transaction model references ProductType using a foreign key. I use list_filter to filter on ProductType in the admin environment for the Transaction model. However, the header name in the list filter is correct, since it calls the filter option "By name" instead of "By product type". How can I update this header name to "By product type"? models.py class ProductType(models.Model): name = models.CharField(max_length=20) class Transaction(models.Model): product_type = models.ForeignKey(ProductType, on_delete=models.CASCADE) admin.py @admin.register(Transaction) class TransactionAdmin(admin.ModelAdmin): list_filter = ['product_type__name']