Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
forward and backward in ajax
I have a page with products that are filtered through ajax. Also the url changes via pushState. But when you click the backward and forward buttons in the browser, nothing happens, only the url changes. How to handle the clicks of these buttons? -
How to extract two values from list in python?
I'm using python3 and and i have data set. That contains the following data. I'm trying to get the desire value from this data list. I have tried many ways but unable to figure out how to do that. slots_data = [ { "id":551, "user_id":1, "time":"199322002", "expire":"199322002" }, { "id":552, "user_id":1, "time":"199322002", "expire":"199322002" }, { "id":525, "user_id":3, "time":"199322002", "expire":"199322002" }, { "id":524, "user_id":3, "time":"199322002", "expire":"199322002" }, { "id":553, "user_id":1, "time":"199322002", "expire":"199322002" }, { "id":550, "user_id":2, "time":"199322002", "expire":"199322002" } ] # Desired output # [ # {"user_id":1,"slots_ids":[551,552,553]} # {"user_id":2,"slots_ids":[550]} # {"user_id":3,"slots_ids":[524,525]} # ] I have tried in the following way and obviously this is not correct. I couldn't figure out the solution of this problem : final_list = [] for item in slots_data: obj = obj.dict() obj = { "user_id":item["user_id"], "slot_ids":item["id"] } final_list.append(obj) print(set(final_list)) -
Access Foreign Key count in Django Template
I have two models: Farm and Animal with a ForeignKey relation. Each Farm contains x animals. I'm doing a table in the frontend with a for loop of each farm. How can I show the number of animals in each farm? models: class Farm(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, default=None) square_meter = models.IntegerField(blank=True, null=True) friendly_name = models.CharField(max_length=24, blank=True) kml = models.FileField(upload_to=user_directory_path_kml, null=True, blank=True) class Animal(models.Model): class Meta: verbose_name_plural = "Animals" farm = models.ForeignKey(Farm, on_delete=models.CASCADE, blank=True, null=True, default=None) name = models.CharField(max_length=24, blank=True) datetime = models.DateTimeField(blank=True, null=True, default=datetime.now) tracking = models.BooleanField(default=False) kg = models.IntegerField(blank=True, null=True) template: {% for farm in farms %} <tr> <th scope="row">{{forloop.counter}}</th> <td>{{farm.friendly_name}}</td> <td>{{farm.square_meter}}</td> <td>{{farm. }}</td> # Here I want animal count </tr> {% endfor %} -
How to call HTML page as a popup from another HTML page using Django
I am working on Django project where i need pop up the HTML when i click the button. Let me explain, when ever user click the button it should open another HTML as a popup there user can upload the files and download the sample files. Could you please help me on the issue Here is my code below, HTML Button - <button data-href='{% url "employeeBulkUpload" companydetail.id %}' id="uploadEmployees" title="Upload Employees" class="btn btn-blue mr-2 px-3 d-block w-100 text-95 radius-round border-2 brc-black-tp10"><i class="fa fa-upload"></i></button> $(document).ready(function () { $('#uploadEmployees').initDialog({'url': '{% url "employeeBulkUpload" companydetail.id %}', 'title': 'Upload Employees'}); }); -
How to display related One to Many Instances in ListView?
I want to display all belonging Instances of model Report referenced to model Module referenced to model Course. Therefore I implemented three Models related via Foreignkey. class Course(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=200, blank=True, null=True) class Module(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=200, blank=True, null=True) course_id = models.ForeignKey( Course, null=True, on_delete=models.SET_NULL, related_name="modules", default=uuid.uuid4, ) class Report(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=200, blank=True, null=True) module_id = models.ForeignKey( Module, null=True, on_delete=models.SET_NULL, related_name="reports", default=uuid.uuid4, ) I want to display model Module referenced to model Course in CourseDetailView(DetailView): Here is what I implemented: class CourseDetailView(DetailView): model = Course context_object_name = "course" template_name = "course/course_detail.html" fields = ["title", "description"] def get_context_data(self, **kwargs): context = super(CourseDetailView, self).get_context_data(**kwargs) context["courses"] = Course.objects.filter(pk=self.kwargs.get("pk")) return context and I get the instance belonging to itsself. If I change the context to: context["modules"] = Module.objects.all() and iterate over modules in course_detail.html: {{ course.description|safe }} {% for module in modules %} <div> <h2><a href="{{ module.get_absolute_url }}">{{ modules.title }}</a></h2> </div> {% endfor %} I'll get all instances of Module but I want only the ones related to the specific Course. I know I have to filter context["modules"] but I don't know how to do it. Due … -
Creating Integer Range from multiple string math expressions in python
I have a problem in a project and I've searched the internet high and low with no clear answer. How can i convert math expressions As 3x + 5y >= 100 And x,y < 500 Into a range of x and range of y to be used as ristriction in a math problem, Ex: f = x^2+4y The end result is to find the largest answer using genetic algorithms where x and y are ristricted in value. Tried sympy and eval with no luck Searched every and found only a few helpful but not enough resources I need just to translate the user input to the code for the genetic algorithm to use. -
Django admin upload multiple images in 1 form
I dont want to use inlines so I figured I want to upload a bunch of images at the same time. Now I've been struggling for an entire day to get it working but it doesn't for some reason. My first code: Model class LaptopInfoImages(models.Model): laptop_info = models.ForeignKey(LaptopInfo, on_delete=models.CASCADE) image = models.ImageField(upload_to=images_directory) admin class LaptopInfoImagesForm(forms.ModelForm): image = forms.ImageField(widget=forms.ClearableFileInput(attrs={'multiple': True})) class Meta: model = LaptopInfoImages fields = '__all__' def save(self, commit=True): instance = super().save(commit=False) for image in self.cleaned_data['image']: image_obj = LaptopInfoImages(laptop_info=instance.laptop_info, image=image) image_obj.save() if commit: instance.save() return instance This gives me the error: AttributeError: 'bytes' object has no attribute '_committed' So I changed the code to: admin class LaptopInfoImagesForm(forms.ModelForm): image = forms.ImageField(widget=forms.ClearableFileInput(attrs={'multiple': True})) class Meta: model = LaptopInfoImages fields = '__all__' def save(self, commit=True): instance = super().save(commit=False) for image in self.cleaned_data['image']: # Convert the image to a BytesIO object bytes_io = BytesIO(image) # Create an InMemoryUploadedFile from the BytesIO object in_memory_file = InMemoryUploadedFile( bytes_io, None, 'image.jpg', 'image/jpeg', len(image), None ) # Save the image to the LaptopInfoImages model image_obj = LaptopInfoImages(laptop_info=instance.laptop_info, image=in_memory_file) image_obj.save() if commit: instance.save() return instance It doesnt give me any errors but it is uploading 9332 laptop info imagess and the images don't work. -
How to clean and save multiple instances one after one in Django using clean and save methods?
I noticed that when using Django admin and whenever select/change multiple instances and click on save button (for example see the below image, it's not directly related to the code below), Django will clean/validate all instances and then save them one by one. is this how things are working in Django or the process should be clean and then save the instance before repeat same process with the next instance? because when trying to set is_active value to be true for multiple instances, it passing the clean method condition without shown the error message that tells should only one instance be selected as true and that's correct cause no one of the instances have is_active as true in the database yet But if I click the save button again will show the error message. models.py: class SupplierAddress(models.Model): """Model to create supplier's address instances""" class Meta: """Customize django default way to plural the class name""" verbose_name = 'Supplier Address' verbose_name_plural = 'Supplier Addresses' constraints = [ models.UniqueConstraint( fields=['supplier', 'address'], name='supplier_address_unique_appversion' ) ] # Define model fields. supplier = models.ForeignKey( 'Supplier', on_delete=models.CASCADE, related_name='supplier_addresses_supplier' ) address = models.ForeignKey( 'Address', on_delete=models.CASCADE, related_name='supplier_addresses_address' ) is_active = models.BooleanField(default=False) def clean(self): """Restrict the add/change to model fields""" … -
Multi Nested Serializers in django
Nested Serializers is not working properly... { "book_id": 1, "book_name": "AAAA", "language": "A", "category_type": "a", "page_count": 212, "price": "212.00", "volume": 1, "year_of_publication": "2022-12-08", "rating": 2, "cover_image": "http://127.0.0.1:8000/media/images/download_1_8Bvr7hM.jpg", "pdf": "http://127.0.0.1:8000/media/pdf/eclipse_path_mUBp1xX.txt", "Author": [ { "publisher_id": 1, "publisher_name": "pub2we", "created_at": "2022-12-21T11:37:26.192207Z", "updated_at": "2022-12-21T11:37:26.192207Z" "PUblisher" :[ { "publisher_id": 1, "publisher_name": "pub2we", "created_at": "2022-12-21T11:37:26.192207Z", "updated_at": "2022-12-21T11:37:26.192207Z" }, ] }, ] }, [ enter image description here] (https://i.stack.imgur.com/0A6tZ.png) -
How to inline radio buttons in a django form?
Here's the radio buttons: account_type = forms.ChoiceField( choices=enumerate(('Choice 1', 'Choice 2')), widget=forms.RadioSelect( {'class': 'form-check form-check-inline', 'style': 'margin-left: 20px'} ), label='', ) I'm using bootstrap-nightshade for styling which possibly contains something that prevents inlining the buttons. So far I tried: display: inline and display: inline-block; and class="radio-inline" Nothing works. Here's the template of the form {% extends 'index.html' %} {% load bootstrap5 %} {% block content %} <section class="h-100"> <div class="container h-100"> <div class="row justify-content-sm-center h-100"> <div class="col-xxl-4 col-xl-5 col-lg-5 col-md-7 col-sm-9"> <div class="card shadow-lg"> <div class="card-body p-5"> <h4>{{ form_title }}</h4> <form method="post"> {% csrf_token %} {% bootstrap_form form %} <button class="btn btn-success">{{ form_title }}</button> {% if form_title == 'Sign in' %} <a style="margin-left: 15px" href={% url 'reset-password' %}>Forgot password?</a> {% endif %} </form> </div> </div> </div> </div> </div> </section> {% endblock %} -
PycharmProjects\pythonProject\vencannot be loaded because running scripts is disabled on this system. For more informatio see about_Execution_Policies
I want to install Django on pycharm but when I try to install this massage display: File C:\Users\dell\PycharmProjects\pythonProject\venv\Scripts\activate.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170. + CategoryInfo : SecurityError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : UnauthorizedAccess -
admin profile view after login instead of displaying user profile in django
I am working on a django project.There are two types of users. One is admin and another one is researcher. So I want to display admin profile when admin logs in using the login page instead of researcher profile. I know django has an admin panel. But I want to build custom admin profile. So when admin logs in using the login page created by myself, admin can see the posts created by users. Also he can add category, approve post, delete post. On the other hand, when researchers logs in, users can see their profile page. blog/models.py from django.db import models from django.utils import timezone from django.contrib.auth import get_user_model from django.urls import reverse from ckeditor.fields import RichTextField # Create your models here. class Category(models.Model): cid = models.AutoField(primary_key=True) category_name = models.CharField(max_length=100) def __str__(self): return self.category_name class Post(models.Model): aid = models.AutoField(primary_key=True) image = models.ImageField(default='blog-default.png', upload_to='images/') title = models.CharField(max_length=200) content = RichTextField() created = models.DateTimeField(default=timezone.now) author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) cid = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='specialization') approved = models.BooleanField('Approved', default=False) like = models.ManyToManyField(get_user_model(), related_name='likes', blank=True) def __str__(self): return self.title users/model.py from django.db import models from blog.models import Category from django.contrib.auth.models import AbstractUser # Create your models here. class CustomUser(AbstractUser): cid = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='specialization', … -
Periodically create/update a model based on another model's annotation
I have model Foo that changes periodically (every week for simplicity). The corresponding API endpoint for this model only needs the annotation foo_annotate. I want to be able to backtrack even if the period changes. My current setup works fine but I realized that if new entries are created in the database, I may run out of storage. So instead of doing that, I create a new model based on the computed value from Foo. Here's what I have so far: class FooManager(models.Manager): ... def get_queryset(self): return super(FooManager, self).get_queryset() \ .annotate(foo_annotate=Coalesce(models.Count("bar"), 0)) # Annotation is much more complex class Foo(models.Model): # Periodic model ... period = models.CharField(...) # Name of current period, unsure if DateField is better user = models.ForeignKey(User, ...) objects = FooManager() class Bar(models.Model): # Fields may change ... foo = models.ForeignKey(Foo, ...) class Baz(models.Model): # Model based on annotation period = ... foo_annotate = ??? -
cannot import name 'urlquote' from 'django.utils.http'
I am trying to login to the admin portal, however I am getting the below error. Please help I have been searching for solution but nothing Exception Type: ImportError at /admin/login/ Exception Value: cannot import name 'urlquote' from 'django.utils.http' (C:_project\my-events\env\lib\site-packages\django\utils\http.py) -
Postgresql cannot connect to server
The project is a django web app, packed on docker containers. For some reason, I cannot run the server and launch it. when I run "manage.py runserver", this error occurs: File "C:\Users\andre\AppData\Local\Programs\Python\Python310\lib\site-packages\psycopg2\__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: connection to server at "158.160.17.21", port 5432 failed: Connection refused (0x0000274D/10061) Is the server running on that host and accepting TCP/IP connections? What do you think can be done with it? Thank you. -
django.db.backends.postgresql
I am trying to switch my Django database from SQLite3 to PostgreSQl, so I follow many tutorials to install and setup Postgres with Django project. I do the following: pip install psycopg2, pip install psycopg2-binary and I modify the settings.py like that: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': BASE_DIR / 'db.postgresql', 'USER': 'muusername', 'PASSWORD': 'mypassword', 'HOST': '127.0.0.1', 'PORT': '5432' } } Finally I make my database, by running the command python manage.py makemigrations. However, I got this error: django.core.exceptions.ImproperlyConfigured: 'django.db.backends.postgresql' isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'sqlite3' Please note that I am also seccesufully install the pgAdmin in my OS which is Windows 10. I know that the problem is postgres is not configured in my django project, but I don't know how to add it, also I check my djnago version which is tha latest one, also all needed packages are installed in venv. -
Deploy django/react on the same server, different port?
I have 2 projects for backend and frontend which are written in django and react respectively. I bought one linux server, now I'm wondering is it possible to deploy these two projects in one server? (in different ports), if so, how? To be honest, I can't find any good articles about this. I have an experience deploying only django projects using linux/apache... -
Polygon selection based on marker position in leaflet
On the map, I have an added layer with polygons and one marker on another layer. When I click anywhere, the marker moves to that location and the polygon is selected. The marker has the ability to drag across the map, but just when I drag it, the polygon selection does not appear. How to do this? var osm = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' }); var map = new L.Map('map', { 'center': [51, 17], 'zoom': 6, 'layers': [osm], }); var selected; var marker marker = L.marker([51, 17], { draggable: true }).addTo(map); var geoJsonLayer2 geoJsonLayer2 = L.geoJson( polygons ,{ style: { fillColor: "#1ED100", color: "orange", fillOpacity: 0.0, opacity: 0.0, }, }) .on('click', function (e) { // Check for selected if (selected) { // Reset selected to default style e.target.resetStyle(selected) } // Assign new selected selected = e.layer // Bring selected to front selected.bringToFront() // Style selected selected.setStyle({ 'color': 'red', 'opacity': 1, }) }) .addTo(map); marker.on('dragend', function (e, feature) { updateLatLng(marker.getLatLng().lat, marker.getLatLng().lng); }); map.on('click', function (e) { marker.setLatLng(e.latlng); updateLatLng(marker.getLatLng().lat, marker.getLatLng().lng); }); function updateLatLng(lat, lng, reverse) { if (reverse) { marker.setLatLng([lat, lng]); map.panTo([lat, lng]); } else { document.getElementById('lat').value = marker.getLatLng().lat.toFixed(10); document.getElementById('long').value = marker.getLatLng().lng.toFixed(10); map.panTo([lat, lng]); document.getElementById("lat").value = lat.toFixed(10); document.getElementById("long").value = … -
ModuleNotFoundError: No module named 'application' when deploying Django app to AWS EB
I'm trying to deploy a django project to Elastic Beanstalk. I have the following code in .ebeextensions/django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: pos.wsgi:application aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: pos.settings I see this error all the time in the logs ModuleNotFoundError: No module named 'application' I've tried to write the config file this way, but still the same error option_settings: aws:elasticbeanstalk:container:python: WSGIPath: pos/wsgi.py Here is the platform Python 3.8 running on 64bit Amazon Linux 2/3.4.2 -
Need help about redirecting views in Django (New)
I have posted a question with the same title as this one, everyone can see it from this link Unfortunately, because that was my first time making a question, some format mistakes were made and that question is closed for the moment. I have edited it and resubmitted for opening again but I don't know how long will that take so I might as well make a new one. I'm working on a web application for reading novels and currently I'm stuck at a certain part in directing views using urls. I use Django as the back end with PostgreSQL as the database and HTML with bootsrap as front end. I will post my code below: This is my urls.py (from the project folder): from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('app.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) This is my urls.py (from the app folder): from django.contrib import admin from django.urls import path, include from django.contrib.auth import views as auth_views from . import views urlpatterns = [ path('', views.home), path('book/<slug:book_slug>/<slug:chapter_slug>/', views.detail, name='detail'), path('genre/<slug:category_slug>', views.category_detail, name='category_detail'), path('book/<slug:book_slug>', views.book_detail, name='book_detail'), path('register/', views.register, name="register"), path('login/',auth_views.LoginView.as_view(template_name="app/login.html"), … -
Submit Button checks if file doesn't select in Django
Currently working on a Django project where I am stuck in a situation and the scenario is something like that I have two forms in my abc.html page, one is used for input file and second is used to run python script internally. But the issue is even if I don't input the file the submit button "run python script" start's working without submitting a file. Here I want to create a check that submit button "run python script" will run only at one condition when file will submitted otherwise button will disable. It will active only at one condition when user will input the file. I am sharing the details: abc.html: <!--form to input file --> <form method="post" enctype="multipart/form-data" name="myform"> {% csrf_token %} <input type="file" id="file" name="doc" class="inputfile" onchange="document.myform.submit()"> </form> <-- end of input file--> <!-- form to run python script --> <form action = "/results/" method="post" id="subform"> {% csrf_token %} <input type="submit" id="btnSubmit" name="doc" value="run python script" class="btn btn-warning btn-sm" /> </form> <-- end of form running python script --> views.py: def compliance_check(request): //function to upload file global uploaded_file if request.method == 'POST': uploaded_file = request.FILES['doc'] print(uploaded_file.name) print(uploaded_file.size) fs = FileSystemStorage() fs.save(uploaded_file.name, uploaded_file) messages.info(request, 'your file ' + … -
submitting django crispy form with file field and some other text fields using fetch and then
I am trying to submit my crispy form using fetch and then methods to django backend. All my fields are submitting to the server. but files are shown as empty fields in the server. below, is my front end from {{ photo.media }} <form action="" method="post" class="form my-4 px-2" enctype="multipart/form-data" id="photo_form" onsubmit=""> {% csrf_token %} {{photo|crispy}} <input type="submit" value="Add" class="btn btn-primary btn-lg"> </form> Here is the ajax request I made <script> const photoForm = document.querySelector('#photo_form'); console.log(photoForm.values); photoForm.addEventListener('submit', (event) => { event.preventDefault(); const photoFormData = new FormData(photoForm); photoFormData.forEach((value, key) => { console.log(key + ': ' + value); }); fetch("{% url 'add_photo' %}", { method: 'POST', body: photoFormData, contentType: false, processData: false, }) .then((response) => response.json()) .then((data) => { console.log(data); if (data.result == 'success') { $('.modal-body').html('Form submission was successful!'); $('#modal-dialog').modal('show'); photoForm.reset(); } else { $('.modal-body').html('There was an error with the form submission.'); $('#modal-dialog').modal('show'); } }); }); </script> Below, is the model I Made class Photos(models.Model): photo_title = models.CharField(max_length=50, blank=False) photo_description = models.CharField(max_length=50, blank=False) photo_date = models.DateField(blank=False) photo_location = models.CharField(max_length=50, blank=False) photo_file = models.ImageField(upload_to='photos', blank=False) def __str__(self): return self.photo_title Below, is the view function """ ajax add photo event to home wall """ def add_photo(request): if request.method == 'POST': response_data = {} photoForm … -
obj.id printing loop of the ids, need to get only the recent/top one
It's a function inside the class ServiceReportCallbackAdmin(BaseAdmin):, I'm calling save_meta from another function, def save_meta(self,obj, form): print(obj.id) when i'm calling this function, i'm getting: 51 45 34 24 17 10 5 3 1 But i just want to get 51 only for further use, how can i do that? -
How to save or upload an image from LOCAL directory to ImageField of database object in DJANGO
i was trying to create some products in ecommerce project in django and i had the data file ready and just wanted to loop throw the data and save to the database with Product.objects.create(image='', ...) but i couldnt upload the images from local directory to database!!! i tried these ways: 1- first try: with open('IMAGE_PATH', 'rb') as f: image = f.read() Product.objects.create(image=image) didnt work!!! 2- second try: image = open('IMAGE_PATH', 'rb') Product.objects.create(image=image) 3- third try: module_dir = dir_path = os.path.dirname(os.path.realpath(__file__)) for p in products: file_path = os.path.join(module_dir, p['image']) Product.objects.create() product.image.save( file_path, File(open(file_path, 'rb')) ) product.save() -
How can I fix this error? json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
https://youtu.be/0iB5IPoTDts?t=4690 I am currently trying to like a product with my microservice per request. Here is the code from his video: https://github.com/scalablescripts/python-microservices This is my code: from flask import Flask, jsonify from flask_cors import CORS from flask_sqlalchemy import SQLAlchemy from sqlalchemy import UniqueConstraint from dataclasses import dataclass import requests \#from markupsafe import escape \#from jinja2 import escape app = Flask(__name__) app.config\["SQLALCHEMY_DATABASE_URI"\] = 'mysql://root:root@db/main' CORS(app) db = SQLAlchemy(app) @dataclass class Product(db.Model): id: int title: str image: str id = db.Column(db.Integer, primary_key=True, autoincrement=False) title = db.Column(db.String(200)) image = db.Column(db.String(200)) @dataclass class ProductUser(db.Model): id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer) product_id = db.Column(db.Integer) UniqueConstraint('user_id', 'product_id', name='user_product_unique') @app.route('/api/products') def index(): return jsonify(Product.query.all()) @app.route('/api/products/\<int:id\>/like', methods=\['POST'\]) def like(id): req = requests.get('http://host.docker.internal:8000/api/user') return jsonify(req.json()) if __name__ == '__main__': app.run(debug=True, host='0.0.0.0') The API user is called which creates a random user, see code: from django.contrib import admin from django.urls import path from .views import ProductViewSet, UserAPIView urlpatterns = [ path('products', ProductViewSet.as_view({ 'get': 'list', 'post': 'create' })), path('products/<str:pk>', ProductViewSet.as_view({ 'get': 'retrieve', 'put': 'update', 'delete': 'destroy' })), path('user', UserAPIView.as_view()) ] and this is the class that will be executed: class UserAPIView(APIView): def get(self, _): users = User.objects.all() user = random.choice(users) return Response({ 'id': user.id }) I get the following error …