Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError "Cannot filter a query once a slice has been taken." while running self.client.get(reverse()) function in django
I'm currently learning some basics of django using tutorials in documentation (https://docs.djangoproject.com/en/4.2/intro/tutorial05/) and have a problem with chapter about testing. class QuestionDetailViewTests(TestCase): def test_past_question(self): question = create_question('text', -30) response = self.client.get(reverse('polls:detail', args=(question.id,))) self.assertContains(response, question.question_text) create_question is just a shortcut for creating Question(models.Model) object with second argument meaning offset in days for publication date, which is set relatively to current date. 'polls:detail' is the name of path to this concrete view, which takes number of question as argument. Running of py manage.py test app results in following error: Traceback (most recent call last): File "C:\web\django\project1\mysite\polls\tests.py", line 59, in test_past_question response = self.client.get(reverse('polls:detail', args=(question.id,))) File "C:\web\django\project1\lib\site-packages\django\test\client.py", line 927, in get response = super().get(path, data=data, secure=secure, headers=headers, **extra) File "C:\web\django\project1\lib\site-packages\django\test\client.py", line 457, in get return self.generic( File "C:\web\django\project1\lib\site-packages\django\test\client.py", line 609, in generic return self.request(**r) File "C:\web\django\project1\lib\site-packages\django\test\client.py", line 891, in request self.check_exception(response) File "C:\web\django\project1\lib\site-packages\django\test\client.py", line 738, in check_exception raise exc_value File "C:\web\django\project1\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\web\django\project1\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\web\django\project1\lib\site-packages\django\views\generic\base.py", line 104, in view return self.dispatch(request, *args, **kwargs) File "C:\web\django\project1\lib\site-packages\django\views\generic\base.py", line 143, in dispatch return handler(request, *args, **kwargs) File "C:\web\django\project1\lib\site-packages\django\views\generic\detail.py", line 108, in get self.object = self.get_object() File "C:\web\django\project1\lib\site-packages\django\views\generic\detail.py", line 37, in … -
Django's Success messages displayed like error messages
I'm working on a Django project and I'm using Django's built-in messaging framework to display success and error messages to the user. However, I'm encountering an issue where success messages are being displayed in a way that makes them look like error messages.error messages displyed like success messages here is my Html code: {% if messages %} {% for message in messages %} {% if message.tags == 'success' %} <div class="rounded border-s-4 mb-1 border-green-500 bg-emerald-50 p-4"> <strong class="block font-medium text-green-800"> Successfully </strong> <p class="mt-2 text-sm text-green-700"> {{ message }} </p> </div> {% else%} <div class="rounded border-s-4 mb-1 border-red-500 bg-red-50 p-4"> <strong class="block font-medium text-red-800"> Something went wrong </strong> <p class="mt-2 text-sm text-red-700"> {{ message }} </p> </div> {% endif %} {% endfor %} {% endif %} here is example enter image description here -
python django linebot can receive http response but the code did not work
I'm building a game linebot, using ngrok to build the server. I've tried echo linebot, and it worked well. Now, i'm trying to put a game code on it, but it does not work. Below it's my code. Any advise or keyword would be helpful. If needing more information, please comment below. Thanks all!!! Btw, this game is that guessing a 4 digit number. If a number in "guess" is right and at the right place, you will get 1A. If a number in "guess" is right but not the right place, you will get 1B. For example, if the answer is '1234'. When guessing 5678, the code will response '0A0B'. When guessing 1567, the code will response '1A0B'. When guessing 5167, you will get '0A1B' module version: django 4.1 line-bot-sdk 3.4.0 python 3.11.4 # views.py from django.shortcuts import render # Create your views here. from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from linebot import LineBotApi, WebhookHandler from linebot.exceptions import InvalidSignatureError from linebot.models import MessageEvent, TextMessage import random line_bot_api = LineBotApi('YOUR_CHANNEL_ACCESS_TOKEN') handler = WebhookHandler('YOUR_CHANNEL_SECRET') @csrf_exempt def callback(request): if request.method == 'POST': signature = request.headers['X-Line-Signature'] body = request.body.decode('utf-8') try: handler.handle(body, signature) except InvalidSignatureError: return JsonResponse({'status': 'error', 'message': 'Invalid signature'}) return … -
What are you doing
Because someone asked me what yo do for living I am doing as software engineer but i gols are not in path so give me suggestions for python Django Devloper please ping me when you are free give me some career in python Django Devloper please drop me a massage therapy for the next time hai be bahot hi hai ki nhi hot mnun tu hi to hai na tera -
Wagtail: custom URLs for blog page categories?
My blog pages have a type and a subtype. I want blog page URLs to look like mysite.com/pages/<blog_type>/<blog_subtype>/<blog_title> By default, they are just mysite.com/pages/<blog_title> I can't think of a way to do this (I'm new to Wagtail). Can anyone help? Thanks in advance -
Django Deployment with Gunicorn
Sep 9 05:57:41 PM [2023-09-09 22:57:41 +0000] [52] [INFO] Starting gunicorn 20.1.0 Sep 9 05:57:41 PM [2023-09-09 22:57:41 +0000] [52] [INFO] Listening at: http://0.0.0.0:10000 (52) Sep 9 05:57:42 PM [2023-09-09 22:57:42 +0000] [52] [INFO] Using worker: sync Sep 9 05:57:42 PM [2023-09-09 22:57:42 +0000] [53] [INFO] Booting worker with pid: 53 Sep 9 05:57:42 PM [2023-09-09 22:57:42 +0000] [54] [INFO] Booting worker with pid: 54 Sep 9 05:57:42 PM [2023-09-09 22:57:42 +0000] [55] [INFO] Booting worker with pid: 55 Sep 9 05:57:42 PM [2023-09-09 22:57:42 +0000] [56] [INFO] Booting worker with pid: 56 Sep 9 06:08:06 PM [2023-09-09 23:08:06 +0000] [52] [INFO] Handling signal: term Sep 9 06:08:06 PM [2023-09-09 23:08:06 +0000] [53] [INFO] Worker exiting (pid: 53) Sep 9 06:08:06 PM [2023-09-09 23:08:06 +0000] [54] [INFO] Worker exiting (pid: 54) Sep 9 06:08:06 PM [2023-09-09 23:08:06 +0000] [55] [INFO] Worker exiting (pid: 55) Sep 9 06:08:06 PM [2023-09-09 23:08:06 +0000] [56] [INFO] Worker exiting (pid: 56) Sep 9 06:08:12 PM [2023-09-09 23:08:12 +0000] [52] [INFO] Shutting down: Master Worker keeps exitting without logs. gunicorn wsgi:application is my build command. The app is in the root of the directory, where gunicorn launches from Attempted debugging by adding flags to gunicorn, … -
Django - Product title not showing in cart page
I'm having trouble getting the product title to show in the cart page after its added to cart. It shows everything except the Title of the product. cart.py def __len__(self): return sum(item["qty"] for item in self.cart.values()) def __iter__(self): product_ids = self.cart.keys() products = Product.objects.filter(id__in=product_ids) cart = self.cart.copy() for product in products: cart[str(product.id)]["product"] = product for item in cart.values(): item["price"] = Decimal(item["price"]) item["total_price"] = item["price"] * item["qty"] yield item cart.py def front_page(request): cart = Cart(request) return render(request, 'cart/front_page.html', { 'cart':cart }) cart_details.html This is all the issue starts, it shows everything else like qty and price for each added item but not the product name. {% for item in cart %} {% with product=item.product %} <div class="" data-index="{{product.id}}"> <div class="row g-0"> <div class="col-md-2 d-none d-md-block"> {% for image in product.product_image.all %} {% if image.is_feature%} <img class="img-fluid" alt="Responsive image" src="{{ image.image.url }}" alt="{{ image.image.alt_text }}"> {% endif %} {% endfor %} </div> <div class="col-md-10 ps-md-3"> <div class="card-body p-1"> <a class="" href="{{item.product.get_absolute_url}}"> <p class="card-text pb-3">{{product.title}}</p> </a> <label for="select">Qty</label> <select id="select{{product.id}}" style="width:50px;height:31px;"> <option value="" selected disabled hidden>{{item.qty}}</option> <option value="">1</option> <option value="">2</option> <option value="">3</option> <option value="">4</option> </select> <a type="button" id="update-button" data-index="{{product.id}}" class="update-button text-decoration-none small ps-3">Update</a> <a type="button" id="delete-button" data-index="{{product.id}}" class="delete-button text-decoration-none small">Delete</a> </div> </div> </div> … -
How to add a bullet point in a form in Javascript?
I have a javascript code inside a form, This javascript is supposed to put a bullet point to the previous line, every time that I press the 'enter' key. However, when I do press the enter key it does put the bullet point, but when I press the enter key again, an additional bullet appears. For instance, I have line 1, line 2, and line 3. When I type line one and press enter, a bullet appears behind line one, but when I type line 2 and press enter, line one suddenly has 2 bullets behind it and line 2 has a bullet added to it. This is the code: // Function to format the "roles" textarea into bullet points document.addEventListener('keydown', function (e) { if (e.target.id === 'id_form-0-roles' && e.keyCode === 13) { formatRoles(e.target); e.preventDefault(); } }); function formatRoles(textarea) { let lines = textarea.value.split('\n'); let formattedText = ''; lines.forEach(function (line) { if (line.trim() !== '') { formattedText += '• ' + line.trim() + '\n'; } else { formattedText += '\n'; // Add a new line for empty lines } }); textarea.value = formattedText; } </script> I expect the javascript to put just one bullet point in the preceding line after … -
Is there a best practice to avoid Django's "Found another file with the destination path" during collectstatic on production?
So I'm using Django 4.2, with Django-JET admin package via Django-jet-reboot fork; it enhances Admin with nice functionality and UX. Each time I deploy my app on production, it feels its taking much longer when it reach collectstatic command cause it throws Found another file with the destination path warnings. Now it seems it's related to Django-Jet's css & js files that needs to override django.contrib.admin ones, so my two questions are: Is this harmless and working as designed for my use-case? or there is a better practice to handle this? (like specifically configuring not looking for those django files? or add them to local static folder?) Will adding additional UI-changing package(s) be ok with this? For example I'm looking at creative tims' Black Dashboard Django - I just manage on it's priority in INSTALLED_APPS and let it be? = after jet so it doesn't override that package but takes the additional ones. Issue Details Found another file with the destination path 'admin/css/base.css'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path. Found another file with the destination path 'admin/css/changelists.css'. It … -
error in vercel deployment of django project
Error: Command failed: pip3.9 install --disable-pip-version-check --target . --upgrade -r /vercel/path0/requirements.txt ERROR: Could not find a version that satisfies the requirement pywin32 (from versions: none) ERROR: No matching distribution found for pywin32 where i am going wrong -
How can I create a Django Model for Funds Transfer in a Banking Application
I'm a Django developer with a project to create a banking application. One of the biggest problems is fund transfers between users. To achieve this, I need to design a Django model that includes both a sender and a receiver for fund transfers so that when the sender sends the funds, it will update the receiver's 'account_balance' field in the 'account' model. How can I create a 'Transfer' model that includes a sender and a receiver in one model, and how can I differentiate between the sender and receiver when making fund transfers in the 'views.py' file? my models: class Account(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) account_number = models.IntegerField() account_balance = models.DecimalField(max_digits=12, decimal_places=6) class CustomUser(AbstractUser): username = models.CharField(max_length=30) full_name = models.CharField(max_length=100) phone_number = models.CharField(max_length=16) address = models.CharField(max_length=200) date_of_birth = models.DateField(blank=True, null=True) gender = models.CharField(max_length=20, choices=GENDER) email = models.EmailField(_("email address"), unique=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = ['username'] objects = CustomUserManager() def __str__(self): return str(self.username) Can you please provide a detailed breakdown of the key components this model should have, including fields, relationships, and any security measures or transaction management techniques I should implement? -
Django page not found although everything seems okay
I am new to Django and I am doing everything that is indicated in Django documentation but I can not figure out why it keeps saying Page Not Found I tried changing the path or Debug=True to Debug=False but nothing interesting happened. It once worked but now it keeps saying Page Not Found. from django.urls import path from . import views urlpatterns = [ path("mainpage/", views.index, name="index"), ] this is urls.py mainpage from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("My first page") this is views.py mainpage from django.contrib import admin from django.urls import path from django.contrib import admin from django.urls import include, path urlpatterns = [ path("mainpage/", include("mainpage.urls")), path('admin/', admin.site.urls), ] ```and this one is urls.py mysite this is the result: Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: mainpage/ mainpage/ [name='mainpage'] admin/ The current path, mainpage/, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. http://127.0.0.1:8000/mainpage/ -
Django and docker-compose serving with NGINX: file not found
I've been trying to set up my django project with gunicorn and nginx. The server runs, but I've been struggling to get the admin page to serve static files (I haven't created any other static files for the project, so I'm just starting with admin). I bit the bullet and just copied the original django admin static file into my own project, but when I load the admin page, there are no static files. My docker "web" image shows: web_image_name | Not Found: /static/admin/js/... web_image_name | Not Found: /static/admin/css/... ... This error is interesting, since when I go into that image's terminal and do "ls", I can see the static directory. Is this problem related to nginx, docker, or both? Code: nginx.conf: # nginx.conf events { worker_connections 1024; } http { server { listen 80; server_name your_domain.com; # Change to your domain or IP address location / { proxy_pass http://web:8000; # Points to your Gunicorn service proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location /static/ { alias /app/static/; } } } docker-compose.yml (truncated): version: "3" services: web: container_name: newspigeon_web build: context: . dockerfile: Dockerfile command: > bash -c "python manage.py migrate && gunicorn --workers=4 --bind=0.0.0.0:8000 newspigeon.wsgi:application" ports: … -
django allauth github organizations restriction
i have created a Django webapp, and i want to use allauth to create a sso for github. I have set it up, and it works fine. But now all github users can login to my webapp. I want to restrict it only to my github organization. So that all users of my organization can login to the web app and users which are not in the organization cant login. Is there any option from allauth to realize this? i have checked the allauth documentation, but i can't find any option for that. Or is there any other way which i can use to realize my requirement? -
Django Admin Display Problem (TabularInline)
as you see in the photos "Member" table is too long , there is a one to one relation between User and Member. this is the admin.py code class MemberInLine(admin.TabularInline): model = Member class UserAdmin(admin.ModelAdmin): list_display = ('username','is_active', 'is_staff','is_superuser') list_filter = ('is_active', 'is_staff') search_fields = ("username",) ordering = ('username',) filter_horizontal = () filter_vertical = () fieldsets = () inlines=[ MemberInLine, ] admin.site.register(User,UserAdmin) -
Trouble getting past CORS error in Django
I'm getting a CORS error whilst trying to use React with Django and postgresql. I have tried many ways to configure the CORS settings in Django however nothing seems to work. When I made a simple route that passes "Hi" it works. So I am not sure if there is an error with my view or something is wrong with the front end at React. I have also ensured that the VITE_SERVER is correct by console logging it and that my endpoints used are accurate. This are my Django settings: ALLOWED_HOSTS = [] CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_HEADERS = [ 'content-type', 'authorization', ] CORS_ALLOWED_ALL_ORIGINS = True ALLOWED_HOSTS = [ "127.0.0.1", ] CSRF_TRUSTED_ORIGINS = ["http://127.0.0.1:8000/"] AUTH_USER_MODEL = 'customers.CustomerAccount' # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'customers', 'dealer', 'restful_apis', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", "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", ] This is my fetch hook that I used: import React from "react"; const useFetch = () => { const fetchData = async (endpoint, method, body, token) => { const res = await fetch(import.meta.env.VITE_SERVER + endpoint, { // mode: "no-cors", method, headers: { "Content-Type": "application/json", Authorization: "Bearer … -
How to change the year range of datepicker in django jalali date?
In my Django project, I am looking to get users birth dates. For this purpose, I used a django-jalali-date and jdatetime packages. Currently, the user has access to 10 years before and 10 years after today's date and can picker. I am looking for it to display only 100 years before the current date. model: class Student(models.Model): birthday_date = models.DateField(null=True) form: class StudentForm(forms.ModelForm): birthday_date = JalaliDateField(widget=AdminJalaliDateWidget) class Meta: model = Student fields = ( 'birthday_date', ) template: {% load jalali_tags %} {% 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>Success singup</title> </head> <body> {% comment %} <p>{{ request.user.date_joined|to_jalali:'%y/%m/%d _ %H:%M:%S' }}</p> {% endcomment %} <form method="post" action="{% url 'accounts:student_success_signup' pk=pk %}"> {% csrf_token %} {{ customuser_form.as_p }} {{ student_form.as_p }} {{ phonenumber_form.as_p }} <button type="submit">Submit</button> </form> <!-- By default, Datepicker using jQuery, you need to set your script after loading jQuery! --> <!-- loading directly --> <link rel="stylesheet" href="{% static 'admin/jquery.ui.datepicker.jalali/themes/base/jquery-ui.min.css' %}"> <script src="{% static 'admin/js/django_jalali.min.js' %}"></script> <!-- OR --> <!-- loading by form (if used AdminJalaliDateWidget) --> {{ form.media }} </body> </html> AdminJalaliDateWidget: class AdminJalaliDateWidget(AdminDateWidget): @property def media(self): js = settings.JALALI_DATE_DEFAULTS['Static']['js'] css = settings.JALALI_DATE_DEFAULTS['Static']['css'] return forms.Media(js=[static(path) for path in … -
Designing a Secure and Efficient Django Model for Money Transactions
I'm worki on Django application that involves sending and receiving money between users. I want to ensure that my database model is designed efficiently and securely to handle these transactions. What are the best practices and considerations I should keep in mind when designing the Django model for managing money transfers? Are there any specific patterns that can help with this? I'm particularly interested in: Ensuring the security and integrity of financial transactions. Handling different types of transactions (e.g., transfers between users, deposits, withdrawals). The best practices for structuring the database model to track money transactions accurately? Any insights or code examples would be greatly appreciated. -
Which Relationship between Django Models
I'm trying to code a DB based web app with Python/Django and I have some issues figuring out which is the best approach for my purpose, so I'll try to explain myself the best way possible. The DB stores objects that represent a videogame PG's Armor Pieces. Every piece has some positive/negative abilities scores: wearing a complete Armor set (Helmet, Jacket etc..), the scores for each ability sum up and can give different effects. So, every armor piece can have different abilities, and each Ability can be shared between several Armor Pieces, but the scores for each Ability may be different for different Armor Pieces. Once finished, this app should be able to find - if possible - a complete ArmorSet composed of 5 ArmorPiece which have the PieceAbility.scores necessary to activate one or more Effects the user would like. from django.db import models class Ability(models.Model): name = models.CharField(max_length=20) def __str__(self) -> str: return self.name class ArmorSetPart(models.Model): part = models.CharField(max_length=10) def __str__(self) -> str: return self.part class WeaponClass(models.Model): type = models.CharField(max_length=20) def __str__(self) -> str: return self.type class Rank(models.Model): rank = models.CharField(max_length=10) def __str__(self) -> str: return self.rank class PieceAbility(models.Model): name = models.ForeignKey(Ability, related_name='pieces', on_delete=models.CASCADE) score = models.IntegerField(default=0, ) def … -
Issue with Loading and Sorting Comments Using JavaScript (FETCH API) and Django
I'm working on a blog using Django and JavaScript, where users can submit and view comments on a post. I have implemented a functionality to sort these comments based on "newest", "Most liked", and "oldest" using a dropdown menu. Additionally, I've added a "Load more comments" button to paginate the comments. When the page initially loads, the first ten comments are displayed, which is what i want. When a user clicks on the "load more comments" button, i want the next batch of ten comments to be displayed underneath, and so on until there is no more comment to be displayed, at which point the "Load more comments" button is hidden. However, I'm facing some issues, and they are - After clicking the "Load more comments" button, the initial set of comments is replaced by the next set of comments. Instead, I want the new comments to be appended below the existing ones. The intended behaviour of the "Load more comments" button is only achieved AFTER changing the sorting option back and forth. What I mean is that after initially loading up the page, the "load more comments" button when clicked, replaces the 10 existing displayed comments with the next … -
python data formatting in Django
I get this flow of data from database. but I couldn't figure out how to format it. this is how I want it; This is how it is. [{'date': datetime.date(2023, 5, 27), 'pnl': '69'}, {'date': datetime.date(2023, 7, 23), 'pnl': '81'}, {'date': datetime.date(2023, 9, 12), 'pnl': '67'} ] This is how I want it [[69, 27, 5, 2023],[81, 23, 7, 2023],[67, 12, 9, 2023]] [0] = pnl, [1] = date, [2] = month, [3] = year -
Axios instance does not attach Authorization header in GET requests despite attaching it in POST requests
I use axios to call my API(Django server) from a react website, I want an authorization header with a Bearer token to be present in every request in the authorization header. This is how I set the authorization header apiClient.defaults.headers.common['Authorization'] = Bearer ${token}; When I call my api with a post request: const response = await apiClient.post('posts/', payload); It works as expected, the authorization token is present in the request. However whenever I call any GET request: apiClient.get(posts/${router.query.id}/), I see no Authorization header in the requests header in the network tab of the browser. I verified that it is the same axios instance and that it is not an issue of an incorrect request. I also noticed that before each POST request an OPTIONS request is being sent, perhaps it is somehow telling axios to attach authorization header? Thank you in advance, if needed I can attach also the code in the backend responsible for the API endpoints. -
error while running the codeException in thread django-main-thread Traceback
Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner self.run() File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\commands\runserver.py", line 133, in inner_run self.check(display_num_errors=True) File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\base.py", line 485, in check all_issues = checks.run_checks( ^^^^^^^^^^^^^^^^^^ File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\checks\urls.py", line 42, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\checks\urls.py", line 72, in _load_all_namespaces namespaces.extend(_load_all_namespaces(pattern, current)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\checks\urls.py", line 72, in _load_all_namespaces namespaces.extend(_load_all_namespaces(pattern, current)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\checks\urls.py", line 72, in _load_all_namespaces namespaces.extend(_load_all_namespaces(pattern, current)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [Previous line repeated 988 more times] File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\checks\urls.py", line 62, in _load_all_namespaces namespaces = [ ^ RecursionError: maximum recursion depth exceeded can anyone tell ma what can I do to solve it -
I am using Railway to host my Django project, but the static files do not load even after correctly configuring the directories in settings.py
I have correctly configured the path of static urls in settings.py but Railway keeps displaying my pages without any CSS. I don't have any other pages other than the admin panel and rest framework pages because it is just a backend project. Usually (according to all tutorials I watched), running python manage.py collectstatic after correctly configuring the paths in settings.py is enough to make Railway detect staticfiles and use them in deployment. I did and it is successfully deploying my project but logs that it couldn't find all of my static files hence displaying plain HTML. Here's the Static URLs configuration: STATIC_URL = '/static/' STATIC_ROOT =os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] -
Django query by parent id without join
Let's say I've two models Parent and Child related by foreign key want to query all children without making a join with the parent table will Child.objects.filter( parent_id=parent_id ) do the trick? notice I'm doing a single underscore instead of double, so in theory it should only look through parent_id column in child table instead of making the joins, right?