Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Python websocket API [closed]
I am trying to develop a Django websocket API. I want this websocket api to be kind of generic which i mean to be connected from different programing languages like java etc. Please help me out if this can be done. -
Django REST framework is powerfull?
is Django REST framework good for big amount of request can use the Django REST framework for big API projects? and Django will not decrease the speed of the API? I'm using Swagger with Django, and there is another options to create API like Fast API which is not Dependent on Django. so the question Django REST framework is power full enough or i should use some other options? -
How to add punctuation in django email message body
I am building an app that allows users to send emails to preferred email addresses. I am having trouble adding punctuation marks to the message body and getting a ValueError Invalid address; only 'Glo' could be parsed from "Glo; Flo." when I try to send the email. views.py def emailView(request): if request.method == 'POST': form = ContactForm(request.POST, request.FILES) if form.is_valid(): form.save() name = form.cleaned_data['name'] subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] tagline_one = form.cleaned_data['tagline_one'] tagline_two = form.cleaned_data['tagline_two'] recipient = form.cleaned_data['recipient'] msg = loader.render_to_string( 'email_portal/email.html', { 'name': name, 'subject': subject, 'message': message, 'tagline_one': tagline_one, 'tagline_two': tagline_two, } ) try: #message = str(text) recipient_list = [recipient, ] send_mail(subject, name, message, recipient_list, auth_user=None, auth_password=None, fail_silently=True, html_message=msg,) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('/') else: form = ContactForm(request.POST, request.FILES) return render(request, "email_portal/index.html", {'form': form}) I don't know how to go about this any help will be appreciated -
django - filtering via ManyToMany field
Let's say I have models like this: class Pizza(models.Model): name = models.CharField(max_length=100) class Topping(models.Model): name = models.CharField(max_length=100) class Flavor(models.Model): name = models.CharField(max_length=100) of_topping = models.ForeignKey(Topping, on_delete=models.CASCADE) on_pizzas = models.ManyToManyField(Pizza) Then, I have topping "Salami" with flavors "spicy", "non-spicy" and "italian", a topping "Fungus" with flavors "Champignon", "Boletus" and "Fly agaric". A pizza is constrained such that it cannot contain two toppings of the same Topping class but with different flavors. (e.g. there is no Pizza with both italian and spicy salami). Now, let's say my pizzaria offers those pizzas: Margherita (no toppings) Salami (non-spicy salami) Funghi (Champignon) Yummy (italian salami and Champignon) Toxic (spicy salami and fly agaric) Special (italian salami and Boletus) Now, for a customer Bob, I know is constraints, e.g. he would eat Champignon and italian salami (but would also eat anything that has only a subset of those as toppings). For Bob, I would no like to find out, that I could offer him Margherita, Funghi or Yummy. For each customer, the list of constraints will only include (at most) one flavor per topping. So there would be no customer who says that she likes both spicy and non-spicy salami. How do I write a filter … -
how to setup microsoft visual studio c++ for misaka in vs code
I have installed microsoft visual c++ compiler for installing misaka but do I have to include it somewhere int the path because it is still showing error in installing. ERROR: Command errored out with exit status 1: command: 'c:\users\akanksha sharma\desktop\project 2\be_a_socialstar\be_a_socialstar\scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\akanksha sharma\\AppData\\Local\\Temp\\pip-install-c9tjt7_3\\misaka_25def6025d584d6f8ac1394be9c2f041\\setup.py'"'"'; __file__='"'"'C:\\Users\\akanksha sharma\\AppData\\Local\\Temp\\pip-install-c9tjt7_3\\misaka_25def6025d584d6f8ac1394be9c2f041\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\akanksha sharma\AppData\Local\Temp\pip-record-9ogyd3l2\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\akanksha sharma\desktop\project 2\be_a_socialstar\be_a_socialstar\include\site\python3.8\misaka' cwd: C:\Users\akanksha sharma\AppData\Local\Temp\pip-install-c9tjt7_3\misaka_25def6025d584d6f8ac1394be9c2f041\ Complete output (17 lines): running install running build running build_py creating build creating build\lib.win-amd64-3.8 creating build\lib.win-amd64-3.8\misaka copying misaka\api.py -> build\lib.win-amd64-3.8\misaka copying misaka\callbacks.py -> build\lib.win-amd64-3.8\misaka copying misaka\constants.py -> build\lib.win-amd64-3.8\misaka copying misaka\utils.py -> build\lib.win-amd64-3.8\misaka copying misaka\__init__.py -> build\lib.win-amd64-3.8\misaka running build_ext generating cffi module 'build\\temp.win-amd64-3.8\\Release\\misaka._hoedown.c' creating build\temp.win-amd64-3.8 creating build\temp.win-amd64-3.8\Release building 'misaka._hoedown' extension error: Microsoft Visual C++ 14.0 is required. Get it with "Build Tools for Visual Studio": https://visualstudio.microsoft.com/downloads/ ---------------------------------------- ERROR: Command errored out with exit status 1: 'c:\users\akanksha sharma\desktop\project 2\be_a_socialstar\be_a_socialstar\scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\akanksha sharma\\AppData\\Local\\Temp\\pip-install-c9tjt7_3\\misaka_25def6025d584d6f8ac1394be9c2f041\\setup.py'"'"'; __file__='"'"'C:\\Users\\akanksha sharma\\AppData\\Local\\Temp\\pip-install-c9tjt7_3\\misaka_25def6025d584d6f8ac1394be9c2f041\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\akanksha sharma\AppData\Local\Temp\pip-record-9ogyd3l2\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\akanksha sharma\desktop\project 2\be_a_socialstar\be_a_socialstar\include\site\python3.8\misaka' Check the logs for full command output. please help me figuring out the error. -
Django Admin cannot access file outside Admin
in my django project when in Admin i have to connect to a MQTT broker and pass path related to certs. My main projects structs is: |manage.py |... |backend |____init__.py |_mqtt_manager.py |mqtt_site |__init__.py |_certs-mqtt |_client |_ca.crt |_... Well, from Django Admin, if user update a model i use signals for call my `mqtt_manager.py function that try to connect to a MQTT server using path for Crt: mqtt_ca_crt = os.getenv('MQTT_CA_CRT') or '/mqtt_site/certs-mqtt/client/ca.crt' mqtt_cli_crt = os.getenv('MQTT_CLI_CRT') or '/mqtt_site/certs-mqtt/client/client.crt' mqtt_cli_key = os.getenv('MQTT_CLI_KEY') or '/mqtt_site/certs-mqtt/client/client.key' but when my signals trigger i get FileNotFoundError at /admin/mqtt_site/device/MSU152423/change/ How can i ask Django about file location whithout admin path? So many thanks in advance -
Obtaing Max Allowed Value of PositiveSmallIntegerField Django Field
I have the following PositiveSmallIntegerField attached to a Model as follows: class Proficiency(models.Model): class Meta: verbose_name = 'Proficiency' verbose_name_plural = 'Proficiencies' ... ... rating = models.PositiveSmallIntegerField(default=0, validators=[MinValueValidator(0), MaxValueValidator(10)]) I have to do some complex calculations (*which can't be done within the ORM as far as I can see) on an endpoint which returns an average value: The calculation turns out to be: candidate['average'] = (candidate['total'] / count) * maximum_value_of_proficiency_rating_field i.e., maximum_value_of_rating_field is 10. Inspection of this field, and some digging into object attributes etc has lead me to find 10 dynamically as the following: proficiency._meta.get_field('rating')._validators[1].limit_value However, I was wondering if there was a simpler way to find the maximum value of a PositiveSmallIntegerField... i.e., either whatever value passed into the MaxValueValidator(10) i.e., "10" or if there is no MaxValueValidator, then 32767. I was thinking something like maybe a method would return this safely, or maybe an attribute on the field, i.e.,: proficiency.rating.get_maximum_value() or proficiency.rating.max_value Does anyone know if there is such a class method or attribute on the field to do this? -
Bootstrap dual list box POST Selected
I'm trying to post selected data from Bootstrap dual list (https://www.virtuosoft.eu/code/bootstrap-duallistbox/) do django. I'm using example code from https://codepen.io/jaredbell/pen/OejgMe. Problem occurs when i try to send selected items to view in django - i'm always getting one selected item instead of multiple selected items. Given example from https://codepen.io/jaredbell/pen/OejgMe showing selected items with js alert script works well but when I try to get selected items with django there is always one selected item instead of list of selected items. If you have any ideas i would be very appreciate. Regards django ( views.py ): if request.method=='POST': q=request.POST.get('duallistbox_demo1[]','') return HttpResponse(q) # always one item html: same code as https://codepen.io/jaredbell/pen/OejgMe -
Django - Why is the folder in html are not able to read?
I'm new to Django and just started to create an app and still learning. Right now, I'm actually in a part where I'm trying to call the HTML file. But I don't understand why if I put the line like this below. I get an error saying TemplateDoesNotExist:- views.py def index(request): return render(request, "hello/index.html") But if I put the line like this, it works like a charm:- views.py def index(request): return render(request, "index.html") but by the way, I create a new folder name templates under hello and another new folder hello under the templates and inside there is a file index.html was placed. The directory view:- lecture3/hello/templates/hellp/index.html Can anybody help me to understand why such an occurrence can happen? -
Is there any good tutorial for django leaflet which uses raster tiles? [closed]
I am creating a website using django leaflet. I want to create a world map and want to set colors of different regions according to my data by a region name. For this purpose, I am trying to use raster tiles, but I do not know how to do it. I am working on leaflet first time. I need some help. Thank you in advance. -
How to show this blog django backend by its id in react frontend
models class Blog(models.Model): title = models.CharField(max_length=50) content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) serializers class BlogSerializer(serializers.ModelSerializer): class Meta: model = Blog fields = '__all__' views class BlogDetailView(generics.RetrieveUpdateDestroyAPIView): queryset = Blog.objects.all() serializer_class = BlogSerializer and urls from django.urls import path from .views import BlogDetailView urlpatterns = [ path('blog/<int:pk>/', BlogDetailView.as_view()), ] I'm trying to make a blog website. How can we show blogs by id in react js -
My deployed django app fail to load static files even collectstatic fail to fix
My django web app failed to load static files even after collecting all static files with manage.py collectstatic, I tried to look for solution but i failed to help. The deployment was done by uploading files from github repositories so they were accommodated in repositories/surveyapp folder. github link is https://github.com/carlomoan/surveyapp -
500 Server Error in my Django App in App Engine (Google Cloud)
I am new to Google Cloud an I followed the steps in https://cloud.google.com/python/django/appengine and deployed the App successfully. However, when I go to the page https://PROJECT_ID.REGION_ID.r.appspot.com the next message is displayed: Error: Server Error The server encountered an error and could not complete your request. Please try again in 30 seconds. I have seen this is something really usual but cannot find any useful solution. I would appreciate any help. -
django rest powered by json using nosql
I'm trying to develop an REST app which is flexible in term's of fields, means new fields can be added or removed dynamically, fields can be powered using json. for example, Here is json, can be edited at runtime to add new field or remove existing field, { "model": "MyModel", fields:{ "title": "CharField", "description": "CharField" } } Serializer can be, class MyModelSerializer(serializers.ModelSerializer): class Meta = MyModel How to achieve this ? Any guidance/ suggestion appreciated. -
save an instance of object in two models simultaneously
I am trying to create a route that will track all the history of a product. I have created a model for the product and a similar model for producthistory. Now, whenever I am creating an object I want it to be saved in the product table as well as the producthistory table. The only difference in both the tables is the id field. The producttable contains the id of the product & the producthistorytable has an id field of the historytable as well as the id of the product. I want to filter with the id of the product for further usage of the data. How can I insert the product object in the producthistory table along with the id of the product that was created at that point in time? Here is the models: class Product(Base): __tablename__ = "product" id = Column(Integer, primary_key=True, index=True) product_url= Column(String) current_price= Column(Integer) updated_at= Column(String) created_at= Column(String) target_price= Column(Integer) product_name= Column(String) class ProductHistory(Base): __tablename__ = "producthistory" id = Column(Integer, primary_key=True, index=True) product_id = Column(Integer) product_url= Column(String) current_price= Column(Integer) updated_at= Column(String) created_at= Column(String) target_price= Column(Integer) product_name= Column(String) here is the logic for creating product: @app.post('/createproducts/') def createproducts(request: Product, db:Session = Depends(get_db)): product = models.Product( … -
Django fat model update field reference model
i have two models: class Demand(models.Model): name = models.CharField(max_length=500) status = models.CharField(max_length=50, default="PREPARE") insert_user = models.ForeignKey(User, on_delete=models.PROTECT, editable=False) insert_date = models.DateTimeField(default=datetime.datetime.now, editable=False) def __str__(self): return self.name def submitt(self, *args, **kwargs): if self.pk : demand_detail = DemandDetails.objects.filter(demand_id = self.pk).update(status='SUBMITTED') self.status = 'SUBMITTED' self.save() class Meta: verbose_name = 'Demand' verbose_name_plural = 'Demand' class DemandDetails(models.Model): demand = models.ForeignKey(Demand, on_delete=models.CASCADE) component = models.ForeignKey(Component, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) comment = models.CharField(max_length=150, null=True, blank=True) status = models.CharField(max_length=50, default="PREPARE") insert_user = models.ForeignKey(User, on_delete=models.PROTECT, editable=False) insert_date = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): if not self.pk: try: super(DemandDetails, self).save(*args, **kwargs) except IntegrityError as e: obj = DemandDetails.objects.get(demand_id=self.demand_id, component_id=self.component_id) obj.quantity = obj.quantity + 1 obj.save() else: super(DemandDetails, self).save(*args, **kwargs) def __str__(self): return self.demand.name class Meta: verbose_name = 'Demand Detail' verbose_name_plural = 'Demand Details' constraints = [ models.UniqueConstraint(fields=['demand_id', 'component_id'], name='epm - DemandDetail (demand, component)' ) ] when I call the defined "submitt" method then I get this error: demand_detail = DemandDetails.objects.filter(demand_id = self.pk).update(status='SUBMITTED') NameError: name 'DemandDetail' is not defined how can i fix this error ? -
How to pass a variable from view1 which is inside view2 to view2's template in Django
I have a view home: def home(request): return render(request, 'detection/home.html') And here is its' template templates/detection/home.html: {% extends "detection/base.html" %} {% block content %} <h1>Camera View</h1> <img src="{% url 'cam-feed' %}"></img> {% endblock content %} which is based on templates/detection/base.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> {% block content %} {% endblock content %} </body> </html> In this view, as can be seen from home.html, I show camera output using view cam_feed: def cam_feed(request): return StreamingHttpResponse(gen(VideoCamera()), content_type="multipart/x-mixed-replace;boundary=frame") which uses the class VideoCamera which is an openCV class to show the camera and which outputs a prediction variable in get_frame: class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture(0) def __del__(self): self.video.release() def get_frame(self): _, image = self.video.read() ### All the detections # Person Existence Classification # RGB_img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) im = Image.fromarray(image) im = im.resize((128, 128)) img_array = np.array(im) img_array = np.expand_dims(img_array, axis=0) prediction = int(model.predict(img_array)[0][0]) # plt.imshow(RGB_img) # plt.show() if prediction == 0: print('You ARE here') else: print('You are NOT here') _, jpeg = cv2.imencode('.jpg', image) return jpeg.tobytes() cam_feed also uses function gen which passes the camera output in the appropriate form: def gen(camera): while True: frame = camera.get_frame() … -
How to Skip preview page (step 4 ) and redirect the user to Thank you page(Step 5) in Djnago-Oscar
I have been working on django-oscar, where i am integrating stripe prebuilt checkout page, i want to be able to achieve this 2 scenarios, Scenario 1: How to skip step 4(Preview) and redirect the user to the step 5(Thank you) without clicking on the "Place order" button on Preview page ? the rest functionality should work as it is. Scenario 2: How to make the preview page first and then the payment page after preview ? Let me know if you need more explanation or you want to see what i have done yet ? -
How to create env file in GCP for Django?
I was trying to create .env in GCP cloud build. The cloudbuild.yaml file steps: - name: 'python:3.8' entrypoint: python3 args: ['-m', 'pip', 'install', '-t', '.', '-r', 'requirements.txt'] - name: 'python:3.8' entrypoint: python3 args: ['touch', '.env'] env: - 'DATABASE_HOST=$$DB_HOST' - 'DATABASE_USER=$$DB_USER' - 'DATABASE_PASSWORD=$$DB_PASS' - 'DATABASE_NAME=$$DB_NAME' - 'FIREBASE_CREDENTIALS=$$FIRE_CRED' - name: 'python:3.8' entrypoint: python3 args: ['./manage.py', 'collectstatic', '--noinput'] - name: "gcr.io/cloud-builders/gcloud" args: ["app", "deploy"] timeout: "1600s" I've tried with several ways to do that but it's not yet solved. Created Substitution variable in GCP Trigger that I used in env. The problem is - name: 'python:3.8' entrypoint: python3 args: ['touch', '.env'] env: - 'DATABASE_HOST=$$DB_HOST' - 'DATABASE_USER=$$DB_USER' - 'DATABASE_PASSWORD=$$DB_PASS' - 'DATABASE_NAME=$$DB_NAME' - 'FIREBASE_CREDENTIALS=$$FIRE_CRED' This portion of the code. Thank you in advance. -
Django Application data not persisting for deployment
Currently developing a Django application to be deployed onto a digital ocean droplet. On this droplet there is 4 docker containers for: PostgreSQL, PGADMIN4, Django App, Certbot. In Django Admin (localhost), I have added some values to my database and they will be displayed throughout the web application. However, when I deploy my Django Application to the digital ocean droplet, this data is nowhere to be seen. I read that I can make a sql dump file of my local database and get the values on my droplet that way. But id rather another way if possible. I have done this process before but I was using a postgis database that came with a prebuilt database, whereas now I have to create a database again on my postgresql container (locally and on droplet). I am creating an image of my Django Application through a Docker file that I then push to dockerhub and pull to my digital ocean droplet. Any help is appreciated. Dockerfile ## ## Dockerfile to generate a Docker image ## # Start from an existing image with Python 3.8 installed FROM python:3.8 MAINTAINER Mark Foley # Run a series of Linux commands to ensure that # 1. … -
Highcharts Sankey Colors not working in django
Does anyone know why the sankey chart responds differently in a django compared to just an HTML file that is not in a server. The chart options and the data provided to them is the same and the chart definition is also the same but the rendering of the charts is different. For example, the colors in the server do not work yet on the static HTML they render perfectly. Kindly assist. Thanks -
Django REST framework HyperlinkedIdentityField format kwarg not working
I have just started looking into Django REST Framework and am following the tutorial in the official documentation. In this tutorial, we use HyperLinkedIdentityField for highlight attribute. We set the format kwarg to html. The tutorial states: Notice that we've also added a new 'highlight' field. This field is of the same type as the url field, except that it points to the 'snippet-highlight' url pattern, instead of the 'snippet-detail' url pattern. Because we've included format suffixed URLs such as '.json', we also need to indicate on the highlight field that any format suffixed hyperlinks it returns should use the '.html' suffix. The problem is that when I visit the snippet-list using the url http://127.0.0.1:8000/snippets/?format=json I get the highlight url as http://127.0.0.1:8000/snippets/1/highlight/?format=json while I expected it to be http://127.0.0.1:8000/snippets/1/highlight/?format=html because no matter what format we request the snippet-list url, the highlight link will always have HTML format. My code looks like this: highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight', format='html') class Meta: model = Snippet fields = ['url', 'id', 'highlight', 'owner', 'title', 'code', 'linenos', 'language', 'style'] Any help will be highly appreciated Thanks, -
Bootstrap + Django navbar not opening on toggle
I am attempting to use the collapsible navbar component provided by bootstrap. I believe I am not importing the correct libraries. Here is my base.html <!doctype HTML> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous"> <title>Course!</title> </head> <body> {% include 'navbar.html' %} {% block content %} {% endblock %} <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.bundle.min.js" integrity="sha384-b5kHyXgcpbZJO/tY9Ul7kGkf1S0CWuKcCD38l8YkeH8z8QjE0GmW1gYU5S9FOnJ0" crossorigin="anonymous"></script> </body> </html> And here is my navbar.html: <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="/"> <img src="http://getbootstrap.com/docs/4.0/assets/brand/bootstrap-solid.svg" width="30" height="30" alt=""> Navbar </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent" > <ul class="navbar-nav"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> </ul> </div> </nav> I am sure that the error is actually in base.html itself where I am not importing the correct scripts. Additionally, if it would be greatly appreciated if I could get advice on how to store these files locally. -
serializing foreing key variable in update method
I'm trying to override the update method of a serializer. This serializer have a field 'gear' which is a foreing key of the Trawl table. But when I try to save the updated instance in update method, I get the error: ValueError: Cannot assign "2": "Haul.gear" must be a "Trawl" instance This is the serializer: class HaulTrawlSerializer(serializers.ModelSerializer): gear = serializers.IntegerField() class Meta: model = Haul fields = ['id', 'haul', 'gear', 'valid', ] def update(self, instance, validated_data): if validated_data: for attr, value in validated_data.items(): print(attr, value) setattr(instance, attr, value) instance.save() return instance So I try to convert Haul.gear to a Trawl instance changing the update method: def update(self, instance, validated_data): instance.gear = Trawl.objects.get(pk=validated_data.pop('gear')) if validated_data: for attr, value in validated_data.items(): print(attr, value) setattr(instance, attr, value) instance.save() return instance And then, the error TypeError: int() argument must be a string, a bytes-like object or a number, not 'Trawl' is thrown and I don't understand it. Why first ask for a Trawl instance, but after ask for a int? -
Get Page_not_found on Django project
I got page_not_found when try to use url: from django.urls import path from . import views urlpatterns = [ path('api/v1/posts/int:post_id/', views.get_post, name='get_post'), ] To my view function in small Django project: from django.http import JsonResponse from rest_framework.response import Response def get_post(post_id): if request.method == 'GET': post = get_object_or_404(Post, id=post_id) serializer = PostSerializer(post) return JsonResponse(serializer.data) Asking for help)