Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery beat doesn't pick up tasks
I have a task that is supposed to run every minute and a celery worker. I have placed the celery.py into my main project folder, where wsgi.py is located and it looks like this: from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'TestTask.settings') app = Celery('TestTask') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(settings.INSTALLED_APPS) @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task(60.0, print_hw(), name="print_hw") @app.task def print_hw(): print('hello_world') app.conf.beat_schedule = { 'print_hello_world': { 'task': 'tasks.print_hw', 'schedule': 10.0, } } app.conf.timezone = "UTC" But when I run the command celery -A TestTask beat I only see the following in the console: celery beat v5.3.1 (emerald-rush) is starting. __ - ... __ - _ LocalTime -> 2023-08-30 14:20:04 Configuration -> . broker -> redis://127.0.0.1:6379/0 . loader -> celery.loaders.app.AppLoader . scheduler -> celery.beat.PersistentScheduler . db -> celerybeat-schedule . logfile -> [stderr]@%WARNING . maxinterval -> 5.00 minutes (300s) And nothing happens afterwards, i.e. tasks aren't being identified/executed by the worker. Any idea what I did wrong here or what can be the problem? -
how to integrate django and scrapy and celery?
I have a django project and in its root directory i have a scrapy project that has a spider that should be run every 24 hours and it scrapes provided urls and saves data to a mysql database using django model. i want to shcedule this task using celery beat but i don't know how to integrate django and scrapy project. this is how my project tree looks like: news-website | ├──django_app | └──models.py | ├──news-website | └──settings.py (and other django auto made files are in this directory) | ├──manage.py ├──tasks.py | └──scrapy_project ├──scrapy_project | ├──settings.py | ├──piplines.py | ├──items.py | └──spiders | └──spider.py └──scrapy.cfg i tried to create a file in root directory named as tasks.py and i tried to run my spider in it but when i run tasks.py i get this error. from scrapy_project.items import NewsItem ModuleNotFoundError: No module named 'scrapy_project.items' actually i have this line in my spider.py file: from scrapy_prject.items import NewsItem but since i am running my spider from a script it seems that items file is not accessible for it. how should i fix this problem and how should i use celery with this project for scheduling my scraper? -
Django Rest Framework Role and Permissions having hierarchical relationship
We have two user types: service provide customer each user has following roles- admin service and support operator -reporter but each role has follwoing subrole region admin, region operator, region service and support and with same way to other roles site admin, site operaotor , site service and support in above case service provider and cusotmer has hierarchical relationship. service provider in top of customer. then how to manges role and permission with hierarchical in efficent way ? how to get data in hierarchial way ? then how to manges role and permission with hierarchical in efficent way ? how to get data in hierarchial way ? -
How to serve django static files via kong and nginx
I have Django app, nginx and Kongo. I configured the service and routes. I have a simple web page with a form. In order to display it correctly, you need to load static files such as js, css, png. I don't understand how to tell Kongo routes to static files. django nginx kong deployed in docker. Didn't find any information on how to do it. -
How to integrate OTP sending with Celery into a project?
Here is my viewset and serialsers. I want to integrate OTP sending during user authorization. To pass successful authorization, you need to enter a 6-digit OTP code. How can I do it better? I also want to connect Celery to send OTP codes. from djoser.views import UserViewSet class AccountViewSet(UserViewSet): queryset = User.objects.all() search_fields = ('^username', '^email', '^first_name', '^last_name') from djoser.serializers import UserCreateSerializer as UserCreate from djoser.serializers import UserSerializer class CustomUserCreateSerializer(UserCreate): password = serializers.CharField( max_length=MAX_LENGTH_PASSWORD, required=True, write_only=True, validators=[ MinLengthValidator( limit_value=MIN_LENGTH_PASSWORD, message='Password must be longer than 6 characters' ), MaxLengthValidator( limit_value=MAX_LENGTH_PASSWORD, message='Password must be shorter than 30 characters' ), validate_password ], help_text=( 'Enter password.' 'It must include lowercase and uppercase letters ' 'of the Latin alphabet and numbers.' ), ) email = serializers.EmailField( validators=[ UniqueValidator( message='This email is already taken', queryset=User.objects.all() ), MaxLengthValidator( limit_value=MAX_LENGTH_EMAIL, message=( 'Email must be shorter than' f'{MAX_LENGTH_EMAIL} characters' ) ) ], required=True ) username = serializers.CharField( validators=[ UniqueValidator( message='This username is already taken', queryset=User.objects.all() ), validate_username ], required=True ) first_name = serializers.CharField( max_length=MAX_LENGTH_USERNAME, help_text='Enter your first name', validators=[validate_first_name], required=True ) last_name = serializers.CharField( max_length=MAX_LENGTH_USERNAME, help_text='Enter your last name', validators=[validate_last_name], required=True ) class Meta(UserCreate.Meta): model = User fields = ( 'id', 'email', 'first_name', 'last_name', 'username', 'password' ) class CustomUserSerializer(UserSerializer): … -
Django Image upload missing exif data on Android Chrome devices
I'm having some issues with a project I'm working on at the moment. In testing on my local machine there were no issues, on production there are no issues via a desktop PC but I am experiencing issues on Android Chrome which will be the main use for the application. Essentially I have a simple form in django that takes a few values and has an Image Upload field. I then have the following piece of code at the start of the submission: if request.method == "POST": form = ImageUploadForm(request.POST, request.FILES) image = request.FILES.get('image') print(image) try: x = float(getgpsloc(image)[0]) y = float(getgpsloc(image)[1]) The process will upload the file, take the GPS and some other exif data and if valid submit some of this information to the database and at the same time strip the exif data from the image and rename the file so there is no user identifiable information. As noted, on PC this works fine, the getgpsloc function reads all of the exif fields as expected. On Android Chrome however it appears as though only a couple of the exif data fields are present in the image file that is then causing a divde by zero error as … -
Why is running django app in cmd giving me a module error?
each time I try to run my django app it is giving me this error( ModuleNotFoundError: No module named 'django.contrib.genresdjango') The genres is the page iam trying to create I tried removing the line from the django settings.py it is running perfectly but when i add the line for my app it is not -
How can I check what is the maximum python version that I use with in my Django?
I'm using Django with many pip modules; python version is 3.7.5. I want to write a script that will tell me at any given moment what is the maximum python version that I can use without pip module changes. Thank you. -
Fetching Captions from CustomImage Model for Images in Wagtail RichText
I'm working on a Wagtail project and I'm trying to dynamically fetch captions from a CustomImage model to display below images within a RichText field. However, I've encountered challenges in implementing this functionality correctly. In my project, the rich text field is loaded as follows: <div class="blog_detail_content"> {{ page.body }} </div> the images used within the RichText field are loaded as follows on the browser: <img alt="alt_Text" class="richtext-image full-width" height="400" src="/media/images/discovering_e-paath_in_canada_5.width-800.jpg" width="800"> The CustomImage model is related to the images used in the default richtext field provided by Wagtail. Desired Outcome: I want to dynamically fetch captions from the CustomImage model and display them below the images in the RichText field. What I've Tried: I've attempted to implement this by using JavaScript and creating API endpoints, but I'm facing difficulties in correctly associating images with their respective captions. Code Samples: #custom images model class CustomImage(AbstractImage): alt_text = models.CharField(max_length=255, blank=True, null=True, help_text="alt text for the image") caption = models.TextField(blank=True, null=True, help_text="caption for the image") admin_form_fields = Image.admin_form_fields + ( 'alt_text', 'caption' ) class CustomRendition(AbstractRendition): image = models.ForeignKey(CustomImage, on_delete=models.CASCADE, related_name='renditions') class Meta: unique_together = ( ('image', 'filter_spec', 'focal_point_key'), ) #views to retrive the caption from the customimagemodel with provided image **def get_caption(request, … -
Switching to a web framework from vanilla WSGI
Our stack split into four main components: Several web applications that contain only the presentation layer Another application that we called Warden that contains a set of WSGI endpoints that we define ourselves. A library of classes that represent our database entities. A PostgreSQL database In order for the web applications to make requests to the database, they talk to the Warden. We have realised that our user's needs are such that we need to write endpoints often and continually. The fact that we explicitly write our endpoints means that the turn around time from getting a request from a user to implementing is very slow. Is it possible to rewrite our Warden in a web framework? Is there a framework that is particularly suited to this? Alternatively, is there a different and better approach to this problem? -
deplpoy django app to azure cloud with debug = 0
I have depployd a django app to the azure cloud environment. But I still see the message: You’re seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, and only the initial error message will be displayed. But I have set the debug to 0: settings.py: SECRET_KEY = os.environ.get('SECRET_KEY') DEBUG = bool(int(os.environ.get('DEBUG', 0))) ALLOWED_HOSTS = ['https://docker.azurewebsites.net'] ALLOWED_HOSTS.extend( filter( None, os.environ.get('ALLOWED_HOSTS', '').split(" "), ) ) CSRF_TRUSTED_ORIGINS = ["https://docker.azurewebsites.net"] And if I run the container on localhost. It works. I don't see the extra information. Just output: Not Found The requested resource was not found on this server. But when I enter the url https://site.azurewebsites.net/admin/login/?next=/admin/ Then the information is shown: Help Reason given for failure: Origin checking failed - https://docker.azurewebsites.net does not match any trusted origins. In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django’s CSRF mechanism has not been used correctly. For POST forms, you need to ensure: Your browser is accepting cookies. The view function passes a request to the template’s render method. In the template, there is a {% csrf_token %} template tag inside each POST form that targets … -
OVERRIDING THE ORDER OF FIELDS IN SERIALIZER RESPONSE
class Meta: model = Order fields = ( 'brand', 'currency', 'order_id', 'reference_id', 'ordered_date', 'amount', 'quantity', 'order_status', 'app_code', 'vouchers') I need to change the ordering of field's on response. I have changed the ordering in class Meta. its not working i have tried to_representation method. -
Djang - 404 Error occurs only at specific time
I'm running my Django project in a docker container on AWS EC2 instance. There are some APIs and all of them have been working fine for several months. But since last week, APIs return 404 error only around 6pm everyday. <head><title>404 Not Found</title></head> <body> <center><h1>404 Not Found</h1></center> <hr><center>openresty/1.19.9.1</center> </body> </html> Is there any way to solve this error? Any comments would be appreciated. -
costum variable index inside a DJango template
I have a template in Django that is generated by a for loop like {% for test in test_list %} <!-- dome code here --> {% if not test.testInPausa %} <div class="progress-wrapper-{{ forloop.counter0 }}"> <div id="progress-bar-{{ forloop.counter0 }}" class="progress-bar-{{ forloop.counter0 }} progress-bar-striped" > &nbsp; </div> </div> <div id="progress-bar-message-{{ forloop.counter0 }}"> Waiting for progress to start... </div> {% endif %} {% endfor %} Now, I would like to count the time in which the code enter the if statement. I want to do so because, at the moment, the id and class inside the div are indexed by the forloop.counter, which, because it doesn't always enter the if statement, counts every for loop making the id and class jump index. Is there a way to have something {% for test in test_list %} {% my_index = 0 %} <!-- dome code here --> {% if not test.testInPausa %} <div class="progress-wrapper-{{ my_index }}"> <div id="progress-bar-{{ my_index }}" class="progress-bar-{{ my_index }} progress-bar-striped" > &nbsp; </div> </div> <div id="progress-bar-message-{{ my_index }}"> Waiting for progress to start... </div> {% my_index++ %} {% endif %} {% endfor %} -
Read data from dynamic table Django
I have automated batch processn creates tables in sqlite DB and update the table in one of the table defined by Django ORM. I would like to use Django ORM to select data from newly created DB. -
Charts not loading out data for my django project
So, I've been trying to get my charts to display packages created per hour, but it doesn't render out the data on the chart. The axes display though. When I use print statements in the view, it returns an empty array for the hours, despite the same code working for a different project def warehouse_dashboard(request): user = request.user if user.role == 'warehouse_admin': warehouse = user.warehouse_admin_field if warehouse: buses = Bus.objects.filter(warehouse=warehouse) # Filter items that are either assigned to a bus or have a delivery status of "Ready" packages_coming = Item.objects.filter( Q(station_to=warehouse, bus_number_plate__isnull=False) | Q(station_to=warehouse, delivery_status='Ready') ).exclude(delivery_status__in=['Canceled', 'Received', 'Ready']) packages_leaving = Item.objects.filter(station_from=warehouse).exclude(delivery_status='Canceled') packages_by_bus = {} for bus in buses: packages_from = Item.objects.filter( Q(station_from=warehouse) | Q(station_to=warehouse), bus_number_plate=bus ).exclude(delivery_status='Canceled') packages_by_bus[bus] = packages_from bus_count = buses.count() packages_count_coming = packages_coming.count() packages_count_leaving = packages_leaving.count() # Retrieve data for the graph (daily packages added) # Get the datetime for the start of the current day current_day_start = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0) hourly_totals = Item.objects.filter( station_from=warehouse, creation_date__gte=current_day_start ).annotate(hour=ExtractHour('creation_date')).values('hour').annotate(total=Count('id')).order_by('hour') # Initialize an array to hold the data for each hour of the day chart_data = [0] * 24 for total in hourly_totals: hour = total['hour'] if hour is not None: chart_data[hour] = total['total'] print(chart_data[hour]) # Get the number of … -
Permission denied for ..../<id>/ CRUD ModelViewSet endpoints
I am trying to create a ModelViewSet for supporting CRUD operations on my address model. I am able to successfully use LIST and CREATE endpoints, but all the other 4 endpoints which require/id/ in their URL return me the error - { "detail": "You do not have permission to perform this action." } The address model should support the operations only by the Users who are marked NOT SELLER in the DB, hence the ~IsSeller custom permission is applied. The issue goes away when I remove this custom permission from permissions classes, but i need to keep this restriction of only non-seller users to be able to add the address. permissions.py from rest_framework.permissions import BasePermission class IsSeller(BasePermission): def has_permission(self, request, view): return (request.user and request.user.is_seller) Views.py class ManageAddressViewSet(viewsets.ModelViewSet): serializer_class = AddressSerializer permission_classes = [permissions.IsAuthenticated, (~IsSeller)] queryset = Address.objects.all() def get_queryset(self): return self.queryset.filter(user=self.request.user) def perform_create(self, serializer): return serializer.save(user=self.request.user) Serializers.py class AddressSerializer(serializers.ModelSerializer): class Meta: model = Address fields = [ 'id', 'name', 'line_1', 'line_2', 'city', 'state', 'pincode', 'type' ] read_only_fields = ['id'] urls.py from django.urls import path, include from rest_framework.routers import DefaultRouter from user import views router = DefaultRouter() router.register('address', views.ManageAddressViewSet) urlpatterns = [ path('create/', views.CreateUserView.as_view(), name='create'), path('authenticate/', views.CreateTokenView.as_view(), name='authenticate'), path('my-profile/', views.ManageUserView.as_view(), … -
How to deploy my Django project into plesk server and run it , give me a step by step process please
I need to know how deploy my project into plesk , i never done this before. I search in Youtube but i can't fine a video for it . chat gpt also not give a clear steps i have a plesk panel credentials and i verify the python installed or not , it instaled and pip also there i created a virtual environment too , i upload the django folder to plesk server, i don't know what to do next, the problem is i want to upload my django project to pleask that i don't know -
Unable to get the date from tempusdominus bootstrap4 plugin to Django form
Here is my html code. <div class="col-md-3"> <label> Approved Date:</label> <div class="input-group date" id="{{ form.ApprovedDate.id_for_label }}" data-target-input="nearest"> <input type="text" class="form-control datetimepicker-input" id="{{ form.ApprovedDate.id_for_label }}" name="{{ form.ApprovedDate.id_for_label }}" data-target="#{{ form.ApprovedDate.id_for_label }}"/> <div class="input-group-append" data-target="#{{ form.ApprovedDate.id_for_label }}" data-toggle="datetimepicker"> <div class="input-group-text"><i class="fa fa-calendar"></i></div> </div> </div> </div> and here is the Script Jquery <script> $(function () { $('#{{ form.ApprovedDate.id_for_label }}').datetimepicker({ format: 'DD-MM-YYYY' }); }) </script> My problem is that this field is not being passed to my django form which is of this code. class ProjectForm(forms.ModelForm): #views.py class Meta: model = Project fields = '__all__' def save(self, commit=True): instance = super().save(commit=False) instance.created_on = timezone.now() # Import timezone if not already imported instance.createdBy = 0 if commit: instance.save() return instance def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in iter(self.fields): self.fields[field].widget.attrs.update({ 'class': 'form-control' }) I simply want to read value of this field so the same can be saved to db. by this code in views.py def create_project(request): if request.method == 'POST': form = ProjectForm(request.POST) if form.is_valid(): form.save() # Save to the database with the modified fields return redirect('projects:project_list') # Redirect to the list view else: form = ProjectForm() return render(request, 'create_project.html', {'form': form}) I have tried many solutions like importing tempusdominus package but I … -
python setup.py egg_info did not run successfully : when trying to install psycopg2
I am facing this issue when trying to run psycopg2, any one with solution would be helpful, thanx! Collecting psycopg2==2.8.6 (from -r requirements.txt (line 45)) Using cached psycopg2-2.8.6.tar.gz (383 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [37 lines of output] running egg_info creating /tmp/pip-pip-egg-info-kg2ft5p1/psycopg2.egg-info writing /tmp/pip-pip-egg-info-kg2ft5p1/psycopg2.egg-info/PKG-INFO writing dependency_links to /tmp/pip-pip-egg-info-kg2ft5p1/psycopg2.egg-info/dependency_links.txt writing top-level names to /tmp/pip-pip-egg-info-kg2ft5p1/psycopg2.egg-info/top_level.txt writing manifest file '/tmp/pip-pip-egg-info-kg2ft5p1/psycopg2.egg-info/SOURCES.txt' /home/lungsang/Desktop/Contextus/env/lib/python3.8/site-packages/setuptools/config/setupcfg.py:293: _DeprecatedConfig: Deprecated config in `setup.cfg` !! parsed = self.parsers.get(option_name, lambda x: x)(value) Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. For further information please check the 'doc/src/install.rst' file (also at <https://www.psycopg.org/docs/install.html>). [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed This error appears when i try to run psycopg2 and I upgraded setuptools, still not solved. -
copy to clipboard not working with django and js
Hi guys I created a basic copy to clipboard functionality using django and js, everything seems to be ok but when i try to copy my info i get this error This is the piece of code where I'm doing everything <table class="init-datatable display"> <thead> <tr> <th>Company</th> <th>Avt User Name</th> <th>Full Name</th> <th class="email-column">Email Address</th> <th>Expiration Date</th> <th>Avt Version</th> <th>License</th> <th>Generated User</th> <th>Copy information</th> </tr> </thead> <tbody> {% for item in object_list %} <tr> <td class="th-width">{{ item.user.company.name }}</td> <td class="th-width">{{ item.user.user_name }}</td> <td class="th-width">{{ item.user.full_name }}</td> <td class="th-width email-column">{{ item.user.email }}</td> <td class="th-width">{{ item.expire_date }}</td> <td class="th-width">{{ item.avt_version}}</td> <td class="th-width">{{ item.license_avt }}</td> <td class="th-width">{{ item.generated_user.username }}</td> <td class="th-width"> <button class="control button copy-btn btn" company-name="{{item.user.company.name}}" user-name="{{item.user.user_name}}" full-name="{{item.user.full_name}}" email="{{item.user.email}}" expire-date="{{item.expire_date}}">Copy information</button> </td> </tr> {% endfor %} </tbody> </table> <script> const copyBtns = [...document.getElementsByClassName("copy-btn")] copyBtns.forEach(btn => btn.addEventListener('click', ()=>{ const companyName = btn.getAttribute("company-name") const userName = btn.getAttribute("user-name") const fullName = btn.getAttribute("full-name") const email = btn.getAttribute("email") const expireDate = btn.getAttribute("expire-date") console.log(companyName) console.log(userName) console.log(fullName) console.log(email) console.log(expireDate) btn.textContent = "Copied" setTimeout(() => { btn.textContent = "Copy information" }, "1350"); navigator.clipboard.writeText(companyName) })) </script> If someone can tell me how to fix this or another way to tackle this feature of copying stuff from the HTML it would be … -
How to implement ForeignKey search in Django REST framework
When developing the API, I tried to implement a search system but encountered an error Unsupported lookup 'icontains' for ForeignKey or join on the field not permitted. Models class GroupTask(models.Model): UserToken = models.TextField(default="") NameGroupTask = models.TextField(null=True) StatusGroupTask= models.BooleanField(default=False) class Meta: ordering = ['NameGroupTask'] def __str__(self): return self.NameGroupTask[0:50] class TaskForGroup(models.Model): UserToken = models.TextField(default="") NameTaskForGroup= models.TextField(null=True) DescriptionTask = models.TextField(null=True) StatusTaskForGroup= models.BooleanField(default=False) Group = models.ForeignKey(GroupTask, on_delete = models.CASCADE) class Meta: ordering = ['NameTaskForGroup'] def __str__(self): return self.NameTaskForGroup[0:50] viewsets for output class TaskForGroupAPI(viewsets.ModelViewSet): # показываем что доступны все методы для работы с данными (post, get, put, delete запросы) queryset= TaskForGroup.objects.all() # указываем сериализатор serializer_class = TaskForGroupSerializer # устанавливаем классы для фильтрации filter_backends = (DjangoFilterBackend, SearchFilter) # указываем поле по которому проводить фильтрацию search_fields = ['Group',] def get_paginated_response(self, data): return Response(data) how am I trying to find the TaskForGroup I need http://127.0.0.1:8000/TaskForGroupAPI/TaskForGroupAPI/?search=5 -
Ajax Request is returning error with log: {readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}
I have a Django application where I have an html page with two forms that I want to be submitted with two different ajax requests. The first request works perfectly fine, but for some reason the second request results in an error response I'm printing out to the console like this: {readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …} abort : ƒ (a) always : ƒ () complete : ƒ () done : ƒ () error : ƒ () fail : ƒ () getAllResponseHeaders : ƒ () getResponseHeader : ƒ (a) overrideMimeType : ƒ (a) pipe : ƒ () progress : ƒ () promise : ƒ (a) readyState : 4 responseText : "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n setRequestHeader : ƒ (a,b) state : ƒ () status : 200 statusCode : ƒ (a) statusText : "OK" success : ƒ () then : ƒ () [[Prototype]] : Object I have no clue how to debug this... The first ajax request is just to partially fill the second form. The second form is a Model Form that is supposed to add an instance off my model in my view. View: def canadaTaxEntries(request): newest_record = LAWCHG.objects.aggregate(Max('control_number')) newest_control_number = newest_record["control_number__max"] print(newest_control_number) today = date.today().strftime("1%y%m%d") … -
How get Nearby place information's like school, hospital, malls and cinema hall in django
I am creating a real estate rental project and in that I want to show a property and nearby places to that particular property to the users using latitude and longitude of the property. I have no idea how to do that, so can you please tell all steps including what required files I need to install as well. Please show me complete guide with code. -
Why is DRF's router selectively not redirecting to a trailing slash?
Desired behavior For router endpoints to append a trailing slash if one is not provided. E.g. /api/customers would redirect to /api/customers/ Actual behavior A 404 is returned if a trailing slash isn't applied to the endpoint. E.g. /api/customers return a 404 response Additional context APPEND_SLASH is set to True CommonMiddleware is set The trailing slash works on non-DRF endpoints. E.g. /admin redirects to /admin/ The trailing slash works on one set of ViewSet endpoints. The user ViewSet works. E.g. /users redirects to /users/ The user app is the last app in the project alphabetically. None of the other ViewSets registered redirect to the trailing slash. Code project_name/urls.py from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include from rest_framework import routers from user.views import UserViewSet, LoginView, logout_view from customer.views import CustomerViewSet from intake.views import IntakeViewSet from extraction.views import ExtractionViewSet router = routers.DefaultRouter() router.register(r'users', UserViewSet, basename='users') router.register(r'customers', CustomerViewSet, basename='customers') router.register(r'intakes', IntakeViewSet, basename='intakes') router.register(r'extractions', ExtractionViewSet, basename='extractions') urlpatterns = [ path('admin/', admin.site.urls), path('api/', include(router.urls)), path('api/login/', LoginView.as_view()), path('api/logout/', logout_view), ] if settings.DEBUG: # Add dev static files urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # Add debug toolbar patterns urlpatterns.append(path('__debug__/', include('debug_toolbar.urls'))) TLDR Only one set of endpoints registered to DRF's …