Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF writable serializer for GenericRelation in django
I'm trying to have a writable serializer that creates/updates a model and its GenericRelation target in a single API class TaggedItem(models.Model): tag_name = models.SlugField() content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() tagged_object = GenericForeignKey('content_type', 'object_id') class Note(models.Model): text = models.CharField(max_length=1000) tags = GenericRelation(TaggedItem) In the above, I would like to support a create/update end-point on Note. The data would be: { "text": "something", "tags": [ { "object_id": "1" "tag_name": "something" }, { ... ... } ] } The documentation only has the following brief note: Note that reverse generic keys, expressed using the GenericRelation field, can be serialized using the regular relational field types, since the type of the target in the relationship is always known. One option of course is to override create, update in NoteSerializer, extract the TaggedItem data and call the TaggedItemSerializer manually. However, since Note is a GenericRelation target from multiple models, I want to avoid doing this on every source model Is there a better way ? As best as I can tell, all the information needed to create these objects is present since the target of the relationship is known...so I'm hoping this pattern is a first-class-citizen with DRF. Haven't found anything yet. -
Running Django Test on CircleCI - django.db.utils.OperationalError: FATAL: role "circleci" does not exist
hope you are fine: as i'm trying to use django with circleCI, i have the following as my settings.py database configuration: DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME':'default_db', 'USERNAME':'postgres', 'PASSWORD':'default_pass', 'HOST':'localhost', 'PORT':'5432', } } and on circleCI config.yml (same user, db and password): environment: POSTGRES_USER: postgres POSTGRES_DB: default_db POSTGRES_PASSWORD: default_pass and i get django.db.utils.OperationalError: FATAL: role "circleci" does not exist, from a previous question it seems when running postgres inside docker, there might be some problems regarding the port as postgres also running locally, but i don't know if this is the same case here, any help would be appreciated. circleCI executor: docker. circleCI db image: circleci/postgres:latest-postgis -
Django Custom Queryset managers: Implicit chained filter()?
In Django, when it comes to M2M relationships, we know that these two queries: MyModel.objects.filter(othermodel__attr1="someval1", othermodel__attr2="someval2") MyModel.objects.filter(othermodel__attr1="someval1").filter(othermodel__attr2="someval2") Will not necessarily return the same results (docs). I've recently started utilizing custom QuerySet managers and it suddenly dawned on me that I may get this undesired behavior (for me at least) if I'm doing something like this: # defined as customobjects = MyModelQuerySet.as_manager() in `MyModel` class MyModelQuerySet(models.QuerySet): def method1(self): return self.filter(othermodel__attr1="someval1") def method2(self): return self.filter(othermodel__attr2="someval2") and using MyModelQuerySet like this: results = MyModel.customobjects.method1().method2() Then I may be getting the behavior of chained filters. For me this makes using a custom QuerySet manager completely useless as I need an AND behavior most of the time. But I'm not sure this is indeed the behaviour. If it is, are there are any workarounds while using managers? (I want the ability to flexibly use different filters and mix and match them with managers, but I don't want the chained filters behavior) -
Django, React encountered static file 404 error. Is there any solution?
In Dango, index.html of React is successfully displayed, but it is not rendered and only white blank pages are displayed. Below are my settings. /etc/nginx/sites-available/mystar.conf: django setting: dir tree: site error: React is shown by setting the build folder from the template of Janggo. How can I solve the above error? -
Trouble with writing view in django
So I have the following models in my Django app: Models.py class Cia(models.Model): confidentiality = models.BooleanField(default=False) integrity = models.BooleanField(default=False) availability = models.BooleanField(default=False) def __str__(self): return '%s, %s, %s' (self.confidentiality, self.integrity, self.availability) class security_incident(models.Model): asset = models.CharField(max_length=200) actor = models.CharField(max_length=200) action = models.CharField(max_length=200) cia = models.ManyToManyField(Cia) def __str__(self): return self.asset class attack(models.Model): name = models.CharField(max_length=100) defense_mechanism = models.CharField(max_length=100) action = models.ManyToManyField(security_incident) def __str__(self): return self.name class adtree(models.Model): goal = models.CharField(max_length=200) security_incident = models.ManyToManyField(security_incident) cia = models.ManyToManyField(Cia) def __str__(self): return self.goal the adtree model should be rendered into a tree structure like this: Database (root node/asset) --Confidentiality ---Security Incident ----Attack --Integrity ---Security Incident ----Attack --Availability ---Security Incident ----Attack So this is the usecase: A user inputs the root node (asset) of a tree in this form, and selects the checkboxes the user wants to see: <form method="GET" action="."> <div class="form-row"> <div class="form-group col-12"> <div class="input-group"> <input class="form-control py-2 border-right-0 border" type="search" name="goal" placeholder="Enter goal of ADT (asset)" /> <span class="input-group-append"> <div class="input-group-text bg-transparent"> <i class="fa fa-search"></i> </div> </span> </div> </div> </div> <div class="form-group"> <div class="form-check"> <input class="form-check-input" type="checkbox" id="confidentiality" name="confidentiality"> <label class="form-check-label" for="confidentiality"> Confidentiality </label> </div> </div> <div class="form-group"> <div class="form-check"> <input class="form-check-input" type="checkbox" id="integrity" name="integrity"> <label class="form-check-label" for="integrity"> Integrity </label> </div> … -
Django in python
What I do ?Docmas.profile.user: (fields.E300) Field defines a relation with model 'app.Model', which is either not installed, or is abstract. Docmas.profile.user: (fields.E307) The field Docmas.profile.user was declared with a lazy reference to 'app.model', but app 'app' isn't installed. : from django.db import models from django.contrib.auth.models import User class profile(models.Model): user = models.OneToOneField("app.Model", verbose_name=("user"), on_delete=models.CASCADE) name= models.CharField(("NAME:"),max_length=30) who_i = models.TextField(("Who are You?"),max_length=120) price= models.IntegerField(("what is your price?")) class Meta: verbose_name = ('profile') verbose_name_plural = ('profile') def __str__(self): return self.name -
Django Query - Return All objects that have been referenced at least once in a model
I have two models. Employees and Schedule class Employee(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) phone = models.CharField(max_length=20) class Scheduled(models.Model): title = models.CharField(max_length=50) description = models.TextField() assigned_employee = models.ForeignKey(Employee, on_delete=models.CASCADE) I want to return all employees that have been referenced at least once in Scheduled table. Note: I have done it with 2 queries, but is there a way to do this in just one query? -
NoReverseMatch Django url parameter passing
I am trying to pass a string parameter to a url and I keep getting this error. Reverse for '' not found. '' is not a valid view function or pattern name. on this url urlpatterns = [ path('dashboard/<str:filter>/', views.dashboard, name='dashboard'), ] root urls urlpatterns = [ path('admin/', admin.site.urls), path('user/', include('users.urls')), path('', include('app.urls')), # dashboard comes from here ] this is how I pass the parameter href="{% url 'dashboard' 'create_time' %}" -
django tutorial02 "playing with the api"
okay so i have been following the django tutorial perfectly up untill the "Playing with the API" point. Now here's my problem. I got to the point where i had to add def __str__(self): to my code. I did exactly what the tutorial said and when it got to the point that i had to restart the shell i pressed ctrl+z to exit the shell then i started the shell again. The only problem is that when it got to making sure that the __str__() addition worked. It didnt. ive been stuck on this for the past week and i really want to move forward. ive looked at everybodys opinion that ive seen and none of the solutions worked. from my point of view i dont know what i did wrong. someone help please. im using python 3.9.2 by the way. the only place im not sure of was the restarting of the shell. -
Python django, check if sql column contains a value
Is there a way to check if a table column already contain a value without using a for loop? Does django have a "not in" syntax? -
How to merge two model in a signal from django?
I want to merge two model in a signal from which I am using for update my blog post. here is my code: models.py class Post(models.Model): title = models.CharField(max_length=300,unique=True,error_messages={'unique':"This title already exists. Please use different title"}) author = models.ForeignKey(User, on_delete=models.CASCADE) class HeaderImage(models.Model): header_image = models.ImageField() #I want to merge this model with Post model and want to add image field in my current forms. froms.py class BlogPost(forms.ModelForm): class Meta: model = Post fields = ['title','author','body'] views.py class BlogUpdateView(PermissionRequiredMixin,UpdateView): raise_exception = True permission_required = "blog.change_post" model = Post template_name = "blog_update_post.html" form_class = BlogPost How to get image filed from second model and add it to existing from which using first model? -
Where to query model if not in model.py?
I have a model.py that looks as such: from django.db import models import requests import pandas as pd from datetime import timezone from datetime import datetime from datetime import date from datetime import timedelta import time class cryptoData(models.Model): coin = models.CharField(max_length=10) asset_id = models.SmallIntegerField() time = models.DateTimeField() close = models.FloatField() volume = models.BigIntegerField() market_cap = models.FloatField() reddit_posts = models.IntegerField() reddit_comments = models.IntegerField() tweets = models.IntegerField() tweet_favorites = models.IntegerField() social_volume = models.IntegerField() def apiFunc(): #pull data from API and put into df return(df) df = apiFunc() cryptoData.objects.bulk_create( cryptoData(**vals) for vals in df.to_dict('records') ) However, as I understand from reviewing other threads, it is not in best practice to query the database in the same file as model.py. Where then should I house the code that loads data into my created model? -
How do I manage django reusable app urls for different environments?
I am creating a Django reusable app with django rest framework DRF. I defined at first this urls.py file. (omit imports for shortness) urlpatterns = [ path(r'api-auth/', include('rest_framework.urls', namespace='rest_framework')), path(r'admin/', admin.site.urls), path('core/v1/', include(ApiRouter.get().urls)), # I define here url paths for models ] The problem is that when I build this app, and I installed it on another project. There are going to show up all the api-auth and admin urls from the reusable app in the other project. I came with this idea: Create two url files (for local dev and for build), and use an env variable to use one or another. And I implemented like this: Define an env variable in for example env.ini dev_mode=False Then in project settings file: DEV_MODE = get_var_from_env_file(‘dev_mode’) if DEV_MODE: ROOT_URLCONF = 'myproject.urls_dev' else: ROOT_URLCONF = 'myproject.urls' And so in urls.py I will have only url relative to models and in urls_dev all. urls.py urlpatterns = [ path('v1/', include(ApiRouter.get().urls)), ] urls_dev.py urlpatterns = [ path(r'api-auth/', include('rest_framework.urls', namespace='rest_framework')), path(r'admin/', admin.site.urls), path('core/v1/', include(ApiRouter.get().urls)), # I define here url paths for models ] Is there a standard way to manage this? Or is there a better approach? -
How to implement a double sided referral program with Stripe Checkout?
we're selling access to our product which has a monthly/yearly subscription. We're using Stripe Checkout to manage our subscriptions. How do I implement double sided rewards for our users (e.g. if a friend signs up with someone's promo code, they both get $25 off the price of their subscription). -
Dropdown menu should only show user created data from the field with Django
A disclaimer that I'm new to programming so please take it easy on me. :) I have authentication set up and users that log into my Django website. I have two forms that the user can fill out. Patient and Script. The Script form and view of ScriptCreateView has a patient field that should only show patients that that user has entered. Currently the dropdown shows all patients all users has entered. I have googled my head off and can't seem to figure it out. Any assistance would be appreciated. Models.py from django.conf import settings from django.contrib.auth import get_user_model from django.db import models from django.urls import reverse class Patient(models.Model): patient_name = models.CharField(get_user_model(), max_length=40, unique=True) num_cycles = models.PositiveIntegerField(verbose_name='How Many Cycles Will This Patent Have') cycle_length_days = models.PositiveIntegerField(verbose_name='How Many Days Will Each Cycle Be') treatments_per_cycle = models.PositiveIntegerField(verbose_name='How Many Treatments Will Be In Each Cycle') cycle_start_day = models.DateField(null=False,verbose_name='What Is The Date Of The First Cycle') author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, ) def __str__(self): return self.patient_name def get_absolute_url(self): return reverse('patient_detail', args=[str(self.id)]) class Script(models.Model): patient = models.ForeignKey(Patient, on_delete=models.SET_NULL, null=True, verbose_name='Patient Name') author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE,) drug_name = models.CharField(max_length=40, unique=True, verbose_name='Name Of Drug') drug_instructions = models.CharField(max_length=250, verbose_name='Detailed Instructions') drug_start_day = models.DateField(null=False, verbose_name='First Day To Take This Drug') … -
idk whats happending but i get an error saying Blacklist.findOne is not a function
const command = client.commands.get(commandName); if (command.devOnly == true && message.author.id !== '696023375788900353') return message.channel.send('You dont have permission to use this as this is a dev command'); let profile = await Blacklist.findOne({ userID: message.author.id }); if (profile) return message.channel.send('You cannot use the commands as you are banned from using my commands'); try { command.execute(message, args, client); } catch (err) { console.log(err); } }, }; -
Django template conditionals not working as intended
I am trying to create a basic view which returns a bunch of posts to be rendered as per the given keyword. I want it to be such that: When it loads initially, it just shows a search bar. When a keyword is supplied for search then it finds the posts with that keyword and renders them. If no posts are found then it should show a message that "no posts for the given keyword were found". I am able to achieve 1 and 2 but for the 3rd one, django is acting strange. Views.py def search(request): if 'keyword' in request.GET and request.GET['keyword'] != '' and request.GET['keyword'] != ' ': res = Post.objects.filter(tag__icontains=request.GET['keyword']) posts = [PostSerializer(x).data for x in res] if len(posts) == 0: return render(request, 'search.html', context={'notfound':True}) return render(request, 'search.html', context={'posts':posts}) return render(request, 'search.html') Template {% if notfound %} <h2> Seems like there are no posts with that keyword </h2> {% endif %} {% for post in posts %} //render posts {% endfor %} Note that here I have used the 'notfound' key as simply checking if posts | length equals 0 was achieving 3 (the 3 points mentioned above) but was also showing the message for 1, which … -
Problem with deploying Django app using Heroku
I am not clear with where to save Procfile in Django app for Heroku my app file structure is like this: coding_site coding_site wsgi.py settings.py Procfile2 readME.md Procfile1 other_files should I save in Procfile1 or Procfile2 location? my Procfile looks like this: in location Procfile1 web: gunicorn coding_site.coding_site.wsgi --log-file - in Procfile2 web: gunicorn coding_site.wsgi --log-file - Errors I got Using Procfile1 location 2021-05-19T18:40:51.423744+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/admin" host=coding-club-jaya.herokuapp.com request_id=71078218-39b0-4b7f-a817-7093078baa08 fwd="123.201.77.16" dyno= connect= service= status=503 bytes= protocol=https Using Procfile2 location 2021-05-19T17:49:21.981719+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/admin" host=coding-club-jaya.herokuapp.com request_id=a47a58e6-4513-44a4-88aa-4425470d8465 fwd="123.201.77.16" dyno= connect= service= status=503 bytes= protocol=https in btw: I changed the settings.py file as shown in different tutorials here are the changes made in the setting.py code import django_heroku import dj_database_url *** MIDDLEWARE =[**, 'whitenoise.middleware.WhiteNoiseMiddleware', **] *** DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'ciba', } } *** STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") STATIC_URL = '/static/' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' os.makedirs(STATIC_ROOT, exist_ok=True) os.makedirs(STATICFILES_DIRS[0], exist_ok=True) # Activate Django-Heroku. django_heroku.settings(locals()) in case needed here is my requirements.txt file gunicorn==20.1.0 whitenoise==5.2.0 django-heroku==0.3.1 Django==3.0.2 requests==2.22.0 sqlparse==0.2.4 dj-database-url==0.5.0 dj-static==0.0.6 docopt==0.6.2 psycopg2 python-decouple gitignore==0.0.8 pytz==2018.9 static3==0.7.0 Pls help, All my work is done and got stuck in the last step (it's … -
ValueError at /profile/ Required parameter name not set Request Method: GET
After properly deploying my app using Heroku I get this error while accessing my profile. Required parameter name not set Request Method: GET Request URL: https://(domain).herokuapp.com/profile/ Django Version: 3.2.2 Exception Type: ValueError Exception Value: Required parameter name not set Exception Location: /app/.heroku/python/lib/python3.9/site-packages/boto3/resources/base.py, line 118, in __init__ Python Executable: /app/.heroku/python/bin/python Python Version: 3.9.5 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python39.zip', '/app/.heroku/python/lib/python3.9', '/app/.heroku/python/lib/python3.9/lib-dynload', '/app/.heroku/python/lib/python3.9/site-packages'] Server time: Wed, 19 May 2021 18:40:44 +0000 Error during template rendering In template /app/blog/templates/blog/base.html, error at line 10 Required parameter name not set 1 {% load static %} 2 <!DOCTYPE html> 3 <html> 4 5 <head> 6 <link rel="shortcut icon" type="image/png" href="{% static 'favicon.ico' %}"/> 7 8 <!-- Required meta tags --> 9 <meta charset="utf-8"> 10 <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> 11 12 <!-- Bootstrap CSS --> 13 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" 14 integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> 15 16 <link rel="stylesheet" type="text/css" href=" {% static 'blog/main.css' %} "> 17 18 {% if title %} 19 <title>mytitle -{{ title }} </title> 20 {% else %} I don't understand why i keep getting this error. I have also set the environment variables correctly. This is my settings.py import os import django_heroku # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) … -
Load an inclusion tag from context variable name
I have a template which would need to call some inclusion_tag based on a variable in the context. Something like this: <div> {% for section in sections %} {{ section.tagname }} {% endfor %} </div> Can I actually do that somehow? Or do I need to build a big if-elif statement & check names explicitely? EDIT: I also tried something like {% {{ section.tagname }} %} but doesn't work either. -
Lazy Load Plotly Graphs without iFrame
I'm trying to improve my websites Largest Contentful Paint score, and one large problem I'm having is attempting to lazy load plotly graphs. That page in question has 6-8 graphs. At first I created them by using the embed tool on chart studio, which gave me an iFrame for each one. This worked but the issue with the iFrame is it needs to reload the plotly javascript each time which really slowed it down. I'm sure I can implement lazy loading on the iFrame's, but that would still be a big draw and doesn't seem efficient at all. My second attempt I took all the code out of the iFrame, and simply put this at the top of the page: <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> This improved some metrics, such as Time to Interactive, a lot. Unfortunately it actually made Largest Content Paint worse. I'm wondering how I'd be able to either lazy load the graphs or parent divs, or make it so each iFrame doesn't need to reload the plotly javascript independently. Here is an example of each graph being created. <div id="4023a488-b679-4fdd-a482-30d6e6ec851b" style="width: 100%; height: 100%;" class="plotly-graph-div"></div> <script async type="text/javascript"> (function(){ window.PLOTLYENV={'BASE_URL': 'https://plotly.com'}; var gd = document.getElementById('4023a488-b679-4fdd-a482-30d6e6ec851b') var resizeDebounce = null; … -
ValueError: too many values to unpack: error in django models while querying a model
The following is the stack trace- Internal Server Error: /merger/merge/ Traceback (most recent call last): File "C:\Users\Yash\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Yash\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Yash\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "F:\Internship Project\pdf_merger\merger\views.py", line 72, in mergefiles mergedFile = requests.post('https://pdfmergerapi.herokuapp.com/', files = postlist) File "C:\Users\Yash\AppData\Local\Continuum\anaconda3\lib\site-packages\requests\api.py", line 112, in post return request('post', url, data=data, json=json, **kwargs) File "C:\Users\Yash\AppData\Local\Continuum\anaconda3\lib\site-packages\requests\api.py", line 58, in request return session.request(method=method, url=url, **kwargs) File "C:\Users\Yash\AppData\Local\Continuum\anaconda3\lib\site-packages\requests\sessions.py", line 494, in request prep = self.prepare_request(req) File "C:\Users\Yash\AppData\Local\Continuum\anaconda3\lib\site-packages\requests\sessions.py", line 437, in prepare_request hooks=merge_hooks(request.hooks, self.hooks), File "C:\Users\Yash\AppData\Local\Continuum\anaconda3\lib\site-packages\requests\models.py", line 308, in prepare self.prepare_body(data, files, json) File "C:\Users\Yash\AppData\Local\Continuum\anaconda3\lib\site-packages\requests\models.py", line 496, in prepare_body (body, content_type) = self._encode_files(files, data) File "C:\Users\Yash\AppData\Local\Continuum\anaconda3\lib\site-packages\requests\models.py", line 141, in _encode_files for (k, v) in files: ValueError: too many values to unpack (expected 2) This happens when I try to query a model- class userFiles(models.Model): user = models.ForeignKey(user, on_delete=models.CASCADE) filename = models.CharField(max_length=200, null=True) file = models.FileField(storage=fs) where the user model is imported from another app- class user(models.Model): userhandle = models.CharField(max_length=200) phone = models.CharField(max_length=10) username = models.CharField(max_length=200) password = models.CharField(max_length=200) The query is- f = userFiles.objects.get(filename=nameToBeSearched) I have tried passing the foreign-key model both as a string and as … -
Errno 2 No such file or directory: '/img' in Django admin page
I am trying to add and edit objects from my sqlite3 database in Django in the Admin page as I don't want to use the terminal for that. My app is called homepage and my model is Raport: class Raport(models.Model): titlu = models.CharField(max_length=100) descriere = models.TextField() imagine = models.FilePathField(path='/img') The error received when trying to add or change a "Raport" in the Django admin page: Request URL: http://127.0.0.1:8000/admin/homepage/raport/4/change/ Django Version: 3.2.3 Exception Type: FileNotFoundError Exception Value: [Errno 2] No such file or directory: '/img' My admin.py: from django.contrib import admin from .models import Raport @admin.register(Raport) class RaportAdmin(admin.ModelAdmin): list_display = ("titlu", "imagine") My folder structure is homepage/static/img/image.png On the site, the images from Raport are shown correctly, with no errors linked to not finding img directory. Example of working html: {% extends "base.html" %} {% load static %} {% block page_content %} <h1>{{ raport.titlu }}</h1> <div class="row"> <div class="col-md-8"> <img src="{% static raport.imagine %}" alt="" width="100%"> </div> <div class="col-md-4"> <h5>Despre raport:</h5> <p>{{ raport.descriere }}</p> </div> </div> {% endblock %} What am I missing? Thank you! -
Django convert String in Dictionary to Integer for the first 3 keys
Sorry for this newbie questions. I have a dict like this: {'id':'1', 'Book':'21', 'Member':'3', 'Title':'Chameleon vol. 2', 'Author':'Jason Bridge'} I want to convert that dict to: {'id':1, 'Book':21, 'Member':3, 'Title':'Chameleon vol. 2', 'Author':'Jason Bridge'} I need to convert only the first 3 key value to int Thanks in advance -
Going to the first page of a chapter/issue
I'm developing a webcomic using django. I'm trying to implement a feature that if you click on a comic issue or chapter cover it will redirect you to the first page of that issue/chapter. Picture for a reference. Here is what I have managed to do so far. models.py class PagePL(models.Model): create_date = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now= True) number = models.PositiveIntegerField('Page number', unique=True) status = models.IntegerField(choices=STATUS, default=0) issue = models.ForeignKey(IssuePL, on_delete=models.CASCADE, related_name='pages') chapter = models.ForeignKey(ChapterPL, on_delete=models.CASCADE) image = models.ImageField('Page image', upload_to=get_image_pl_filename, blank=True) views.py def ComicPagePL(request, slug, number): comic_page_pl = get_object_or_404(PagePL, chapter__slug=slug, number=number, status=1) context = { 'comic_page_pl': comic_page_pl, } return render(request, 'comics/comic_page_pl.html', context) urls.py urlpatterns = [ path('comics/', views.IssueListPL, name='comics_pl'), path('comics/<slug>/<number>', views.ComicPagePL, name='comic_page_pl'), ] issue list template <div class="container"> <div class="row d-flex justify-content-center"> <div class="col-md-10 mt-3"> {% if issue_pl %} {% for issue in issue_pl %} <a href="#"><img src="{{ issue.cover.url }}" class="issue-thumbnail" alt="{{ issue.title }}" title="{{ issue.title }}" /></a> {% endfor %} {% else %} <div class="container"> <div class="row"> <div class="col-md-12"> <p style="text-align:center">BRAK ZESZYTÓW</p> </div> </div> </div> {% endif %} </div> </div> Now when you go to .../chapter-slug/page-number it works. I would like to make it that if you click on issue one it goes to the first page of …