Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
My css styles don't connect to my django-written website
Some styles were connected without any problems, but I managed to make only one section, as they stopped connecting and my entire site began to look like a document in word I have already searched for similar problems here, tried the solutions given; I also searched for how to connect styles, etc. Unfortunately, I did not find a solution to my problem, so I am writing here Base.html {% load static %} <!DOCTYPE html> <html lang="ru"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{% block title %}{% endblock %}</title> {% block css %} <link rel="stylesheet" href="{% static 'css/_normalize.css' %}"> <link rel="stylesheet" href="{% static 'css/main.css' %}"> {% endblock %} </head> index.html {% extends './base.html' %} {% load static %} {% block css %} <link rel="stylesheet" href="{% static 'css/main.css' %}"> {% endblock %} {% block title %} Главная {% endblock %} {% block content %} <section class="hero"> <div class="container hero__container"> <div class="hero__content"> <div class="hero__text"> <h1 class="title hero__title"> Центр подбора лечения от&nbsp;алкоголизма, наркомании и&nbsp;других зависимостей </h1> <h4 class="title hero__subtitle"> Мы&nbsp;приходим на&nbsp;помощь в&nbsp;самых нелегких ситуациях и&nbsp;точно знаем как можем помочь и&nbsp;пациенту, и&nbsp;его близкому окружению. </h4> </div> <button class="btn btn-reset hero__btn"> <a href="#" class="link-reset hero__link">Бесплатная консультация</a> </button> </div> <div class="hero__image"> <img src="{% static 'images/hero/hero-img.png' %}" … -
Can't send files to ChatConsumer in Django Channels
I'm having an issue with sending files to a handler in ChatConsumer using Django Channels. I have two consumers, ChatConsumer and GroupChatConsumer, for handling direct messages and group messages. I want to send files to ChatConsumer or GroupChatConsumer based on whether a group exists or not. If the group doesn't exist then file should go to ChatConsumer I'm sending the files using channel_layer.group_send through views. Keep in mind I have the same handler name in ChatConsumer and GroupConsumer but despite changing those the issue persists What i have tried: Added print statements right after group_send to confirm if they execute without any error and they do! I also added logging inside ChatConsumer to see if any file or message is recived but there isn't! Ensured if the websocket connections are active and they are! So how can I verify if a message is successfully sent to ChatConsumer? Why is the consumer not receiving any messages? My code: https://github.com/Kioshi5581/djchat -
Django Debug Toolbar is not showing
After setting all the configuration i still cant see the toolbar. P.S. some of ther other not related to the problem code were removed to save space What I Did python -m pip install django-debug-toolb settings.py Also tried adding fix for set content type of js files in Django import mimetypes mimetypes.add_type("application/javascript", ".js", True) from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.staticfiles', 'playground', "debug_toolbar", ] MIDDLEWARE = [ "debug_toolbar.middleware.DebugToolbarMiddleware", 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'storefront.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'storefront.wsgi.application' STATIC_URL = 'static/' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' INTERNAL_IPS = [ "127.0.0.1", ] urls.py from django.conf import settings from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('playground/', include('playground.urls')), ] if settings.DEBUG: import debug_toolbar urlpatterns += path('__debug__/', include(debug_toolbar.urls)), after all these changes i just ran python manage.py runserver or F5 And after all these steps i still dont see the toolbar -
Django: Html select with onchange action (without using form) and pure Javascript: redirect with code 200 but page not loaded
I have a select box in my template that reacts on changes with the onchange function that sends the selected value to the Django view. The view gets the required data from the database and should display them. main.html {% block content %} <select class="form-select form-select-lg mb-3 categorySelect select" name="categorySelect" aria-label="Select category" onchange="getSelectedId(value)"> <option value="None">Select category</option> <option value="all">All</option> <option value="cat1">Category 1</option> <option value="cat2">Category 2</option> </select> {% endblock %} select.js function getSelectedId(selectedValue) { const value = selectedValue; const endpoint = "/all/select"; fetch(endpoint + "?select_id=" + value) .then() .then(response => { }) } views.py def select(request): select_id = request.GET.get("select_id", "None") print(select_id) if select_id.__contains__('None'): return render(request, "home/main.html" ) elif select_id.__contains__('all'): return redirect(reverse('all:probe_list')) elif select_id.__contains__('cat1'): selected = "Category 1" config = RequestConfig(request) resultTable = AllProbesTable(Probe.objects.filter(category = "cat1")) config.configure(resultTable) return render(request, 'all/selectResults.html', {'table':resultTable, 'selected': selected}) I get the correct select_id in the view and the I get a 200 from the redeirect but the page is not changing (similar to This question). I understand that I need to add a reload such as "location.reload()". I added this to the template I am redirecting to but this did not work. Is there any way to trigger a reload or is there another way to implement a … -
Is Enumerating Through Multiple Categories in API Tests a Good Practice? Alternatives for View Testing?
I'm currently writing tests for my Django application using pytest and pytest-django. One of my tests involves creating multiple category instances and verifying that they are correctly listed in the API response. Here’s a snippet of the test: @pytest.mark.django_db def test_auth_user_can_list_categories(auth_client, category_factory): categories = category_factory.create_batch(5) url = reverse("category-list") response = auth_client.get(url) assert response.status_code == 200 for i, category in enumerate(categories): assert response.data[i]["id"] == category.id assert response.data[i]["name"] == category.name In this test, I’m creating 5 distinct categories and then using enumerate to loop through them to verify that each category is correctly listed in the API response. I’m wondering if this approach of enumerating through the categories to match them with the API response is considered a good practice. Are there any better or more efficient ways to test this scenario? Specifically, are there alternative strategies for view testing that could offer more robust or scalable solutions? I’d appreciate any advice or best practices on how to improve this test or alternative methods to achieve the same results. -
Background-image in CSS url blocked by Opaque Response Blocking
I use a background-image like this: <style> .bg-image { background-image: url("{{ instance.background.url }}"); } </style> but the request gets blocked A resource is blocked by OpaqueResponseBlocking. Displaying the image the 'normal' way with <img src="..."> works perfectly. I tried setting a header in CORS-Configuration like: Content-Type: text/css but that did not change anything. I did specify the origin domain and allowed GET, PUT, DELETE, POST and HEAD. -
Django Session variables not visible after login
I am developing a hospital site. patients are allowed to login and book appointment. When a patient logs in, a sessions is initiated and saved. Again, I debugged, by adding a print statement after saving the sessions in the login view and its good, but when i try to book an appointment, then i print the session variables, they are empty. Could anyone please help me on this.... I would really appreciate. Note: My frontend is built with Next.js and am adding credentials='include' on my request. Also the cookies are set well in my browser with the key: sessionid and its value. const response = await fetch( "http://127.0.0.1:8000/bookings/book-appointment/", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(appointmentData), credentials: "include" } ); @csrf_exempt def login_view(request): if request.method == 'POST': try: data = json.loads(request.body) email = data.get('email') password = data.get('password') # Fetch the user from the database user = Patient.objects.filter(email=email).first() # Check if user exists and password is correct if user and user.check_password(password): # Handle 2FA if enabled if user.enable_2fa: generate_and_send_2fa_code(user) return JsonResponse({ 'success': True, 'message': '2FA code sent', 'user_id': user.id, 'email': user.email, 'requires_2fa': True }) # Set session expiry time request.session.set_expiry(2 * 60 * 60) # 2 hours # Log … -
Django error on forms when running makemigrations
I'm getting the following error when trying to make migrations for my models. This is against a clean DB so it is trying to generate the initial migrations. File "/Users/luketimothy/Library/Mobile Documents/com~apple~CloudDocs/LifePlanner/LifePlanner/LifePlanner/urls.py", line 20, in <module> from . import views File "/Users/luketimothy/Library/Mobile Documents/com~apple~CloudDocs/LifePlanner/LifePlanner/LifePlanner/views.py", line 7, in <module> from .forms import AppUserForm, IncomeSourceForm, AccountForm, SpouseForm, DependentForm File "/Users/luketimothy/Library/Mobile Documents/com~apple~CloudDocs/LifePlanner/LifePlanner/LifePlanner/forms.py", line 32, in <module> class AccountForm(forms.ModelForm): File "/Users/luketimothy/Library/Mobile Documents/com~apple~CloudDocs/LifePlanner/LifePlanner/ProjectEnv/lib/python3.11/site-packages/django/forms/models.py", line 312, in __new__ fields = fields_for_model( ^^^^^^^^^^^^^^^^^ File "/Users/luketimothy/Library/Mobile Documents/com~apple~CloudDocs/LifePlanner/LifePlanner/ProjectEnv/lib/python3.11/site-packages/django/forms/models.py", line 237, in fields_for_model formfield = f.formfield(**kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/Users/luketimothy/Library/Mobile Documents/com~apple~CloudDocs/LifePlanner/LifePlanner/ProjectEnv/lib/python3.11/site-packages/django/db/models/fields/related.py", line 1165, in formfield "queryset": self.remote_field.model._default_manager.using(using), ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'NoneType' object has no attribute 'using' This is the form in my forms.py: class AccountForm(forms.ModelForm): class Meta: model = Account fields = ['account_name','owner','account_provider','balance'] labels = {'account_name': 'Name','account_provider': 'Account Provider','balance': 'Balance','owner': 'Owner'} And here are the relevant Models in models.py: class Projectable(models.Model): class Meta: abstract = True def project_annual_values(self, years): raise NotImplementedError("Subclasses should implement this method.") def project_monthly_values(self, months): raise NotImplementedError("Subclasses should implement this method.") class AccountProvider(models.Model): name = models.CharField(max_length=64) web_url = models.CharField(max_length=256) login_url = models.CharField(max_length=256) logo_file= models.CharField(max_length=64) def __str__(self): return f"{self.name}" class Account(Projectable): account_name = models.CharField(max_length=100) balance = models.DecimalField(max_digits=15, decimal_places=2) owner = models.ForeignKey(Agent, on_delete=models.CASCADE) account_provider = models.ForeignKey(AccountProvider, on_delete=models.SET_NULL) def get_balance(self): return self.balance def get_account_type(self): … -
order_by combined column in django
I have two models who inherit from another model. Example: class Parent(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, verbose_name="ID") class A(Parent): name = models.CharField(max_length=255, verbose_name="Name") class BProxy(Parent): target = models.OneToOneField('B', on_delete=models.CASCADE) class B(models.Model): name = models.CharField(max_length=255, verbose_name="Name") My query currently looks like this: Parent.objects.all() In my serializer, I check which subclass the parent object is (hasattr(obj, 'a')) and then use either name = obj.a.name or name = obj.b.target.name for the serialized data. But now I would like to sort the queryset for the output. Normally I would use Parent.objects.all().order_by('name') here. But the name is in the subclasses. Would it be possible to combine the “name” columns of the two subclasses and then sort by them? Or is there another solution? -
Django s3 bucket upload with out admin static css and js
Is it possible to upload the files into s3 buckets in Django without uploading default django admin css, js files? all files are getting uploaded; but i need only uploaded files in S3 buckets. Is there any work around for this? Any changes to settings file that will help to achieve this ? -
How do I create Stripe-like DB ID's for Django models?
Core problem I'm trying to solve: I want to have ID's on my database models that are similar to Stripe's (i.e. of the form aaa_ABCD1234 where the ABCD1234 part is a ULID and the aaa_ part is effectively the table name (or a shortened version of it)). This feature has saved me a ton of time in debugging Stripe integrations and I'd love for users of my systems to be able to have those same benefits. However, I know taking the nieve approach and just a string as a primary key on a table is terrible for performance (mostly indexes and consequently joins as I understand it) so I want to take advantage of the built in UUID datatype in the DB to store only the ABCD1234 part in the DB and not store the aaa_ part since that will be identical for all rows in that table. Where I stand today I'm currently thinking of doing this as follows: Have a "private" field on the DB model (call it _db_id?) that is the UUID and technically the primary key on the model in the DB. Have a GeneratedField that takes the above private field and prepends the table prefix … -
How to convert query string parameters from Datatables.js, like columns[0][name] into an object in Python/Django?
I'm using DataTables.js and trying to hook up server-side processing. I'm using Django on the server. Currently, the data to Django looks like: {'draw': '1', 'columns[0][data]': '0', 'columns[0][name]': 'Brand', 'columns[0][searchable]': 'true', 'columns[0][orderable]': 'true', 'columns[0][search][value]': '', 'columns[0][search][regex]': 'false', 'columns[1][data]': '1', 'columns[1][name]': 'Sku', 'columns[1][searchable]': 'true', 'columns[1][orderable]': 'true', 'columns[1][search][value]': '', 'columns[1][search][regex]': 'false', 'columns[2][data]': '2', 'columns[2][name]': 'Name', 'columns[2][searchable]': 'true', 'columns[2][orderable]': 'true', 'columns[2][search][value]': '', 'columns[2][search][regex]': 'false', 'order[0][column]': '0', 'order[0][dir]': 'asc', 'order[0][name]': 'Brand', 'start': '0', 'length': '10', 'search[value]': '', 'search[regex]': 'false', '_': '1725412765180'} (as a dictionary) However, there's a variable number of columns and order values that might come through. So I'd like to convert all of this into a few key variables: start length search value search regex draw array/list of column objects array/list of order objects But I don't know a lot of python -
JWT token claims in Django Rest Framework
I am using rest_framework_simplejwt, and would like to add extra information to the access token returned for authorization purposes. Following along with https://django-rest-framework-simplejwt.readthedocs.io/en/latest/customizing_token_claims.html I am able to modify the access token. However I want to be able to add a claim based on the initial POSTed login. For example: curl -X POST -H 'Content-type: application/json' -d '{"username": "user1", "password": "supersecretpassword", "project": "project1"}' https://myurl.com/api/token/ I would like to be able to add project1 to the access token. Is there a way to add extra information in that manner? -
Spotify API 403 Forbidden Error When Adding Tracks to Playlist Despite Correct Token and Scopes
I'm experiencing a 403 Forbidden error when trying to add a track to a Spotify playlist using the Spotify Web API. Despite having a correctly configured token and permissions, I’m still facing this issue. Details: Spotify Client ID: 8273bf06015e4ba7a98ca3bbca70acaa Spotify Client Secret: a581f789e2f0442aa95bb33cfe0c7dcb Redirect URI: http://127.0.0.1:8000/callback Access Token Details: { "access_token": "my access token", "token_type": "Bearer", "expires_in": 3600, "refresh_token": "my refresh token", "scope": "playlist-modify-private playlist-modify-public playlist-read-private playlist-read-collaborative", "expires_at": 1725396428 } Error Log: INFO 2024-09-03 20:16:02,097 cron Distributing 1 playlists to job scheduled at 2024-09-03 20:47:02.097874 for Order ID 28. INFO 2024-09-03 20:16:02,100 cron Adding track 0TT2Tzi8mEETCqYZ1ffiHh to playlist 4CeTjVTCZOFzTBdO8yaLvG ERROR 2024-09-03 20:16:02,557 cron Spotify API error: https://api.spotify.com/v1/playlists/4CeTjVTCZOFzTBdO8yaLvG/tracks: Check settings on developer.spotify.com/dashboard, the user may not be registered. ERROR 2024-09-03 20:16:02,558 cron Check if the user 31rizduwj674dch67g22bjqy7sue is correctly registered and has permissions to modify the playlist. What I’ve Tried 1- Verified Token Scopes: The token includes scopes playlist-modify-private and playlist-modify-public. 2- Checked Token Validity: The token is valid and has not expired. I also attempted to refresh it. 3- Confirmed Playlist Ownership: Ensured that the playlist is either owned by or shared with the user whose token is being used. 4- Re-authenticated: Re-authenticated and re-authorized the application to confirm there … -
ImproperlyConfigured: TaggableManager is not supported by modeltranslation
model.py from taggit.managers import TaggableManager class Blog(models.Model): tags = TaggableManager() fields.py if empty_value not in ("", "both", None, NONE): raise ImproperlyConfigured("%s is not a valid empty_value." % empty_value) field = cast(fields.Field, model._meta.get_field(field_name)) cls_name = field.class.name if not (isinstance(field, SUPPORTED_FIELDS) or cls_name in mt_settings.CUSTOM_FIELDS): raise ImproperlyConfigured("%s is not supported by modeltranslation." % cls_name) translation_class = field_factory(field.class) return translation_class(translated_field=field, language=lang, empty_value=empty_value) Can you help me buy such an error after the blog page tag loading process is completed? -
drf-spectacular not recognizing file upload type
I have a Django endpoint that takes a file upload My annotations look like this @extend_schema( request=UploadObservationalSerializer, responses={ 200: GenericResponseSerializer, 400: OpenApiResponse( response=ErrorResponseSerializer, description="Validation error or parsing error" ), 500: ErrorResponseSerializer }, description="Allow user to upload observational data" ) Here is my serializer: class UploadObservationalSerializer(BaseSerializer): calibration_run_id = serializers.IntegerField(required=True) observational_user_file_path = serializers.CharField(required=True) observational_file = serializers.FileField(required=True) def validate_observational_file(self, value): request = self.context.get('request') files = request.FILES.getlist('observational_file') if len(files) != 1: raise serializers.ValidationError("Only one observational file should be uploaded.") return value But in the Swagger, drf-spectacular lists observational_file as a String, not a File Field { "calibration_run_id": 0, "observational_user_file_path": "string", "observational_file": "string" } Why is drf-spectacular not recognizing the file field? -
How can I call delay task in zappa django
In celery I can call task with <func_name>.delay() How can I do it in zappa? I have task: @task() def task_name(): pass -
Implementations of users in django
i was face with problem in implementing users logic, i have five users with the different roles. So in that five users there is admin which have all abilities of system. so i want to add another users which is called master super user. I want to have ability to login than the other users(admin and other users). so even the system is used by the owner ( admin and others) , but i can login and check details. so how can i handle that logic ? am trying to implement but the master super user is like the admin. i want to be unique -
from myshop.shop import views ModuleNotFoundError: No module named 'myshop.shop'
[enter image description here](ht[enter image description here](https://i.sstatic.net/[enter image description here](https://i.sstatic.net/[enter image description here](https://i.sstatic.net/65otzFwB.png)AJ3ur5i8.png)p4Ait5fgenter image description here.png)tps://i.sstatic.net/nY8mtrPN.png) Actually, this is what my project looks like, but for some reason Django doesn't see the module, I've already tried a bunch of things, but nothing helped. Maybe there is someone faced with this ? -
Heroku Django performance issues - Request Queuing
We run a Django application on Heroku, and lately we've been seeing some performance issues. We have New Relic APM add-on installed, and I can see that any time there is a peak in response times, the time is mostly spent in what New Relic calls "Request Queuing" (see attached image). enter image description here Can someone help me figure out what the problem is here? Why are requests queued? Is this a horizontal scaling issue? It does not seem like the Python app itself is Any help welcome! Kind regards, Martijn -
An error occurred while attempting to login via your third-party account in microsoft allauth callback in django
The all auth settins for microsoft is provided here. The authedication is success and getting 200 after microsoft login. [03/Sep/2024 11:44:38] "GET /accounts/microsoft/login/callback/?code=M.C532_BL2.2.U.aec38xxxxxxx0f2ee&state=fi0hMAxxxxU2K HTTP/1.1" 200 1119 Finally page show error Third-Party Login Failure An error occurred while attempting to login via your third-party account. SOCIALACCOUNT_PROVIDERS = { "microsoft": { "APPS": [ { 'client_id': '14bb4', 'secret': 'ed91f8adc68', "settings": { "tenant": "consumers", "login_url": "https://login.microsoftonline.com", "graph_url": "https://graph.microsoft.com", }, 'SCOPE': [ 'openid', 'profile', 'email', ], 'AUTH_PARAMS': { 'response_type': 'code', }, 'OAUTH_PKCE_ENABLED': True, 'TENANT': 'common', 'LOGIN_URL': 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize', 'TOKEN_URL': 'https://login.microsoftonline.com/common/oauth2/v2.0/token', 'GRAPH_URL': 'https://graph.microsoft.com', } ] } } The authendication and azure directry configuration is fine, no error description is available on the call back side from django allauth. i found that the same will work here - https://allauth.org/ but there is no specific description in this page. The callback function is not working after authentication success. -
How do I correctly render a django-view using Apphooks in django-cms?
I am building a project in Django CMS using version 4.1.2. Part of the project will be a news-section, for which I defined a Django model like this: # news/models.py from django.db import models from django.utils import timezone from djangocms_text_ckeditor.fields import HTMLField class Post(models.Model): title = models.CharField(max_length=200, verbose_name="Title") text = HTMLField(verbose_name="Text") user = models.ForeignKey('auth.User', on_delete=models.CASCADE, verbose_name="Author", blank=True, null=True) date = models.DateTimeField(default=timezone.now, verbose_name="Date") class Meta: verbose_name = "Post" verbose_name_plural = "Posts" def __str__(self): return self.title I want this model to be a django model instead of handling it with CMS-Plugins, so that editors can manage Posts using the admin-interface and to make it easier to use things like pagination. I have a little experience with Django, but not really with Django CMS. However, on the page displaying the news-section, I also want to have a header, a sidebar and a footer that should be editable using the CMS-Toolbar. Therefore I made an Apphook - from what I understand this should allow me to integrate the news-page with Django CMS. This is what my Apphook looks like: # news/cms_apps.py from cms.app_base import CMSApp from cms.apphook_pool import apphook_pool from django.urls import path from django.utils.translation import gettext_lazy as _ from news import views @apphook_pool.register … -
Django Template: How to connect chat script passing in Django Tag with JavaScript?
I'm working on a Django project where I need to conditionally render and execute a chat script based on user cookie consent. Here's what I've got so far: In my Django template, I have the following snippet: {% if page.page_type.chat_script %} {{ page.page_type.chat_script|safe }} {% endif %} This snippet is responsible for rendering a chat script (something like chat script code) which is set via the Django admin panel. However, I only want this script to execute if the user has accepted all cookies. I already have a separate JavaScript file (cookies_configuration.js) that handles cookie consent and injects various scripts into the head or body once consent is given (it works pretty fine when I use it with normal different scripts placed in other files). Here's a simplified example of how that injection looks (a little snippet from my code): 'injections': [ { 'location': 'head', 'code': 'initGoogleAnalytics()' }, ] Now, I want to do something similar for the chat script—essentially wrap the Django template snippet in a function like initChatScript() and then call this function only after cookie consent is granted. However, I'm not sure how to dynamically include and execute this Django template code within the JavaScript function. I've … -
Django update form sending additional field using AJAX
I have Django ModelForm contains Select2 field. I'm using jquery to send AJAX request on backend depends on select2 field choosen and return updated form with additional fields replacing the previous one (same form class but with additinal kwargs). But this causes init problems with select2 as looks like updating the form "resets" event listener on that select2. Is there a way to send not whole form but particular fields as a response for further append on existing form? -
Overriding DRF ListAPIView list() method
I have a DRF Project, wich has a ListAPIView for a model called Category. This model, has a ForeginKey to itself named parent_category and with related name of subcategories. I want my URLs to behave like this: get a list of Categories with no parent: example.com/api/categories get a list of subcategories of an object with some id: example.com/api/categories/{id_here} models.py: class Category(models.Model): name = models.CharField(max_length=100) parent_category = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE, related_name='subcategories') views.py: class CategoryList(generics.ListAPIView): queryset = Category.objects.all() serializer_class = CategorySerializer And I have no idea how to write my urls.py. Do I need DRF routers? or Django path works fine? I don't know which to choose or how to use them for this project. I thought if i override ListAPIMixin's list() method, it would work, but I don't even know what to write in that.