Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModuleNotFoundError: No module named 'sandbox': Docker Build failed with error code [1]
I'm building a django oscar commerce v 3.2 project(https://github.com/django-oscar/django-oscar) on ubuntu 20.04 on GCP with a virtual environment using python 3.8.14 and getting the following error when i run the docker build command using docker-compose -f docker-compose-full.yml up ModuleNotFoundError: No module named 'sandbox' The trace is with regards to the following line in my settings.py: from sandbox.environment import EnvironmentChecker My project folder structure is as follows : django-commerce |- src |- sandbox | |- __init__.py | |- environment.py | |- settings.py | |- manage.py | |- urls.py | |- wsgi.py | |- uwsgi.ini |- DockerFile |- MakeFile |- Manifest.in |- setup.py |- setup.cfg The top lines in my Settings.py import os import sys import logging.config from django.utils.translation import gettext_lazy as _ from sandbox.environment import EnvironmentChecker Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) Path helper location = lambda x: os.path.join( os.path.dirname(os.path.realpath(__file__)), x) My wsgi.py # isort:skip import os import sys root_path = os.path.abspath(os.path.split(__file__)[0]) sys.path.insert(0, os.path.join(root_path, 'django-commerce')) sys.path.insert(0, root_path) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") from django.core.wsgi import get_wsgi_application # isort:skip application = get_wsgi_application() I've also tried adding django-commerce.sandbox to my INSTALLED_APPS in settings.py as a last try but its not working. I've spent hours trying this to work. Help appreciated. … -
Django DEBUG False not working in the Production Environment
I am new to Django and Python world, I am currently working on an Dajngo site, which is hosted on a Ubuntu20.04 VM. Upon hosting the site to the production, I noticed that, although the DEBUG is set to False in the prodiuction settings. I still see the Django DEBUG erros as if the DEBUG is set to True . When I run python manage.py runserver command on the VM I get the below error. CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False. Folder structure . ├── __init__.py ├── __pycache__ │ ├── __init__.cpython-310.pyc │ ├── urls.cpython-310.pyc │ ├── views.cpython-310.pyc │ └── wsgi.cpython-310.pyc ├── settings │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-310.pyc │ │ ├── base.cpython-310.pyc │ │ ├── local.cpython-310.pyc │ │ └── production.cpython-310.pyc │ ├── base.py │ ├── local.py │ └── production.py base.py (Common settings) import os from os.path import dirname, join import posixpath from posixpath import join from pathlib import Path BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '393266f4-9cc7-4cfe-96a8-2f2809e53e32' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True #ALLOWED_HOSTS = [] # Application references INSTALLED_APPS = [ # … -
OperationalError at /admin/card/group/ no such table: card_group
i created a table named group and also run makemigrations and migrate and also registered it in admin.py but it is showing error when i opening it in admin panel. this is my models.py class group(models.Model): dish_category = models.CharField(max_length=255) def __str__(self): return self.dish_category this is my admin.py from .models import group admin.site.register(group) i also reset db and run migration again but it not works the groups table is showing in db but when i click it it shows error that OperationalError at /admin/card/group/ no such table: card_group -
How to create dynamically jstree in django
how to create dynamic jstree in django website Actually, I don't know what type of json data send in ajax request for creating jstree. -
Django Rest Framework very slow on Azure
I had migrated from Heroku to Microsft Azure, and the speed is really very slow, my App service is having the following specs : P1V2 210 total ACU 3.5 GB memory Dv2-Series compute equivalent then when it comes to my Azure Database for PostgreSQL flexible server, the following are the specs : General Purpose (2-64 vCores) - Balanced configuration for most common workloads Am sure all these Specs are higher than the default Heroku specs it used to give, but why is my Django project very slow when it comes to response time of the API requests ? -
Loading category tags with load more button
i am new to jquery , i have implemented a load more button on my blog app using jquery however the categories tags doesnt get displayed on the html when i click on the load more button Every thing works fine so far, i can't just display the tags on the post card, it keeps returning undefined note: 'i am getting my categories with a many to many field relationship' enter image description here Here is my views : ` def home(request): post = BlogPost.objects.all()[0:5] total_post = BlogPost.objects.count() context = {'post': post, 'total_post':total_post} return render(request,'blog/home.html', context) def load_more(request): # get total items currently being displayed total_item = int(request.GET.get('total_item')) # amount of additional posts to be displayed when i click on load more limit = 3 posts = list(BlogPost.objects.values()[total_item:total_item+limit]) print(BlogPost.objects.all()) data = { 'posts':posts, } return JsonResponse(data=data) here is my template: <div class="blogpost-container"> <div class="blogposts" id="blog-content"> {% for post in post %} <div class="post"> <img id="img-src" src="{{post.image.url}} " image-url="{{post.image.url}}" alt=""> <p><strong>{{post.title}}</strong></p> {% for category in post.category.all%} <h3>{{category}}</h3> {%endfor%} <a id="post-detail-link" href="{% url 'detail' post.id %}" detail-url="{% url 'detail' post.id %}"><h2>{{post.summary}}</h2></a> </div> {%endfor%} </div> </div> <div class="add-more" data-url='{% url "load_more" %}'id="add-btn"> <button type="button" class="more-content">load more</button> </div> <div class="alert no-more-data" role="alert" id="alert"> No … -
How to make a '\n' or '<br/>' work rather than display it using django and html template?
I'm facing a serious problem with html and django. What I want to do: Create a table Fill the table with python string The most important one that I want to make line break for the string What I've tried: Use '\n' in the string Use '' in the String But they don't work, they are both displayed on the browser, I don't how to fix it. Can anyone help, Thanks a lot. ` <table border='1'> {% for x in datas %} <tr> <td>{{ x.0 }}</td> <td>{{ x.1 }}</td> <td>{{ x.3 }}</td> </tr> {% endfor %} </table> x.3 is a string and I tried both '\n' and <br/> in it ` -
Django: Use the different field for password in the Custom User Model
When you use the Custom User Model, you can change the "username" field using the USERNAME_FIELD = 'identifier' Is there a way to do similar thing for the "password" field? Something like PASSWORD_FIELD = 'my_password_field' If not, is there any was to store the password not in the default "password" field of the user model? No code tried because I don't know what to write in this case. Django docs contains the instruction about changing the changing the used identifier, but nothing about password. -
Wrong environment in Django
I'm a beginner at Django Web Framework.At the beginning when I start Django project I didnt see venv folder like on the picture on the left.I didnt have bin ,lab , gitignore and pyvenv.cfg files on the right picture.When I made new env I see venv folder but also there are duplicate bin and lib folders.All I want for now is when I start new Django project is to have one VENV folder and that it's gonna be my only enviornment and also bin and lab folders be in venv folder. What I try is this: That was the commands I enter on my MAC. pip install virtualenv virtualenv venv source venv/bin/activate That made a new env and folder venv.But I dont want to have another basic enviornemnt with name of the project like on the picture on the right.I dont want to have in project folder bin and lib folder also. Sorry for my english... -
I need help properly implementing a booking scheduler and availability in Django
This question has been asked many times before on StackOverflow and in the Django forums, but none of the answers I've found are appropriate or complete enough for my situation. First, the brief: I'm creating a web application for a car rental business. In addition to helping them organize and centralize their fleet, it will also help them collect orders directly from customers. As with most rentals, the logistics of it all can be somewhat confusing. Someone may place an order for a car today (December 12th) but actually take the car over the Christmas to New Year's period. A renter may borrow a car for just two days, and then extend the booking at the last minute. When this happens (often very frequently), the business usually has to scramble to find another one for a different customer who was scheduled to get that car the next day. Adding to that, an individual car can only be rented to one client at a time, so it can't have multiple bookings for the same period. Most answers advocate for a simple approach that looks like this: models.py class Booking(models.Model): car = models.ForeignKey(Car, ...) start_date = models.dateField(...) end_date = models.dateField(...) is_available = … -
how to get value from promise and how to get promise resolved
this is my javascript code . I'am trying to get data from backened through axios. how can i get the value in subs variable ? var subs = axios.get("/getdata/", ).then( function(resp){ console.log("respons",resp.data.value); return resp.data.value; }) .catch( function(err){ console.log(err); }) console.log(subs) // console result on browser. How to fulfill this pending promise ? Promise {<pending>} [[Prototype]]: Promise [[PromiseState]]: "fulfilled" [[PromiseResult]]: "false" views.py file code def data_to_api(request): if request.method == "GET": user_name = request.user.get_username() print(user_name) user_obj = All_users.objects.get(username=user_name) subs= str(user_obj.subs_detail).lower() print(subs) request.data = subs data = { "value":subs, } return JsonResponse(data) -
Error No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model
i'm working on a django project to create football trainings. I'm testing the model and its saving. The problem appears when I try to save it, must be something about redirection, because in the database the training does get saved, but it doesn't redirect me anywhere and the error comes out. models.py from django.db import models from django.utils import timezone from users.models import User class Entrenamiento(models.Model): autor = models.ForeignKey(User, on_delete=models.CASCADE) idEntrenamiento = models.AutoField(primary_key=True) idEquipo = models.IntegerField() fecha = models.DateTimeField(default=timezone.now) idDireccionCampo = models.IntegerField() temporadas = [ ('2022/2023','2022/2023'), ('2023/2024','2023/2024'), ('2024/2025','2024/2025'), ('2025/2026','2025/2026') ] temporada = models.CharField(max_length=50, choices=temporadas, default='2022/2023') def __str__(self): return 'Entrenamiento {}'.format(self.idEntrenamiento) @property def entreno(self): return 'Entrenamiento {} de {} para {} con fecha del {}, será en el campo {}'.format(self.idEntrenamiento, self.temporada, self.idEquipo, self.fecha, self.idDireccionCampo) views.py from django.conf import settings from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.contrib.messages.views import SuccessMessageMixin from django.contrib.auth.models import User from django.contrib import messages from django.http import HttpRequest, HttpResponseRedirect from django.shortcuts import get_object_or_404, render from django.views.generic import (CreateView, DeleteView, DetailView, ListView,UpdateView) from django import forms from django.urls import reverse_lazy from .models import Entrenamiento def home(request): context = { 'entrenamientos': Entrenamiento.objects.all() } return render(request, 'entrenamientos/entrenamientos.html', context) class PostListView(ListView): model = Entrenamiento template_name = 'entrenamientos/entrenamientos.html'#<app>/<model>_<viewtype>.html context_object_name = 'entrenamientos' ordering = ['-fecha'] … -
Celery not retrying when an exception is raised when testing in Django
I have a class based celery task, which I would like to test by raising an error and then confirming that retry has been called. During the test, I want to raise a ConnectionError when msg.send() is called and then confirm that it is being 'retried'. The task essentially constructs an email using django.core.mail.EmailMultiAlternatives (which inherits EmailMessage) and then attempts to send that email. The task works well in practice, with a retry being called if a connection does not exist, my only problem is how to test it. So far, I have managed to raise the ConnectionError by patching EmailMultiAlternatives, however, the test does not trigger a retry in the celery terminal. tasks.py (Simplified) class SendMail(Task): max_retries = 4 base = 'BaseTask' def run(self, **kwargs): msg = EmailMultiAlternatives(kwargs.get('some_value'), etc.) msg.attach_alternative(rendered_html) try: msg.send(fail_silently=False) except ConnectionError as exc: self.retry(countdown=backoff(self.request.retries), exc=exc) test_task.py (simplified) class SendMailTest(TestCase): def setUp(self): self.message = {some data} def test_error(self): with patch.object(EmailMultiAlternatives, 'send', return_value=None) as mock_method: mock_method.side_effect = Exception(ConnectionError) SendMail(kwargs=self.message) My question is, why, when the test script is run and an exception is clearly being raise, does Celery not attempt to retry? -
How take path in request.FILE['file'] to put it for download link
I create foo to upload files to Django models, its InMemoryUpload object. and how can I collect the full path to download link? my models.py class Document(models.Model): """Class for uplaoded files. colect file and description working with analog form """ id = models.AutoField(primary_key=True) file_path = models.TextField(max_length=255) hash_size = models.CharField(max_length=255) def __str__(self): return f"{self.id},{self.file_path},{self.hash_size}" def get_hash(file: object) -> str: md = hashlib.md5() # with open(file, "rb") as f: for chunk in iter(lambda: file.read(4096), b""): md.update(chunk) return md.hexdigest() my views.py def model_form_upload_1(request: HttpRequest) -> HttpResponse: ''' view handling this form will receive the file data in :attr:`request.FILES <django.http.HttpRequest.FILES>`''' if request.method == 'POST': upload = request.FILES['file'] path = upload.chunks() print(path) hash_tuple = () form = DocumentForm(request.POST, request.FILES) if form.is_valid(): print(upload.size) if get_file_size(upload): hash = Document.get_hash(upload) hash_list = [x for x in Document.objects.all().values_list('hash_size')] hash_tuple += (hash,) if hash_tuple not in hash_list: Document.objects.create( file_path=request.GET.get(upload), hash_size=hash) else: return HttpResponseBadRequest("file bigger tha 300mb") return redirect("view") else: return HttpResponseBadRequest("Form invalid") else: form = DocumentForm() return render( request=request, template_name='model_form_upload.html', context={'form': form}) return render(request, 'model_form_upload.html') return render(request, 'model_form_upload.html') my template.py <tr> <td>{{document.id}}</td> <td>{{document.file_path}}</td> <td><a href="{{ document.file_path }}">download</a></td> <td>{{document.hash_size}}</td> </tr> before I tried to take request.open(file) but it's actually not what I need. -
How to Install WordPress in Django sub directory
My old site is running on Django. Now I want to run a WordPress site on same domain and server through sub directory. I have a created a sub directory "testsite" in public html folder through c panel, created database and user and then installed WordPress into it. And when I tried accessing my site through www.mysite.com/testsite/wp-admin login page appears for WordPress but when tried to login this error message appears Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ superadmin/ about [name='about'] contact [name='contact'] gallery [name='gallery'] The current path, testsite/wp-admin/, didn’t match any of these. How can I solve this issue.. Please help me in this. thanks in advance I want to access www.mysite.com/testsite/wp-admin and can run my WordPress site smoothly without deleting the Django site. Is it possible anyway? -
Any way we can share a specific item publicly from a private S3 bucket?
The question is pretty vague but here's the entire problem statement. I am using Django REST APIs, and I'm generating invocies for my clients. Using wkhtmltopdf, I'm able to generate a PDF file which gets automatically backed up to S3. Now, we need to retreive the said invoice once our client clicks on a link. We're using pre-signed URLs right now, which last for 12 hours, right? Once that link expires, the entire backend fails. I mean, even if we go for permanent pre-signed links, would there not be a security issue? I could really use some guidance on this. -
Notification template only printing out items after the 3rd position
Notification template only printing out items after the 3rd position. When I inspect element to check if its showing up in the frontend, its there, but its just a blank html <p> tag. Other than this minor bug it works fine. Not sure how to proceed, any help is much appreciated. Here are my models.py class Notification(models.Model): MESSAGE = 'message' APPLICATION = 'application' CHOICES = ( (MESSAGE, 'Message'), (APPLICATION, 'Application') ) to_user = models.ForeignKey(User, related_name='notifications', on_delete=models.CASCADE) notification_type = models.CharField(max_length=20, choices=CHOICES) is_read = models.BooleanField(default=False) extra_id = models.IntegerField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(User, related_name='creatednotifications', on_delete=models.CASCADE) class Meta: ordering = ['-created_at'] notification views.py @login_required def notifications(request): goto = request.GET.get('goto', '') notification_id = request.GET.get('notification', 0) extra_id = request.GET.get('extra_id', 0) if goto != '': notification = Notification.objects.get(pk=notification_id) notification.is_read = True notification.save() if notification.notification_type == Notification.MESSAGE: return redirect('room', pk=notification.extra_id) elif notification.notification_type == Notification.APPLICATION: return redirect('room', pk=notification.extra_id) return render(request, 'notification/notifications.html') notifications.html template {% extends 'main.html' %} {% block content %} <div class="container"> <h1 class="title">Notifications</h1> {% if not notifications %} No notifications yet! {% endif %} {% for notification in notifications %} <div class="notification"> <p> {% if notification.notification_type == 'message' %} <a href="{% url 'notifications' %}?goto=room&notification={{ notification.id }}&extra_id={{ notification.extra_id }}"> <strong>{{ notification.created_by.username }}</strong> sent you a … -
Django: Strange error with connection between view, template and url
I have two main usage and main model pages, in which products from a specific usage or model are listed. I have the following views for these pages: def get_common_queryset(): usage_queryset = Usage.objects.all() sub_usage_queryset = SubUsage.objects.all() main_model_queryset = MainModel.objects.all() pump_type_queryset = PumpType.objects.all() queryset_dictionary = { "usage_queryset": usage_queryset, "sub_usage_queryset": sub_usage_queryset, "main_model_queryset": main_model_queryset, "pump_type_queryset": pump_type_queryset, } return queryset_dictionary def products_usage_main(request): queryset_dictionary = get_common_queryset() context = queryset_dictionary return render(request, "products/products_usage_main.html", context) def products_model_main(request): queryset_dictionary = get_common_queryset() context = queryset_dictionary return render(request, "products/products_model_main.html", context) Here we have a get_common_queryset() view, which you can read about the reason of it in this question. Then we have two simillar view functions, products_usage_main and product_model_main but with different templates. In the urls.py I have following paths for these views: urlpatterns = [ path("application/", products_usage_main, name="products_usage_main"), path("model/", products_model_main, name="products_model_main"), ] In which, again, we can see that the two paths are similar with just different views. And finally I have two separate templates for these two views, which their code is not needed or related to the problem I'm facing. THE PROBLEM: In my products page sidebar, I have two main links referencing /products/application/ and /products/model/, and when I click on the /products/application/, everything works just fine; but … -
Django database design
I want to design a data model in Django with the following fields. Student's First name Student Lastname Fee per hour Dates and times of attendance. student photo. Boolean field as to student present or absent. I want to have a monthly summary of each student who attended and the total fee for that Month. Similar to a printout I can send to parents as to how much they have to pay. So my website App has to calculate for the end of each month. How do I design it? Thanks for the help -
DJANGO ORM LEFT JOIN [closed]
SQL: ` select u1.summaryUpdatedOn, u2.summary from sdgdb.user as u1 left join sdgdb.user as u2 on u1.user_id = u2.user_id and (u2.summaryUpdatedOn != '20221207030805'or u2.summaryUpdatedOn is null) where u1.sdgid = 'SDG-s6547df1445-ece35e6e-c1ea-45ae-83e8-9d9c19fab0cd'; ` my Models: ` class User(BaseModel): customer = models.ForeignKey( Customer, null=False, on_delete=models.PROTECT, db_column="customerid" ) group = models.ForeignKey( Group, null=False, on_delete=models.PROTECT, db_column="groupid" ) licensetype = models.ForeignKey( LicenseType, null=False, on_delete=models.PROTECT, db_column="licensetypeid" ) sdgid = models.CharField( max_length=64, null=False, default="temp-" + str(uuid.uuid4()), editable=False, db_column="sdgid", ) name = models.CharField(max_length=100, null=False, default=None, db_column="name") email = models.EmailField( max_length=254, unique=False, blank=True, null=True, db_column="email", ) note = models.CharField( max_length=500, null=True, blank=True, default=None, db_column="note" ) licensekey = models.CharField(max_length=100, null=True, db_column="licensekey") isdisabled = models.BooleanField(null=False, default=False, db_column="isdisabled") summary = models.TextField(null=True, db_column="summary") summaryupdatedon = models.CharField( max_length=14, null=True, db_column="summaryupdatedon" ) ` I didn't switch from SQL to API query. Please help me -
Is there a way to encrypt the password when creating a normal user through django admin?
is there any way to save password in encrypted form while creating a new user through django admin? from django.db import models from django.contrib.auth.models import AbstractUser from src.core.models import TimeStamp class User(AbstractUser, TimeStamp): joined_date = models.DateField('date joined', null=True) leave_date = models.DateField('Leave Date', null=True) role = models.ForeignKey("Role", on_delete=models.SET_NULL, null=True) class Meta: verbose_name = 'user' verbose_name_plural = 'users' def __str__(self): """ username of each user """ return self.username Here is my user model given above -
I want red borders on form submit on invalid fields using django template language
This is my html file I want red borders on form submit on invalid fields using django template language I want red borders on form submit on invalid fields using django template language I want red borders on form submit on invalid fields using django template language {% block body %} {% include 'navbar.html'%} <!DOCTYPE html> <html> <head> <title></title> <body> <form autocomplete="off" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="mb-3"> <label for="Title" class="form-label">Title</label> {{form.title}} <div class="form-text">{{form.title.errors}}</div> </div> <div class="mb-3"> <label for="Written By" class="form-label">Written by</label> {{form.written_by}} <div class="form-text"> {{ form.written_by.errors }} </div> </div> <div class="mb-3"> <label for="Description" class="form-label">Description</label> {{form.description}} <div class="form-text">{{form.description.errors}}</div> </div> <div class="mb-3"> <label for="image" class="form-label">Image</label> {{form.image}} <div class="form-text">{{form.image.errors}}</div> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> <style> .form-control { width: 50%; } .errorlist { list-style-type: none; color: red; position: relative; right: 31px; } form { margin-left: 30%; margin-right: 30%; } textarea { height: 4em; width: 50em; } </style> </body> </head> </html> {% endblock %} I want red borders on form submit on invalid fields using django template language I want red borders on form submit on invalid fields using django template language I want red borders on form submit on invalid fields using django template language -
Django an JavaScript: document.getElementById return always Uncaught TypeError: Cannot set properties of null (setting 'innerHtml')
I am writing to you because I am stuck on a basic operation (almost ashamed). I'm working on a Django project and what I'm trying to do is: show inside two 'span' tags the length of a list. It's not the first time I've done this and I've always managed to do it. But now I don't understand why it doesn't work. Here is the code: My index.html: {% load static %} <!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>Free Attitude</title> <!-- BOOTSTRAP CSS --> <link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}"> <!-- CSS --> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <!-- JS --> <script type="text/javascript" src="{% static 'js/templatesList.js' %}"></script> </head> <body> {% include '_header.html' %} <main class='home-main'> <div class="container"> <section class="row gy-3"> <!-- FOR LG SCREEN --> <div class="col-md-6 text-container d-md-block d-none"> <h2>Modelli per siti web</h2> <h6>Dai un'occhiata ad alcuni modelli già pronti, protresti trovare qualcosa di tuo interesse.</h6> <a href="{% url 'websiteEcomm:home' %}">Vedi tutti e <span id="total-templates-lg"></span> i modelli disponibili</a> </div> <div class="col-md-6 d-md-block d-none"> <div id="carouselExampleSlidesOnly" class="carousel slide" data-bs-ride="carousel" data-bs-interval="2000"> <div class="carousel-inner"> <div class="carousel-item active"> <img src="{% static 'preview-img/arsha.png' %}" class="d-block w-100" alt="..."> </div> <div class="carousel-item"> <img src="{% static 'preview-img/digimedia.png' %}" … -
How to Reset form field after submit in HTMX
I'm tried to reset form field after submit the data in HTMX. Please guide me how to do. -
Access fields dynamically in a django serilaizer
I am trying to acsess fields of a model dynamically(on the basis of call from frontend) in the serializer but unable to do so code: class DynamicFieldsModelSerializer(serializers.ModelSerializer): def __init__(self, *args, **kwargs): super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs) print("self", self) fields = self.context['request'].query_params.get('fields') if fields: fields = fields.split(',') # Drop any fields that are not specified in the `fields` argument. allowed = set(fields) existing = set(self.fields.keys()) for field_name in existing - allowed: self.fields.pop(field_name) class ProductTestSerializer(DynamicFieldsModelSerializer, serializers.ModelSerializer): class Meta: model = Product fields = ("id",) class ProductTestAPIView(generics.ListAPIView): def get(self, request): obj = Product.objects.all() data = ProductTestSerializer(obj, many=True) s_data = data.data return Response(s_data) URL: http://127.0.0.1:8000/products-test/?fields=id,short_code It returns the following error: KeyError: 'request' at fields = self.context['request'].query_params.get('fields')