Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Fix AJAX Filtered Product List that does not render images in Django Ecommerce Project?
I am trying to implement filter functionality in my Ecommerce Project. I ran into some problem when I generated filtered product list using AJAX, the products are all showing but images are not. After successfully sending and receiving data from the backend using AJAX, I thought it would work but it didn't. -
Create deb file for django
I have a Django app that I have to install it on customer server. I want to made a .deb package for this app, and add my custom repo, then on my customer server, get it like apt-get install {PACKAGE_NAME} . my questions: A- is there any better solution? B- how can I create a .deb package file for Django app? I Read about making packages but I am more confused -
Django Generic detail view 'class' must be called with either an object pk or a slug in the URLconf while trying to delete an object
In my Django app, I'm trying to delete a Comment which is associated with a post, but I keep getting this error message. The expected output is for the Comment to be deleted from the site and the database. Exception Type: AttributeError Exception Value: Generic detail view CommentDeleteView must be called with either an object pk or a slug in the URLconf. I am new to Django and I don't know how to resolve this error. urls.py: from django.urls import path from .views import CommentCreateView, CommentDeleteView from . import views urlpatterns = [ path('post/<int:pk>/comment', CommentCreateView.as_view(), name='add-comment'), path('post/<int:post_pk>/comment_delete/<int:comment_pk>/', CommentDeleteView.as_view(), name='comment-delete'), ] CommentDeleteView: class CommentDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Comment template_name = 'blog/comment_delete.html' context_object_name = 'comment' def test_func(self): comment = self.get_object() return comment.author == self.request.user def get_success_url(self): return reverse('post-detail', kwargs={'pk': self.object.post.pk}) def get_object(self, queryset=None): obj = super().get_object(queryset=queryset) return get_object_or_404(Comment, pk=obj.pk) Comment model: class Comment(models.Model): post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() date_posted = models.DateTimeField(default = timezone.now) def __str__(self): return self.content Html template where the Delete Comment button is located: {% for comment in post.comments.all %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <small class="text-muted">Posted: {{ comment.date_posted|date:"H:i, j F, Y" }}</small> {% if comment.author == user or post.author … -
Fastest way to find out whether row or one of set of rows exists in database accesed via SqlAlchemy
Django has queryset.exists() method that fetch bool indicating whether or not at least 1 row with specific conditions exists. for example User.objects.filter(id__in=[1, 2, 3, 4, 5], usernmae='test').exists() It would just return bool True in case at least one row with these conditions exists and False other way around. Question - is it something like that could be done in SQLAlchemy > 2.0 with asyncpg driver? Best I have found is await session.get but it potentially could fetch multiple objectds from DB, dezerialize them, etc, whereas I only need to find out if at least one of these rows does exists? -
Is there a way to create multiple forms in Django using Bootstrap for updating values in a JSONField dictionary?
I want to create an update form in Django, which I suppose, it is not really complicated, but I need to know which way is a standard way to implement it. I try to simplify it. So let's imagine: models.py: class Building(models.Model): """ORM representation of the Projects""" name = models.CharField(max_length=64, blank=False, null=False) project = models.JSONField(default=building_default_value, blank=False, null=False) A simplified example of project: { "floor": { "Stahlbeton": 200, "Estrich": 50, "Sauberkeitsschicht": 50, "Abdichtung": 10, "Dampfsperre": 2, "Schaumglas": 120, "Extrudiertes Polystyrol (XPS)": 120, }, "roofbase": { "Stahlbeton": 200, "Abdichtung": 10, "Dampfsperre": 4, "Kies": 50, "Extrudiertes Polystyrol (XPS)": 180, }, "wall": { "WDVS Verklebung und Beschichtung": 15, "Steinwolle-Daemmstoff": 140, "KS-Mauerwerk": 175, "Gipsputz": 15, }, } Now I want to have an update form in my HTML page, that user is able to edit each number of this materials. For example it should be rendered something like this: Floor: Stahlbeton = (place to modify number) Estrich = (place to modify number) and so on for all other keys. I tried to use {% bootstrap_form form %}, but the problem is that with this command, there is going to be just 2 forms for name and project, and I could not break it down to … -
How can I zip multiple uploaded files in Django and save the zip file into the database?
import zipfile from django.shortcuts import render, HttpResponse from . models import File def index(request): if request.method == 'GET': return render(request, 'index.html') elif request.method == 'POST': uploadedFiles = request.FILES.getlist('files') with zipfile.ZipFile('new.zip', 'w') as zip_file: for uploadedFile in uploadedFiles: file_name = uploadedFile.name file_data = uploadedFile.read() zip_file.write(file_name, file_data) # File.objects.create(file = zip_file) # How can I save the zip file in database? return HttpResponse('Successfull.') When I upload files occurs an error: **FileNotFoundError: [WinError 2] The system cannot find the file specified: 'Cap.txt' ** How can I solve this? -
Django m2m relationship only saving sometimes through django admin
Have been banging my head against a wall on this one for a while. I have a model called Car, in this is has a models.ManyToManyField of colours. class Car(models.Model): brand = models.CharField(max_length=70, default='', unique=True) colours = models.ManyToManyField('Colours') ... def fetch_data(self): #some code which gets data from an api and adds it to some fields def save(self, *args, **kwargs): self.fetch_data() super(Car, self).save(*args, **kwargs) For a while this has been working seamlessly. A Car can be saved with numerous colours. Recently, if I select a colour in django admin when adding a Car, I click save, the Car will be created. However, clicking back into the car in django admin and you can see there are no Colours attached to it. And looking at the database, the m2m values have not been added. However, if I stay on that Car's edit screen for a while (5 mins) in django admin, re click on the colours, and press save, it will save the colours half of the time. Does anyone have any idea what could be the issue with this? I have tried adding save_related() and save_model() in CarAdmin(admin.ModelAdmin) but to no avail. Thanks! -
in Django using hx-get in a template, it is sending the original placeholder
When i load the template, it is loaded with hx-get=""{% url 'xx_view' CI='placeholder' %}" And from jquery i change the placeholder with this. "{% url 'xx_view' CI='" + selectedValuesString + "' %} i browser debugger i can see it is substituted correctly to this.Timestamp is for making sure it is not cached. /base/tools/?CI=hostxxxx&timestamp=1685534181063 But in the view the i receive CI=placeholder, and i cant get the timestamp using: timestamp = request.GET.get('timestamp'). so is hx-get cached somewhere else or what am i doing wrong? -
Why am I getting 'AttributeError: 'Response' object has no attribute 'get'' when trying to redirect in Django?
I'm creating web shop with django and i have this isue every time i try to redirect from my app which register and login users I wrote this code: def user_register(request): if request.method == 'POST': form = UserRegistrationForm(request.POST) if form.is_valid(): data = form.cleaned_data user = User.objects.create_user( data['email'], data['full_name'], data['password'] ) return redirect('https://www.google.com.ua/') else: form = UserRegistrationForm() context = {'title':'Signup', 'form':form} return render(request, 'register.html', context) No matter where i redirect it throws this error: File "C:\Users\rr006\AppData\Local\Programs\Python\Python310\lib\site-packages\django\middleware\clickjacking.py", line 26, in process_response if response.get('X-Frame-Options') is not None: AttributeError: 'Response' object has no attribute 'get' -
Django app [WARNING] Worker with pid 12276 was terminated due to signal 9
I have a Django application which runs on a linode server. I use a gunicorn for deployment. When I try to upload a large file of 40MB on the website (which is one of the functionalities). The website crashes: 502 Bad Gateway nginx/1.14.2. When I view the error logs, this is what I get: [WARNING] Worker with pid 12276 was terminated due to signal 9. I already tried adding these lines to the server block of the nginx configuration file: client_max_body_size 100M; client_body_timeout 1000s; client_header_timeout 1000s; and this to the gunicorn: ExecStart=/home/jelleheijne/.local/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/jelleheijne/NPS_data_processing.sock NPS_data_processing.wsgi:application --timeout 1000 to increase memory and time before timeout, but this does not work. Can anyone please help me solve this issue? -
Do I need to use a Transactional Email Service Provider to send emails with Django?
Context I would like to send transactional Email through Django. I understand that there are Transactional Email Service Provider (ESP) that faciliatates this endeavour. The obvious issue I see with this is the cost associated with it. (I know there ESP with tier plans for small amounts of emails) Questions So, I have a few questions regarding this topic: Do I need a Transactional Email Service Provider to send emails through Django? What are the pros and cons of using an ESP for transactional emails in Django? If I decide to do it on my own (without using a ESP), does it scale well? What other issues can you see, that I'm not aware of, and you think they might be relevant? Final question If my conclusion would be not to use an ESP, what steps should I take to send emails through Django? I've looked at a Reddit thread where they discuss this topic. But almost everyone keeps recommending using an ESP. -
How do I solve 'The view didn't return an HttpResponse object. It returned None instead.' error in Django?
The view didn't return an Httpresponse object. It returned None instead. enter image description here I am getting "The view didn't return an HttpResponse object. It returned None instead." When I clicked on edit button its giving me error url.py: urlpatterns=[ path("client",views.client,name="client"), path("show_client/<str:pk>",views.show_client,name="show_client"), path("client_edit",views.client_edit,name="edit_client"), ] views.py: def show_client(request,pk): a_url = "" payload = json.dumps({ "grant_type": "client_credentials" }) elastic_api_key="" headers = { 'Authorization': 'Apikey ' + elastic_api_key, 'Content-Type': 'application/json' } auth_response = requests.request("POST", a_url, headers=headers, data=payload) auth_response_json = auth_response.json() # print(auth_response_json) access_token = auth_response_json['access_token'] print(access_token) url = "" payload = "" headers = { 'Authorization': "Bearer " + access_token, 'Content-Type': 'application/json' } response = requests.request("GET", url, headers=headers) res_data = response.json() dt = res_data['hits']['hits'] html: client.html: <table id="order-listing" class="table"> <thead> <tr> <th>Customer Name</th> <th>Jira Id</th> <th>Time zone</th> <th>Signed Date</th> <th>Action</th> </tr> </thead> <tbody> {% for i in data_lst %} <!-- {{i.organization_name}} --> <tr> <td>{{i.organization_name}}</td> <td>{{i.organization_id}}</td> <td>{{i.timezone}}</td> <td>{{i.signed_date}}</td> <td> <a href="{% url 'show_client' i.organization_name %}" style="border: 1px solid gray;padding:10px;color:#4bda2f;outline-style:none"><i class="fa fa-eye"> View</i></a>&nbsp; <a href="" style="border: 1px solid gray;padding:10px;color:#eb2805;">Delete</a> </td> </tr> {%endfor%} </tbody> </table> for i in dt: customer_dt =i customer = customer_dt['_source']['customer'] if pk == customer['organization']['organization_name']: # print("---^^organization^^----",customer['organization']) org = customer['organization'] poc=customer['contacts'][0]['port53'] client = customer['contacts'][1]['customer'] services = customer['services'][0]['socaas'] crtical_assets = customer['criticalAssets'][0]['VMs'] print(crtical_assets) context={'org':org,'poc':poc,'client':client,'services':services,'vm':crtical_assets} … -
Create SQL function using Django
I am working on a project that allowed single user in a database. Now say, particular user with name Jazz logs in and either edit or create blog and save. Each blog has incremental unique id , for example, jazz_1, jazz_2 and so on. When Jazz creates the new blog, new id will be jazz_3. Now I want to allow multiple user in a single database. So I have to handle the counter for each user. Say, new user with name Joy logged in and created the new blog then id will set as joy_1 for the new blog. To implement this, I was planning to create a function in database which will check the last counter for the user, increment the counter and return the id CREATE FUNCTION `get_id`(user_id int, invoice_prefix varchar(15)) RETURNS int BEGIN DECLARE suffix INT; INSERT INTO id_counter (user_id, invoice_prefix, counter) VALUES(user_id, invoice_prefix, 1) ON DUPLICATE KEY UPDATE counter = counter + 1; SELECT counter INTO suffix FROM id_counter WHERE user_id = user_id; RETURN(suffix); END So I have 2 queries: How should I create function in the database using Django? So that anytime if I scrap the old database and run the migrations from Django, tables … -
ValueError No handler Django Channels Chat app
I'm creating a chat application that some people can chat to each other in some rooms and now I got this errors while sending messages: raise ValueError("No handler for message type %s" message["type"]") ValueError: No handler for message type chat_message Consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer from asgiref.sync import sync_to_async class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self,text_data): data=json.loads(text_data) message = data['message'] username = data['username'] room = data['room'] await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message':message, 'username' : username, 'room': room , } ) async def chat_message(self,event): message=event['message'] username=event['username'] room=event['room'] await self.send(text_data=json.dumps({ 'message':message, 'username' : username, 'room': room , })) HTML TEMPLATE {% extends 'core/base.html' %} {% load static %} {% block cont %} <div class='rooms'> <p class='bolder'>Username</p> <p>The messages ......</p> </div> <form method="post" action="." > <div> <input type="text" name="content" class="input" placeholder="write here..." id="chat-message-input"> <button class="bluebot" id="chat-message-submit">Submit</button> </div> </form></div></div> {% endblock %} {% block scripts %} {{ room.slug|json_script:"json-roomname" }} {{ request.user.username|json_script:"json-username" }} <script> const userName = JSON.parse(document.getElementById('json-username').textContent); const roomName = JSON.parse(document.getElementById('json-roomname').textContent); const chatSocket = new WebSocket( 'ws://'+window.location.host+'/ws/'+ roomName+ '/' ); chatSocket.onmessage=function(e){ console.log('onmessage') const data = JSON.parse(e.data); if(data.message) … -
Access Foreign Key's Queryset
I have these models: class Source(models.Model): name = models.CharField(max_length=255, blank=True, null=True) feed_url = models.CharField(max_length=512) .... class Post(models.Model): source = models.ForeignKey(Source, on_delete=models.CASCADE, related_name='posts') title = models.TextField(blank=True) body = models.TextField() .... class FeedCategory(models.Model): feed_category = models.CharField(max_length=128, choices=FEED_CATEGORIES, blank=True) source = models.ForeignKey(Source, on_delete=models.CASCADE) And I want to make a Queryset where I get all FeedCategories but I'd like to also include in there their related posts. So If I use: feeds = FeedCategory.objects.select_related('source').all() my queryset does not return the posts. I tried using: feeds = FeedCategory.objects.select_related('source').all() posts = Post.objects.filter(source_id__in=feeds.values_list('source_id', flat=True)) which works but its on two different queries. What I basically want to do is have a single query which shows the category and the related source's posts in order to bring them up on frontend so I could use something like: {% for feed in feeds %} {{feed.category}} {% for post in feed.source_set %} {{post.body}} {% endfor %} {% endfor %} My thinking was something with annotate but how exactly do I do that? -
Django os module is frozen
Upon changing my env variable from hardcoded ones to the ones in .env file, I encountered an issue with my os import Simplified: import os DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('AWS_RDS_NAME'), 'USER': os.environ.get('AWS_RDS_USER'), 'HOST': os.environ.get('AWS_RDS_HOST'), 'PASSWORD': os.environ.get('AWS_RDS_PASSWORD'), 'PORT': os.environ.get('AWS_RDS_PORT'), } } When starting the server I get an error, as if my env file did not exist. When I print os (print(os)) I get an error I never got : <module 'os' (frozen)> I don't record doing something different than usual. Does anyone know what is this? Thanks a lot -
Add a select field on Django form without saving on database
I have a form that refers to a model into the database so, each time is filled and a user click SUBMIT, the form is saved on the database. The form has a series of fields took directly from the Django Model. See below. My problem is that, I want to add a new field, a select field, that have as option inside data I've processed from the backend via the home view and, when the form is submitted, it passes the data selected to the same view so I can elaborate from there. I don't want this field to be saved on the database with the form.save() Is there a way to have this kind of "hybrid" form where part of the data/field are taken from the database and others are just added by me? models.py class Test(models.Model): testTitle = models.CharField(max_length=50, blank=False, null=False) testDescription = models.TextField() sequenzaTest = models.ForeignKey("SequenzaMovimento", null=True, on_delete=models.SET_NULL) numeroCicli = models.IntegerField(blank=False, null=False) dataInizio = models.DateTimeField(auto_now_add=True) dataFine = models.DateTimeField(blank=False, null=True) testFinito = models.BooleanField(default=False) testInPausa = models.BooleanField(default=False) dataUltimaPausa = models.DateTimeField(null=True, blank=True) workerID = models.CharField(max_length=200, blank=True, null=True) def __str__(self): return self.testTitle class StartWorker(ModelForm): class Meta: model = Test fields = ('testTitle', 'testDescription', 'sequenzaTest', 'numeroCicli') widgets = { 'testTitle': forms.TextInput(attrs={'class':'form-control'}), … -
I need a simple python Django login example using database credentials
Could you please help me find an example of a simple login page where the users can be authenticated using user/password from a database postgres or mysql(I can change that afterwards from mysql to PG )? I googled for almost 1 week but wasn't able to find a django python example. I actually found a Flask example - and: that is exactly what I need - but not using Flask - I need Django. Here the flask example I found: Flask_Example In this Flask example is - most important : login window on the first place after starting of the web application, no TABs, no Navbar, no sidebar, no first click on a button "Login" and then login, nothing really nothing except a white blank page with a little login window in the middle of the screen where you can put your user and password and if the credentials are correct in the database, then you will be redirected to a simple page containing whatever inside. All that what I wrote here is exactly in that Flask example, but... I need a Django and no Flask. There are so many professional people who are writing Django code examples... but there … -
Automatic creation of third-level domain names
I'm developing a kind of small social website for a scientific working group (studying birds of prey) on Python/Djando, the server works on Ubuntu + Nginx + Gunicorn. There are personal sections for the members of the group. To make the URLs more beautiful, I'd like to make them visible as third-level domains. For example, a member creates his/her page mysite.net/persons/member-name/, and it is accessible as member-name.mysite.net. Is it possible to make the 3-level domains automatically, on user section create? If so, how to do it? If not (or too complicated), how it is possible to do it manually? As I think, the simple redirect is not what I want, since I want all internal or incoming links to be to this 3-level domain, not sub-directory. I found only one answer to this question, but it is pretty old (10 years ago) and is missing exact details, so I don´t know how to implement it. It suggests to create NS records for the subdomain in the mysite.com zone file, but I don´t know where exactly this zone is (at my hosting provider?), and not sure that I have access to it. Thanks for any advice, and especially for detailed ones! -
Django ajax listview editing objects one by one
Hi I have a django project where im rendering a listview with ajax and i wana update one object in this list view with a modal and ajax. I am struggling to understand because i think im not familiar enough with ajax and webdevelopment. What i want to be beable to do is basically edit any of those single objects being rendered with a modal form. i get some random objects data when i click edit button. I am not sure what other information i can provide but please let me know if more clarity needed. -
Django template language 2023 alternative stacks
I've been playing around with Django where I come from PHP(Bootstrap 4) background with a few projects under my belt. As I'm trying things around using Djnago default template language, I was looking for alternatives of the default template language. I found some people saying that the default template is outdated and others claiming to use Jinja2. As per ChatGTP, it listed the following template engines: Jinja2: Mako: Handlebars: Mustache: Liquid: I will be using bootstarp, but I wanted to have a comprehensive overview regarding the way forward and best options used in 2023 out there from experienced dev community. Thank you for your understanding. -
Heroku Error R14 (Memory quota exceeded) when I use ML models (python, django)
I have deployed django app with ML models on heroku. But when I use the next code in django view function for make prediction with open(model_path, "rb") as f: model = pickle.load(f) pred_proba = model.predict_proba(mwp)[0] del model I receive the next message: Process running mem=726M(141.8%) 2023-05-31T09:23:53.646613+00:00 heroku[web.1]: Error R14 (Memory quota exceeded) And if I load my ML model again the process memory increase and in the final my app crashes. I can't understand why the memory increasing occurs, because I delete my model after prediction using del model? What can I do to solve this problem? Thank you. -
NewsAPI not able to fetch news of a given city
So, I'm basically trying to make a website that brings information about cities when you input a city name. Right now all I'm able to, successfully, display is the weather report of a city. I'm trying to bring some news headlines as well. I tried this code. And this, as far as I know about the language, should have worked. views.py from django.shortcuts import render import requests import json from datetime import datetime def index(request): try: if request.method == 'POST': API_KEY = '#################################' city_name = request.POST.get('city') url = f'https://api.openweathermap.org/data/2.5/weather?q={city_name}&appid={API_KEY}&units=metric' response = requests.get(url).json() current_time = datetime.now() directives, it will take this format Day, Month Date Year, Current Time formatted_time = current_time.strftime("%A, %B %d %Y, %H:%M:%S %p") information in one dictionary city_weather_update = { 'city': city_name, 'description': response['weather'][0]['description'], 'icon': response['weather'][0]['icon'], 'temperature': 'Temperature: ' + str(response['main']['temp']) + ' °C', 'country_code': response['sys']['country'], 'wind': 'Wind: ' + str(response['wind']['speed']) + 'km/h', 'humidity': 'Humidity: ' + str(response['main']['humidity']) + '%', 'time': formatted_time } else: city_weather_update = {} context = {'city_weather_update': city_weather_update} return render(request, 'index.html', context) except: return render(request, 'error.html') def news(request): try: if request.method == 'POST': API_KEY = '#################################' city = request.POST.get('city') url = f'https://newsapi.org/v2/top-headlines?q={city}&apiKey={API_KEY}' response = requests.get(url) data = response.json() articles = data['articles'] else: articles = {} … -
Vagrant was unable to connect to the virtual machine VirtualBox
I can't connect to the virtual machine. Could you help me with my problem? Here is the log from GitBash: py@cpython MINGW64 ~/courses/profiles-rest-api (master) $ vagrant up Bringing machine 'default' up with 'virtualbox' provider... ==> default: Box 'ubuntu/bionic64' could not be found. Attempting to find and install... default: Box Provider: virtualbox default: Box Version: ~> 20200304.0.0 ==> default: Loading metadata for box 'ubuntu/bionic64' default: URL: https://vagrantcloud.com/ubuntu/bionic64 ==> default: Adding box 'ubuntu/bionic64' (v20200304.0.0) for provider: virtualbox default: Downloading: https://vagrantcloud.com/ubuntu/boxes/bionic64/versions/20200304.0.0/providers/virtualbox.box Download redirected to host: cloud-images.ubuntu.com default: ==> default: Successfully added box 'ubuntu/bionic64' (v20200304.0.0) for 'virtualbox'! ==> default: Importing base box 'ubuntu/bionic64'... ==> default: Matching MAC address for NAT networking... ==> default: Checking if box 'ubuntu/bionic64' version '20200304.0.0' is up to date... ==> default: Setting the name of the VM: profiles-rest-api_default_1685446821258_41886 Vagrant is currently configured to create VirtualBox synced folders with the SharedFoldersEnableSymlinksCreate option enabled. If the Vagrant guest is not trusted, you may want to disable this option. For more information on this option, please refer to the VirtualBox manual: https://www.virtualbox.org/manual/ch04.html#sharedfolders This option can be disabled globally with an environment variable: VAGRANT_DISABLE_VBOXSYMLINKCREATE=1 or on a per folder basis within the Vagrantfile: config.vm.synced_folder '/host/path', '/guest/path', SharedFoldersEnableSymlinksCreate: false ==> default: Clearing any previously set … -
Is there a way to fetch and serialize only a portion of data on demand/onclick in Django to improve performance?
I want to fetch a portion of the data and display it on demand/onclick when a user requests for it from django and serialize it. At the moment, I fetch all data to the client which could cause performance issues as the application scales. How can I achieve that using my get code snippet below. It would be great if anybody could help me out with what I am trying to solve. Thank you so much in advance. def get(self, request, hashid=None, lang=None): try: if hashid: pk_id = settings.LKC_HASH.decode(hashid)[0] disease = Disease.objects.get(pk=pk_id) serializer = CategoriesSerializer(disease) else: diseases = Disease.objects.values('id', 'translations__subcategory', 'translations__name').all() serializer = CategoriesSerializer(diseases, many=True) return Response(serializer.data, status=status.HTTP_200_OK) except Disease.DoesNotExist: return Response({'error': 'Disease Does Not Exist!'}, status=status.HTTP_404_NOT_FOUND) except Exception as e: capture_exception(e) return Response({'error': 'There was an error while fetching the diseases!'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)