Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't get gunicorn service to start with socket
I have a Django and Gunicorn setup. If I start the Gunicorn service from the command line like this: gunicorn --bind 0.0.0.0:8000 first.wsgi from the following working directory: ~/code/firstdjangoproject/first everything works as expected. However when I try to setup a service with systemd for gunicorn with the following gunicorn.service configuration: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=pi Group=www-data WorkingDirectory=/home/pi/firstdjangoproject ExecStart=/usr/local/bin/gunicorn \ --access-logfile - \ --error-logfile - /home/pi/error.log \ --workers 3 \ --bind unix:/run/gunicorn.sock \ first.wsgi:application [Install] WantedBy=multi-user.target I get the following error when trying to access the site with curl --unix-socket /run/gunicorn.sock localhost: curl: (56) Recv failure: Connection reset by peer When I look at the logs sudo systemctl status gunicorn I get the following: ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; disabled; vendor preset: enabled) Active: failed (Result: exit-code) since Mon 2019-09-30 22:14:14 CEST; 7s ago Process: 3070 ExecStart=/usr/local/bin/gunicorn --access-logfile - --error-logfile - /home/pi/error.log --workers 3 --bind uni Main PID: 3070 (code=exited, status=210/CHROOT) sep 30 22:14:14 raspberrypi systemd[1]: Started gunicorn daemon. sep 30 22:14:14 raspberrypi systemd[1]: gunicorn.service: Main process exited, code=exited, status=210/CHROOT sep 30 22:14:14 raspberrypi systemd[1]: gunicorn.service: Unit entered failed state. sep 30 22:14:14 raspberrypi systemd[1]: gunicorn.service: Failed with result 'exit-code'. sep 30 22:14:14 raspberrypi systemd[1]: gunicorn.service: … -
geodjango - construct json from foreigk key geometry
I'm trying to visualize a webmap with a django model whose geometry info is a foreign key, I've tried to update the value with a funtion to contruct a json and call the foreign key, but -I got this error: SyntaxError: expected expression, got '<' it read the json literally the type of the foreignkey object: 'coordinates': []}, how can I turn the foreignkey object as a lat and long value and insert in the json function? models.py class Info_Proy_eyd(models.Model): nom_proy = models.CharField(max_length=50) rol_fk = models.ForeignKey(D_Base_Roles, on_delete=models.CASCADE, blank=True, null=True, verbose_name="Rol") def json(self): return { 'nombre_proy':self.nombre_proyecto, 'geom':self.rol_fk.geom, } views.py def map_eyd(request): serie_t = Info_Proy_eyd.objects.all() json_s = [] for t in serie_t: json_s.append(Info_Proy_eyd.json(t)) p_json = { "type": "FeatureCollection", "features": [ { "type": "Feature", "geometry" : { "type": "Point", "coordinates": [d["geom"]], }, "properties" : d, } for d in json_s] } return render(request, 'b_seco_eyd/mapa_eyd.html', {'serie_t':serie_t, 'p_json':p_json, 'json_s':json_s}) page.html leaflet js var proy_eyd = {{p_json|safe}}; var mrk = L.geoJson(proy_eyd , { style: { } } ).addTo(map); thanks -
Why is Heroku running dev.py by force in Wagtail?
I deployed my Wagtail app on Heroku and want the variable 'DEBUG' to be False on production. I wrote some code in an init.py file that tests an environment variable 'ENV' to decide which python file to execute. In production, it should execute only production.py, but it does not. The code actually seems to work because it is not printing my debug message in the case i'm in the development environement, but somehow, dev.py is executed after production.py I tried removing the variable 'DEBUG' from both files (production.py and dev.py) to put them in init.py and define its value according to the environment. It works, DEBUG becomes False in production but it seems like my static files aren't loaded anymore. #__init__.py import os ENV = os.getenv('GLITCHYWARE_ENV', 'dev') if ENV == 'dev': print('DEV') from .dev import * elif ENV == 'prod': print('PROD') from .production import * The log: $ python manage.py collectstatic --noinput PROD The production.py code is executed The dev.py code is executed #1 As you can see, dev.py is executed after production.py, not six times though, i just put many print statements. -
Django: Q Objects concatenation
Been trying to filter with Q Objects and be able to search for "Firstname" + "Lastname", but only able to search for one or the other. Could anyone tell me what I'm doing wrong? Evaluation search view For clarification: ma = employee number fornavn = firstname efternavn = lastname fagnavn = subject name aktivitetnavn = aktivity name vuderingsnavn = grade delingnavn = department (integer) class SearchEvalueringer(ListView): model = Evaluering template_name = 'evalsys/categories/søg_evalueringer.html' def get_queryset(self): query = self.request.GET.get('q') if len(query) > 1: eval_list = Evaluering.objects.filter( Q(ma__ma__regex=query) | Q(ma__fornavn__iregex=query) | Q(ma__efternavn__iregex=query) | Q(fagnavn__fagnavn__iregex=query) | Q(aktivitetnavn__aktivitetnavn__iregex=query) | Q(vuderingsnavn__vuderingsnavn__iregex=query) | Q(ma__holdnavn__holdnavn__iregex=query) ) else: eval_list = Evaluering.objects.filter( Q(ma__delingnavn__delingnavn__exact=query) ) return eval_list I tried doing this: Q(ma__fornavn__iregex=query) & Q(ma__efternavn__iregex=query) But this does not let me search for "John Smith" still only "John" or "Smith". -
"[Errno 8] nodename nor servname provided, or not known" when using django-ses
I'm trying to plug django-ses into my project. I've followed instructions laid out in this tutorial: https://kholinlabs.com/the-easiest-way-to-send-emails-with-django Although I believe I've followed these closely, when sending a test email I receive this error: File "/usr/local/Cellar/python/3.6.5_1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socket.py", line 745, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): socket.gaierror: [Errno 8] nodename nor servname provided, or not known I've successfully registered with SES and validated the email I'm using to send. The error occurs either when sending from the python console or from the app. These are my relevant settings: EMAIL_BACKEND = 'django_ses.SESBackend' AWS_SES_REGION_NAME = 'eu-west-2' AWS_SES_REGION_ENDPOINT = 'email.eu-west-2.amazonaws.com' AWS_SES_ACCESS_KEY_ID = '{secret key}' AWS_SES_SECRET_ACCESS_KEY = '{secret access key}' AWS_SES_AUTO_THROTTLE = 0.5 How can I fix this? -
Django: Attempting to write a string directly into FileField, when backed by Amazon S3
I am attempting to write a string directly into a Django FileField by way of ContentFile. In doing so, I get a reproducible TypeError: Unicode-objects must be encoded before hashing error when attempting to save the contents of this file to the database, which traces through the s3boto3 lib. The exact source of this error is difficult to suss out. But let's state the question plainly, in Python 3, on Django 2.2.x, what is the correct way to take a csv file created with the csv lib from Python, and save that into a Django FileField backed by Amazon S3? Example code producing the error in question, truncated for privacy and relevance def campaign_to_csv_string(campaign_id): csv_string = io.StringIO() campaign = Campaign.objects.get(pk=campaign_id) checklist = campaign.checklist completed_jobs = JobRecord.objects.filter(appointment__campaign=campaign) writer = csv.writer(csv_string) # A bunch of writing to the writer here # string looks good at this point return csv_string.getvalue() calling function csv_string = campaign_to_csv_string(campaign_report.campaign.pk) campaign_report.last_run = datetime.datetime.now() campaign_report.report_file.save(str(campaign_report_pk) + '.report', ContentFile(csv_string)) campaign_report.processing = False campaign_report.save() My guess here is that s3boto3 is taking issue with ContentFile but the debugging information sent back to me gives me no clear path forward. -
Request headers in APITestCase
I have a test (APITestCase), and I need to specify custom headers: class ListAppsAPITest(APITestCase): def test_list_apps_versions(self): response = self.client.get(reverse('api:applications:list'), None, **{'Device-Id': 'deadbeef'}) I've tried different combinations of arguments, but it did not work. How to specify custom headers in tests? -
How do I create a persistent volume in docker for my postgresql database?
I am creating a docker image of a Django server that uses a postgresql database to keep track of login information, uploaded/downloaded files, etc. I want the data in my database to stick around even when I exit and relaunch the docker image. I created a docker-compose file and entrypoint file that successfully launches the server docker image and creates a volume for the database. Every tutorial that I've read online has said that having persistent data is as simple as mapping your database volume from the location you want it stored on the host to the /var/lib/postgresql/data location in the docker image. docker-compose.yml: version: '3.7' services: web: build: ./ command: python manage.py runserver 0.0.0.0:8000 ports: - 8000:8000 environment: - DEBUG=1 - SECRET_KEY=foo - SQL_ENGINE=django.db.backends.postgresql - SQL_DATABASE=app_db - SQL_USER=app_user - SQL_PASSWORD=changeme - SQL_HOST=db - SQL_PORT=5432 - DATABASE=postgres depends_on: - db db: image: postgres volumes: - ./postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=app_user - POSTGRES_PASSWORD=changeme - POSTGRES_DB=app_db ports: - 5432:5432 volumes: postgres_data: docker-entrypoint.sh: #!/bin/sh if [ "$DATABASE" = "postgres" ] then echo "Waiting for postgres..." while ! nc -z $SQL_HOST $SQL_PORT; do sleep 0.1 done echo "PostgreSQL started" fi python manage.py flush --no-input python manage.py migrate exec $@ Dockerfile: FROM python:3.7.4-alpine ARG PROJECT=EchoNine ARG … -
django-ckeditor - cannot edit image size
I've an instance of django-ckeditor where I seem unable to change image sizes. Quite simple the popup allows me to select and load images BUT I cannot resize them or set any of the properties (height, width, border, hspace, vspace, alignment). I am loading the form with ajax which I mention simply because I don't know if that has an impact -
Use django forms to create a new file
I apologize if this is obvious, but I'm relatively new to Django and couldn't find any resources for this. Goal I would like to create unique invoices that are stored on my server (or a CDN) when a form is filled out. Question Would it be possible to use Django forms to create an HTML file with a unique URL (or upload the newly created file to AWS) I understand how to upload files, I just can't quite figure out how to create a new file using a form. -
Can I serialize in Django without knowing the field name?
If there is a better approach to solving this problem than what I am attempting, please let me know. I have a Django web app where people can get pre-signed urls from s3 for viewing and uploading files. After the backend does some work, it returns JSON, part of which is an dictionary that ha key/value pairs in this format: {filename: s3-pre-signed-url}. Because the file name is different every time, I don't know how to set up my serializer. Is there an easy way to build a serialzier that accounts for different field names like this? I realize that another solution would be to reformat the object I am passing to the serializer. I could create a dictionary that has a fileName and s3URL field, and then build a serializer that looks for both of those fields. For example, if I create a dictionary with one key/value pair, the key being urls and the value being my dictionary with the key/value pairs, like this: urls = {'urls': name_and_url_dict}, and pass it to this serializer: class UrlSerializer(serializers.Serializer): urls = serializers.ListField(child=serializers.CharField()) I get a response (from Postman) like this: { "9": "Long Thought", "10": "Feeling", "11": "Memory", "12": "attachment test", "15": "Document … -
Django Messages - Message to all / specific users
Is it possible to configure Django Messages in a way so that the message is shown to all and or specific users? -
Django: NoReverseMatch but URL and keywords are there
I'm setting up an activation system so when a user registers, he receives an email with the activation link in it. For some kind of reason, it keeps throwing me a NoReverseMatch when I'm trying to generate the activation URL inside the email. What is strange, is that this does work on my local version of the project, but when deployed to my webserver it is throwing this error. So, what happens, when a user gets registered he is being sent an activation email: # views.py # User registers here def registreren(request): # .... f.is_active = False f.save() # Send the mail sendActivationEmail(request, f) def sendActivationEmail(request, user): data = { 'user': user, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), } sendEmail(request, 'XXX: activeer uw gebruiker', user.email, 'registration/activation_email.html', data) # Helper function for sending the email def sendEmail(request, subject, to, template, data): current_site = get_current_site(request) data['domain'] = current_site.domain html_message = render_to_string(template, data) plain_message = strip_tags(html_message) send_mail(subject, plain_message, 'XXX <' + settings.EMAIL_HOST_USER + '>', [to], html_message=html_message) This all works as expected. But when I try to render the template: XXX Hey {{ user.get_short_name }}, Bedankt voor je inschrijving bij het online inschrijvingssysteem van XXX. Om jouw registratie te confirmeren, kan je klikken op de volgende … -
Not Recieving Email Id in User Model in admin section when using social-auth-django for authentication
Here is my pipeline. I want to use the default User for now. SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', # 'social_core.pipeline.mail.mail_validation', #I don't need it. # 'social_core.pipeline.social_auth.associate_by_email', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', 'accounts.pipeline.save_profile', ) Scopes SOCIAL_AUTH_FACEBOOK_SCOPE = [ 'email', 'user_friends', ] SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = { 'fields': 'id,name,email', } accounts/pipeline.py I just wanted to know what the response is. Here is the response: {'id': '521205608677881', 'name': 'Rishabh Jain', 'access_token': 'EAAFF2gP28aQBALgmqXQhM4eKKaAJ9mhLj76S9cYgVYniWAC1KsQI1ML8BZBhOxRpP7UIjOaZBUfNfd9awFzY4S6RlhcmfKLxEsPsAbSdQcld2vQhJmWmX1z3Ww7iG0kKAcJVFvoADsrmPDgikPiaAp9cgTjYIu5MuwYQvHAQZDZD', 'expires': 5183744, 'granted_scopes': ['user_friends', 'email', 'public_profile']} Clearly the granted scopes include the email-id. But I am not able to see the email-ids in the User in Django/admin. I know I should create a new question, but in case you can help. I want to know if the user logging in using fb is coming on the website first time or not so that I can greet him. Any variable in User or User Social Auth to do so. -
Language switcher list without button
I am trying to make a list of available languages and I am not able to as close I got to was this but the language upon choosing is not being changed, the page refreshes but nothing. <form action="/i18n/setlang/" method="post" style="display: inline;">{% csrf_token %} <div style="display: inline;"> <select name="language" onchange="javascript:form.submit()"> {% for lang in LANGUAGES %} <option value="{{ lang.0 }}"{% ifequal LANGUAGE_CODE lang.0 %} selected="selected"{% endifequal %}>{{ lang.1 }}</option> {% endfor %} </select> </div> </form> I get this error in log POST /i18n/setlang/ HTTP/1.1" 302 0 I have tried to make it as a list with button but thats just ugly to have a button to change the language with. -
What's wrong with my indentation at server?
Everything works on my local machine but when I uploaded my project at server I'm getting this error at second "if" statment line: TabError at /home/ inconsistent use of tabs and spaces in indentation def scrape_weather(request): if request.method == 'POST': old_weather = Weather.objects.all() old_weather.delete() api_adress = "http://api.openweathermap.org/data/2.5/weather?q=" api_key = "***" city = request.POST.get("city") url = api_adress + city + api_key if url == (api_adress + api_key): url = api_adress + "warsaw" + api_key json_data = requests.get(url).json() new_weather = json_data['weather'][0]['main'] degree_kelvin = int(json_data['main']['temp']) degree = degree_kelvin-273 pressure = json_data['main']['pressure'] new_weather = Weather() new_weather.degree = degree new_weather.pressure = pressure new_weather.weather = new_weather new_weather.save() return redirect('/home/') -
What should I do and learn after Django Basics?
I have learnt basics and more than basics(I guess) of django. I can make a blogging website,Ecommerce Website(without payment option).I have knowledge of HTML,CSS,Sass,javascript.Now I want to learn and do more things and I want to make a facebook clone using Django. It will have systems including liking and commenting without reloading pages,security,2 step verification,ID deactivating etc.Please suggest me what should I need to learn to make that project. -
How to manage to serve media files with Django, Nginx, Docker and Traefik?
I'm trying to upload and persist media files (images, pdfs) in an application with Django. It's working fine in development mode, but I'm getting a "404 Not Found The requested URL /mediafiles/images/test.jpg was not found on this server." when deployed on a server. "Funny" thing to note : I manage to upload files, I see them on my host, and both containers (nginx and webserver), but whenever I try to access them I get the Not Found error. I've read and tries many things without success such as modifying the nginx conf file, playing with the docker-compose file.. would you have any idea where I should look from now on? Here's what I think are pertinent informations : Server : Ubuntu 16.04 Docker-Compose services: nginx: image: nginx depends_on: - webserver volumes: - ./config/nginx/conf.d:/etc/nginx/conf.d - ./static:/usr/share/nginx/html:ro - ./mediafiles:/mediafiles labels: - "traefik.backend=${TRAEFIK_HOST}_static" - "traefik.frontend.rule=Host:${TRAEFIK_HOST}; PathPrefixStrip: /static/" - "traefik.enable=true" - "traefik.port=80" webserver: image: ${MY_IMAGE} volumes: - ./static:/tmp/html/static - ./mediafiles:/code/server/mediafiles labels: - "traefik.backend=${TRAEFIK_HOST}" - "traefik.frontend.rule=Host:${TRAEFIK_HOST}" - "traefik.enable=true" - "traefik.port=8000" volumes: mediafiles: Nginx Config server { listen 80; server_name localhost; location / { root /usr/share/nginx/html; index index.html index.htm; } error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } location /mediafiles { … -
Django Calculate Average From Model Fields and Store in Another Model
I have a model where I hold at least 3 scores, but which in the future may hold more. The scores can be blank or contain a value, meaning different schools can have a different number of entries. My challenge is I'd like then to have a field that's based off a function of the above scores so I can call this on my views rather than have to calculate it every time. I'm trying to find the best way to ensure that the main score is calculated and saved every time one of the contributing scores is updated, but only then. class Marks(models.Model): school = models.ForeignKey(School, null=True, on_delete=models.SET_NULL) marks_2016 = models.DecimalField(name='2016 Marks', max_digits=12, decimal_places=3, blank=True, null=True) marks_2017 = models.DecimalField(name='2017 Marks', max_digits=12, decimal_places=3, blank=True, null=True) marks_2018 = models.DecimalField(name='2018 Marks', max_digits=12, decimal_places=3, blank=True, null=True) def __str__(self): return self.school.name class Score(models.Model): school = models.ForeignKey(School, null=True, on_delete=models.SET_NULL) score = models.DecimalField(max_digits=5, decimal_places=2) def __str__(self): return self.school -
Static file not load in django template?
Problem is STatic file not load. CRM/ | |-- CRM/ | |-- next_crm/ | |-- static/ | | +-- css/ | | +-- bootstrap.min.css <-- here | +-- manage.py This is my static variables defined in the next_crm/settings/settings.py file. STATIC_ROOT = '' STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")] -
Django annotate by sum of two values with multiple relations
I have 4 models: class App(models.Model): ... class AppVersion(models.Model): app = models.ForeignKey(App) ... class Apk(models.Model): version = models.OneToOneField(AppVersion) size = models.IntegerField() class Obb(models.Model): version = models.ForeignKey(AppVersion) size = models.IntegerField() AppVersion version always has one Apk, but may have 0, 1 or 2 Obb's I want to annotate QuerySet by total size of the App (which is Apk.size + sum of all Obb.size for given AppVersion). My App QuerySet looks like this: qs = App.objects.filter(is_visible=True) and versions subquery is: latest_versions = Subquery(AndroidApplicationVersion.objects.filter(application=OuterRef(OuterRef('pk'))).values('pk')[:1]) This subquery always gives the latest AppVersion of the App. So what subquery should I use to annotate qs with size attribute calculated as shown above? -
ElasticBeanstalk trying to connect local postgres database
Elasticbeanstalk autcreated a postgres database when I changed the env configuration . I tried supplying the RDS_* parameters. Still it is connecting to localhost and failing django.db.utils.OperationalError: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?. container_command 04_migrate in .ebextensions/django.config failed. For more detail, check /var/log/eb-activity.log using console or EB CLI. this is my config container_commands: 02_upgrade_pip: command: ". /home/ec2-user/setup.sh && python -m pip install --upgrade pip" leader_only: true 03_upgradde_setuptools: command: "python -m pip install --upgrade setuptools" leader_only: true 04_migrate: command: "source /opt/python/run/venv/bin/activate && python /opt/python/current/app/manage.py migrate --noinput" leader_only: true 05_createsu: command: "source /opt/python/run/venv/bin/activate && python /opt/python/current/app/manage.py createsu" leader_only: true 06_collectstatic: command: "source /opt/python/run/venv/bin/activate && python /opt/python/current/app/manage.py collectstatic --noinput" files: "/opt/python/run/venv/pip.conf": mode: "000755" owner: root user: root content: | [global] no-cache-dir=false "/home/ec2-user/setup.sh": mode: "000755" owner: root group: root content: | #!/bin/bash #exported RDS variables here option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: "project.settings" "PYTHONPATH": "/opt/python/current/app:$PYTHONPATH" "ALLOWED_HOSTS": ".elasticbeanstalk.com" "aws:elasticbeanstalk:container:python": WSGIPath: /opt/python/current/app/project/wsgi.py NumProcesses: 3 NumThreads: 20 "aws:elasticbeanstalk:container:python:staticfiles": "/static/": "/opt/python/current/app/static/" I think it should have taken by itself when I do ssh to ec2 I cannot echo $RDS_HOSTNAME either. What may be the problem here -
SQL identifier substitution - Using a list of column names
I am trying to run a query of the form: SELECT {} from TABLE where foo = VALUE But I want to be able to provide a list to replace the {} According to the psycopg docs, in order to do this safely, you need to use the sql.Identifier function, in order to properly escape the parameter, and then do something like this: SQL = sql.SQL( "SELECT {} FROM foo WHERE bar = %s" ).format(identifier) cursor.execute(SQL, [VALUE]) This works, when identifier is a single element, but I need it to be an arbitrary number. For example if: identifier = ["abc", "def"] and VALUE = 4 SQL = SELECT abc def FROM foo WHERE bar = 4 I've tried running sql.Identifier(x) for every member of identifier, but that gave "abc""def", which is clearly not correct. -
django social media apps ManyToManyField population issue
I am writing a social media apps, I design a model, when i try to populate it, it throws me this error: ValueError at /admin/social/group/add/ "<Group: Group object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used. this is my models: from django.db import models class Person(models.Model): name = models.CharField(max_length=20) class Group(models.Model): admin = models.ForeignKey( Person, on_delete=models.CASCADE, related_name='group_admin' ) members = models.ManyToManyField( Person, related_name='group_members', blank=True ) def save(self, *args, **kwargs): self.members.add(self.admin) super(Group, self).save(*args, **kwargs) I want an admin also will be a group members when i keep the save method like below this: def save(self, *args, **kwargs): super(Group, self).save(*args, **kwargs) self.members.add(self.admin) it doesn't throws any error but the problem is, the members filed don't populate. I want, I will just submit admin during create a Group, and memebrs field will be filled automatically with same foreignkey of admin. I mean, an admin will be a members of the same group too. can anyone help me to achieve this? -
django admin customise changelist with hyperlink actions in each row
I am using django admin to do a reporting application. and I already add a custom search form in changlist by overriding the 'changlist_view.html' template, there is an element called 'company'. <form action="" method="POST" class="form-inline"> {% csrf_token %} <select name="company"> {% for c in company_list %} <option value="{{c.key}}" {% if company_keep == c.key %} selected="selected"{% endif %} >{{c.value}}</option> {% endfor %} </select> <button type="submit" >Search</button> </form> In the list display, there is hyperlink 'report' in each row, the backend code as below: class myAdminModel(admin.ModelAdmin): ...... def report_link(self, obj): url = f"/%d/%d/report/" % (***company-key***, ***obj.pk-id***,) return mark_safe( "<a target='blank' href='{url}'>Report</a>" ) ...... now my headache question is here, the obj.pk I can easily get except company-key, I know it is a form element from the page request, so is there any solution to get form elements in this situation??