Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Accessing a Django app on a servers private IP/vpn tunnel
I am trying to access a django app via a private ip, i configured a vpn site to site with another server (server2) so that the server2 could access the app via a private ip i created (192.xx.xx.xx) on server1. Now the tunnel is up and running but when server2 try to reach the django app on server1 through the private ip, the django app is not reached. The app uses nginx as a web server and gunicorn as the application server. Below are both config files nginx.conf server { listen 80; server_name 197.xxx.xx.xx 192.xxx.xx.xx; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; client_max_body_size 20M; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /var/www/project_folder/project/settings; } location /media/ { root /var/www/project_folder; } location / { include proxy_params; proxy_pass http://unix:/var/www/project_folder/project.sock; }} gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=root Group=www-data WorkingDirectory=/var/www/project_folder ExecStart=/var/www/env/bin/gunicorn --workers 3 --bind unix:/var/www/project_folder/project.sock project.wsgi:application [Install] WantedBy=multi-user.target settings.py ALLOWED_HOSTS = ['197.xxx.xx.xx','192.xxx.xx.xx'] In the above snippets the 197.xxx.xx.xx is the server1's public ip while 192.xxx.xx.xxis the server1's private ip. So server to is not able to call the django app through server1 private ip. I can see that serve2 is reaching server1 through nginx access logs but nothing in the nginx … -
Efficient way to retrieve information to JSON representation that is linked by multiple foreignkey connections in Django?
I am writing a view in django that grabs a set of objects from the database and returns JSON. Each object in the database is part of a hierarchy formed by foreignkey relationships. For instance, let's say I grab a group of "Metric" objects, and each metric object is linked to an "Objective" object, and each "Objective" object is linked to a "Client" object, and I'd like for each Metric to have in its JSON representation which Client it is related to So instead of returning { "model":"metric", "fields":{"objective":1 ...} } for each metric I could return { "model":"metric", "client":"client_name", "fields":{"objective":1 ...} } Obviously I could brute force it, but I feel like there is likely a clean way to solve this I am unaware of. -
Django & React with django-webpack-loader vs Decoupled App structure linked to Rest API?
I am reading through the following tutorial: http://v1k45.com/blog/modern-django-part-1-setting-up-django-and-react/ I can't quite grasp what the added value is of using something like django-webpack-loader to fully integrate react.js and django when you can completely decouple django from react, running a separate frontend which links to a DRF rest api. I may be comparing apples to oranges here, but I am not sure. Any help ? -
Django: how to loop through nested Json object in html
I am new to json, and I have a nested json object called jresult in django view.py. I passed this object to html and I wanna display it in html. in view.py: return render(request,'home.html', {'jresult': jresult}) jresult: { "company": "xxx", "address": "xxx", "ceo": "xxx, "employee": { "Emily": { "id": "xxx", "gender": "xxx" }, "Tom": { "id": "xxx", "gender": "xxx" }, "Alex": { "id": "xxx", "gender": "xxx" }, }, } So far I can only loop through the employee's name and display them in the html page: Emily, Tom and Alex by the following html code: {% for obj in jresult.employee %} <p>{{obj}}</p> {% endfor %} how can I access the id and gender as well, I have tried {% for obj in jresult.employee %} <p>{{obj}}</p> {% for item in jresult.scans.object.gender %} <p>{{item}}</p> {% endfor %} {% endfor %} but it doesn't work. Any helps will be appreciated. -
How to correctly upload of photos/files in a Django + Angular decoupled application?
I have a decoupled applications build with Django 2, an API with DRF and an Angular 6 frontend application. I want to enable users to upload photos for their profiles, and probably in the future some pdfs, and after some research I figured out that the most convenient thing to do would be to store these files in an Amazon S3 bucket. I have found numerous resources about how to upload files to an S3 bucket on both, Angular and Django, and now I was wondering what would be the best approach to do this in my decoupled application: should I manage it on the frontend and not use my backend at all? or should I pass the file from my angular to my Django app and then upload it to the bucket from there? Some pros and cons of both approaches? It's my first time doing this and I haven't been able to find many resources for decoupled applications. Any help is welcome! thanks! -
Django Rest Framework SerializerMethodField only on GET Request
Running into a little snag here with my DRF backend. I am populating fields with choices on certain models. I have a foreign key requirement on one model. When I create the model I want to save it under the foreign id. When I request the models, I want the model with whatever the choice field maps to. I was able to do this with SerializerMethodField, however when I try to create a model, I get a 400 error because the block is not valid. If I remove the SerializerMethodField, I can save, but get the number stored in the db from the request. Any help would be appreciated. class BlockViewSet(ModelViewSet): model = apps.get_model('backend', 'Block') queryset = model.objects.all() serializer_class = serializers.BlockSerializer permissions = ('All',) def create(self, request, format=None): data = request.data data['user'] = request.user.id data['goal'] = WorkoutGoal.objects.get(goal=data['goal']).id block = serializers.BlockSerializer(data=data, context={'request': request}) if block.is_valid(): new_block = block.save() return Response({'block': {'name': new_block.name, 'id': new_block.id}}, status=status.HTTP_201_CREATED) else: return Response(block.errors, status=status.HTTP_400_BAD_REQUEST) class WorkoutGoalSerializer(serializers.ModelSerializer): class Meta: model = apps.get_model('backend', 'WorkoutGoal') fields = ('goal',) goal = serializers.SerializerMethodField(read_only=True, source='get_goal') def get_goal(self, obj): return dict(WorkoutGoal.GOALS).get(obj.goal) class BlockSerializer(serializers.ModelSerializer): workout_count = serializers.IntegerField(required=False) completed_workouts = serializers.IntegerField(required=False) goal = WorkoutGoalSerializer() class Meta: model = apps.get_model('backend', 'Block') read_only_fields = ('workout_count', 'completed_workouts') fields … -
Django to Angular 6: CSRF token missing or incorrect even though it's set in the headers
I am trying to make a POST request from an Angular 6 app to a Django backend. Even though I include the csrf token in the headers, Django is logging a 403 Forbidden error as "CSRF token missing or incorrect". My code is as follows (with extraneous headers in my attempts to satisfy Django): Angular Component: import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { SharedService } from '../../shared.service'; import { CookieService } from 'ngx-cookie-service'; @Injectable({ providedIn: 'root' }) export class EmailService { // http options used for making any writing API calls with csrf token private httpOptions: any; csrfToken; constructor(private http: HttpClient, private cookieService: CookieService) { // Set the csrf token this.http.get(SharedService.contactEmailUrl).subscribe((data) => (this.csrfToken = data['csrfToken']), (error1) => console.log(error1)); } sendMailgunContactMessage(payload) { // Configure CSRF token header options this.httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded', 'X-CSRFToken': this.csrfToken, 'x-csrftoken': this.csrfToken, 'X-XSRF-TOKEN': this.csrfToken, 'XSRF-TOKEN': this.csrfToken, 'X-CSRF': this.csrfToken, csrfmiddlewaretoken: this.csrfToken, csrftoken: this.csrfToken }), withCredentials: true }; let body = { csrfmiddlewaretoken: this.csrfToken, content: payload }; return this.http.post(SharedService.contactEmailUrl, body, this.httpOptions); } } Django Settings: # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for … -
send data to server using post ajax
Im new to django, I want to send data to server using post ajax, and retrieve returned data. I knew that ajax works properly, since I was successful doing GET request, but when I do POST request, I did not receive any response data from server. Thank you in advance. =========views.py========= def validate_username_(request): if request.method == "POST" and request.is_ajax(): description = request.POST.get('the_post') projects = Project.objects.filter(Q(user__id__icontains = request.user.id)).filter(project__pro_description__icontains = description).values_list('pro_description') response_data = {} try: response_data['result'] = 'Success' response_data['message'] = list(projects) except: response_data['result'] = 'Unsuccessful' response_data['message'] = 'The Subprocess module did not run the script correctly.' data = { 'projects': Project.objects.filter(pro_description__icontains = description) } return HttpResponse(json.dumps(response_data), content_type="application/json") =================index.html=========== {% extends 'base.html'%} <head> <meta charset = "utf-8"> <meta name = "viewport" content = "width = device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous"> <!-- {% load static %} <link rel="stylesheet" href = "{% static 'polls/style.css'%}" type = "text/css"> --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script> <title>this is index page!!</title> </head> {% block body %} <div class = "container"> <!-- <form name="search_form" action="{ url 'search' %}" --> <div class = "pagination"> <input type = "text" id = "talk"></input> <table class = "table table-hover table-dark"> <div class="container"> <form name="search_form" method="POST"> {% csrf_token %} <tr> <td>No<input type = … -
Python - Django - Generic Fields Model design
I need some ideas to solve the following issue, maybe with some design pattern or another approach in my current architecture. My app's backend is entirely developed in Django framework and has five current models (no matter relationships between them): Product(id, product_name, product_category, product_code) Customer(id, customer_name) Account (id, account_code, account_name) City(id, city_name) User(id, email, user_name) In first place, I need to add a new model to dynamically and easily create Transactions with any possible combination of the above models in the following way: Example 1: Transaction(id, product, customer, year, month, amount) Example 2: Transaction(id, account, year, month, amount) Example 3: Transaction(id, account, city, year, month, amount) Example N: Transaction(id, product, user, year, month, anount As you can see, my Transaction model has a few static fields (year, month, amount), but the other fields depends on a random customization according the use case. I've thought something like Transaction(id, dynamic_field_1, dynamic_field_2, dynamic_field_3, year, amount), but how can I make it dynamically? Is there some design pattern or properly way to do this? In addition, I need that those fields have been validated from the previous models. For example: Transaction(id, product, customer, year, month, amount): validate that product exist in the database validate … -
Django - get id from selected choice in data list from form
How can I get the id="" from my options in the form below in the request.POST.items() in my views.py? request.POST.items() only shows the name of the datalist and the value="". I would like the id="" and the value inbetween Any help is appreciated. <input list="myDatalist" name="security"> <datalist id="myDatalist"> {% for security in securities %} <option id="{{ security.id }}" value="{{ security.shortname }}">{{ security.isin }} {{ security.security_currency }}</option> {% endfor %} </datalist> <input type="submit" value="Submit" /> -
Django multiple left joins
I would like to know how to implement in Django the following left join sql query. I already know about Person.objects.raw() select person.name, phone.number, email.emailaddr, home.address from person left join phone on person.id = phone.person_id left join email on person.id = email.person_id left join home on person.id = home.person_id; assuming the following model: class Person(models.Model): name = models.CharField(max_length=30) class Phone(models.Model): number = models.CharField(max_length=30) person = models.ForeignKey('Person') class Email(models.Model): emailaddr = models.CharField(max_length=30) person = models.ForeignKey('Person') class Home(models.Model): address = models.CharField(max_length=30) person = models.ForeignKey('Person') -
wagtail customizing generatrf admin from for parentalkey
In Wagtail document, I find an explanatory example showing how you can customize the behavior of admin form adding a few validation and save perks: from django import forms import geocoder # not in Wagtail, for example only - http://geocoder.readthedocs.io/ from wagtail.admin.edit_handlers import FieldPanel from wagtail.admin.forms import WagtailAdminPageForm from wagtail.core.models import Page class EventPageForm(WagtailAdminPageForm): address = forms.CharField() def clean(self): cleaned_data = super().clean() # Make sure that the event starts before it ends start_date = cleaned_data['start_date'] end_date = cleaned_data['end_date'] if start_date and end_date and start_date > end_date: self.add_error('end_date', 'The end date must be after the start date') return cleaned_data def save(self, commit=True): page = super().save(commit=False) # Update the duration field from the submitted dates page.duration = (page.end_date - page.start_date).days # Fetch the location by geocoding the address page.location = geocoder.arcgis(self.cleaned_data['address']) if commit: page.save() return page class EventPage(Page): start_date = models.DateField() end_date = models.DateField() duration = models.IntegerField() location = models.CharField(max_length=255) content_panels = [ FieldPanel('title'), FieldPanel('start_date'), FieldPanel('end_date'), FieldPanel('address'), ] base_form_class = EventPageForm All and all it shows how you can ensure date fields are set correct before saving the form and so on. Great, my question then will be if the form contains a parentalkey field ?? like this: class EventPage(Page): start_date = … -
How to call custom method in class based views
I was using function based views and was getting output correctly. However when I changed it to class based views while invoking function I am getting error Method Not Allowed (POST): -
Django model iterator
I have a pretty fundamental question about Django models. I have a model for clinic patients (inherits from models.Model) that consists of charfields, integerfields, one textfield, and one emailfield. The types associated with these fields are limited to ASCII characters (I think) so I dont believe any low-level redefinition SHOULD be necessary. Say, though, that I have a Patient object x. I want to be able to iterate through the various fields in that object and print the corresponding values to a template. I specifically do NOT want to hardcode the value/field names as I have been doing so far in case the model itself is altered later on. Example -> {% for value in x %} <p> {{ value }} </p> {% endfor %} I understand that, as with almost any custom class, I must write an __ iter __ method to detail how to iterate through this Patient object. I do not know how to write this method. I do not know if I also need to write a __ next __ method. My attempts at creating something like this have been met with discouraging, almost disparaging errors. Pls halp :) -
How to remove help text and label from django_filters
I've trying to remove the help text and label from my filter, because but without success, How can I do it ? filters.py import django_filters from oportunity.models import * class BlogFilter(django_filters.FilterSet): class Meta: model = Oportunity fields = {'title': ['contains'],} html {% load static %} {% load crispy_tags_forms %} <div class="row"> <div class="mt40 mb20"> <form method="get"> <div class="input-group pull-right" style="width: 300px;"> {{ filter.form|crispy }} <span class="input-group-btn"> <button class="btn btn-success" type="submit">Pesquisar</button> </span> </div> </form> </div> </div> -
403 Client Error: Forbidden for url: https://api.twitter.com/oauth/request_token
I am trying to add twitter credential to my login system, I keep getting 403 Client Error, I read this but doesn't have an answer. I followed the steps mentioned here no luck. I tried these patterns with Callback URL no luck: http://127.0.0.1/ http://127.0.0.1:8000/ http://127.0.0.1/complete/twitter/ http://127.0.0.1/oauth/complete/twitter/ website URL doesn't accept localhost so I put my old website which is not working at the moment. Please help, what's wrong with setting up twitter credential api? -
Apply background image to div in djangi using javascript
I am building a quiz app using django where on Q.4 I have to display an image in the django template using javascript. I tried this in my .js file but didn't succeed: document.getElementById("img").style.backgroundImage="url('images/image_name.jpg')"; Here images is the subdirectory in static directory. The error I am getting is: Not Found: /quiz/images/image_name.jpg Here is my main urls.py : from django.contrib import admin from django.urls import path,include urlpatterns = [ path('quiz/',include('blogsite.urls')), path('admin/', admin.site.urls), ] -
Populate specific json value to html with django template
I am new to json and not familiar with it. In my Django view file, I want to pass only certain json values: school, address, each student's name (Andy, Tom, Jack) and id (Andy.id, Tom.id, Jack.id) to the html from Django view. How can I achieve the above case? my json content is: { "school": "xxx", "address": "xxx", "number": "xxx, "students": { "Andy": { "id": "xxx", "add": "xxx" }, "Tom": { "id": "xxx", "add": "xxx" }, "Jack": { "id": "xxx", "add": "xxx" }, }, } In my view.py, I have got these codes. jresult is the json string and I used json.dumps() to generated JSON, but it will populate all the json data to the html. How can I achieve the above case? Any helps will be appreciated. def model_form_upload(request): if request.method == 'POST': form = FileForm(request.POST, request.FILES) if form.is_valid(): file = request.FILES['file'].read() jresult = execution(file) json_string = json.dumps(jresult, indent=4) return render(request, 'virus/home.html', {'json_string': json_string}) else: form = FileForm() return render(request, 'virus/upload.html', { 'form': form }) my home.html template: <body> <pre>{{ json_string|safe }}</pre> </body> -
Nginx redirects to https://web
My webapp was working fine until today, when my domain stopped working. I was using example.com:8000/ to reach my Django app, but now it redirects me to https://web/. I've tried to go back to previous commits, but the issue does not disappear. My nginx.conf looks like: upstream web { ip_hash; server web:8000; } # portal server { location /static/ { autoindex on; alias /static/; } location / { proxy_pass http://web/; } listen 8000; server_name localhost; } docker-compose.yaml looks like: version: '3' services: nginx: image: nginx:latest container_name: ng01 ports: - "8000:8000" volumes: - ./code:/code - ./code/nginx:/etc/nginx/conf.d - ./static:/static depends_on: - web web: build: . container_name: dg01 command: bash -c "python manage.py makemigrations && python manage.py migrate && gunicorn fortex.wsgi -b 0.0.0.0:8000" volumes: - .:/code - ./static:/static expose: - "8000" depends_on: - db db: image: postgres container_name: ps01 volumes: - pg_volume:/var/lib/postgresql/data volumes: pg_volume: {} Nginx redirects without logging, but when I use incognito in chrome it logs normally but still redirects me. -
Django session authentication failed sometimes
I'm having very weird issue with session authentication. I'm using session authentication over DRF APIs for some legacy django views. And login process implemented with DRF and react app. The server code for sign-in looks like this: class AuthViewSet(viewsets.ViewSet): def create(self, request, *args, **kwargs): is_session_auth = request.data.get('session_auth', False) serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) token = serializer.save() if is_session_auth is True: login(request, token.user) return Response(dict(token=token.key)) So, as far as I expected, the response should has set-cookie header which makes browser to set sessionid and csrftoken cookies. And it works well most of times. But rarely, some users experiencing login failures. I'm faild to reproduce it, but this is what they describe: When user submit sign in form, the request sent to the server and got response successfully. Then the javascript app push url to login/complete, as expected. But in login complete view, the request failed to authenticate. And the view redirect request to the original login view. User retry login, but got same result. I have no idea how this happened so rarely, to the so small amount of users. Am I miss something? Thanks for help. -
Django in production, can store media file but cannot find it
I have just launched my project into production. I have a functionality where the user can upload their own profile picture. People can upload their pictures, it is even stored in the correct directory. However, when I try to achieve it I get a 404 not found error. I am using Pythonanywhere and all pictures are stored at path: home/[username]/[project_name]/media/profile_picture Here are the relevant code snippets: settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py urlpatterns = [ ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py class Person(models.model): ... profile_picture = models.ImageField(upload_to="profile_picture", blank=True, null=True) ... profile_page.html ... <div class="photo-container"> {% if profile.profile_picture %} <img src="{{ profile.profile_picture.url }}"> {% else %} <img src="{% static 'external_page/assets/img/placeholder.png' %}"> {% endif %} </div> ... When I isolate the tag: {{ profile.profile_picture.url }} I get: /media/profile_picture/[name_of_image_file].jpg -
How to send user notifications using django-channels 2.0?
I am working on a chat app that has Rooms. Each room has two users. A user can be in multiple rooms i.e, a user has multiple rooms. And now he is chatting in one room. But he receives a message in another room. I would like to notify about the message from other room to the user. How should I implement this? Currently a websocket connection is established as: ws://localhost:8000/chat/int<room_id>/ And the group_name is named as "room"+room_id. and So far I have: async def connect(self): room_id = self.scope['url_route']['kwargs']['room_id'] await self.channel_layer.group_add( "room"+room_id, self.channel_name ) await self.accept() async def receive(self, text_data): await self.channel_layer.group_send( self.room_name, { 'type': 'chat_message', 'message': json.loads(text_data) } ) async def chat_message(self, event): await self.send(text_data=json.dumps({ 'message': event['message'] })) Django 2.x django-channels 2.x python 3.6 -
Django 1.11 many to many does not appear in django admin
Hi i have a django model for notification which have a many-to-many relation but nothing appears in django admin ( all fields do not appear) class Notification(models.Model): """send notification model""" title = models.CharField(max_length=200) text = models.TextField(null=True, blank=True) device = models.ManyToManyField(Device, null=True, blank=True) country = models.ManyToManyField(Country, null=True, blank=True) sent = models.BooleanField(default=False) when i open django admin for this model and press add notification this is what happens (nothing appears) -
DRF ImportError: cannot import name 'action' on v3.8.2
Why am I getting this error? I'm running v 3.8.2 of DRF. I'm wondering if docker has anything to do with it. Maybe the interpreter is trying to use/find some other installation I have on my machine. Any suggestions/help would be great. Thanks This line is failing from rest_framework.decorators import action I'm replacing the list_route method to action on this line @action(methods=['POST'], permission_classes=[IsAuthenticated, ]) I'm running a virtualenv created in pycharm and running pip freeze gives me: $ pip freeze ... Django==1.10.8 django-extensions==2.1.0 django-rest-swagger==2.2.0 django-widget-tweaks==1.4.1 djangorestframework==3.8.2 ... backend_1 | Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7fa4163708c8> backend_1 | Traceback (most recent call last): backend_1 | File "/usr/local/lib/python3.6/site-packages/django/utils/autoreload.py", line 226, in wrapper backend_1 | fn(*args, **kwargs) backend_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run backend_1 | self.check(display_num_errors=True) backend_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 374, in check backend_1 | include_deployment_checks=include_deployment_checks, backend_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 361, in _run_checks backend_1 | return checks.run_checks(**kwargs) backend_1 | File "/usr/local/lib/python3.6/site-packages/django/core/checks/registry.py", line 81, in run_checks backend_1 | new_errors = check(app_configs=app_configs) backend_1 | File "/usr/local/lib/python3.6/site-packages/django/core/checks/urls.py", line 14, in check_url_config backend_1 | return check_resolver(resolver) backend_1 | File "/usr/local/lib/python3.6/site-packages/django/core/checks/urls.py", line 24, in check_resolver backend_1 | for pattern in resolver.url_patterns: backend_1 | File "/usr/local/lib/python3.6/site-packages/django/utils/functional.py", line 35, in __get__ backend_1 … -
How do I access images uploaded through a formset in Django?
I cannot seem to find a way to iterate through the files uploaded by the formset, although the files are uploaded as the code indicates. When I load the page it shows 1-3 "img src=(unkown)" tags. It shows 3 when I upload 2 images and 1 when I upload 1 image. Template view-post: {% block body %} <div class="container"> <div class="col-md-8"> <p> <h1>{{ post.title }}</h1> <h4>{{ post.body }}</h4> <p> Posted by {{ post.user }} on {{ post.created_date }} {% if not post.created_date == post.updated_date %} and updated on {{ post.updated_date }} {% endif %} </p> </p> {% for img in images %} <img src="{{ img.url }}" width=360> {{ img.url }} <br> {% endfor %} </div> <div class="col-4-md"> {% if post.cover_image %} <img src="{{ post.cover_image.url }}" width=240> {% endif %} </div> </div> {% endblock %} Here I use filter, not get, so it should give me a list of the images connected via foreignkey to the right post. The post here is displayed as it should be, along with the internal cover image and text in the post. View view-post: class ViewPost(TemplateView): template_name = 'posts/view_post.html' context_object_name = 'view_post' def get(self, request, pk): post = Post.objects.get(pk=pk) images = Images.objects.filter(post=post) args = {'post': …