Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can not get group permissions by custom User and Group
I create my custom user and group as below: models.py (myusers app) ` from django.db import models from django.contrib.auth.models import AbstractUser, GroupManager, Permission class AbstractGroup(models.Model): name = models.CharField(_("name"), max_length=150, unique=True) permissions = models.ManyToManyField( Permission, verbose_name=_("permissions"), blank=True, related_name="fk_group_permission", ) objects = GroupManager() def __str__(self): return self.name def natural_key(self): return (self.name,) class Meta: verbose_name = _("group") verbose_name_plural = _("groups") abstract = True class Group(AbstractGroup): is_active = models.BooleanField(_("Is Active"), default=True) class User(AbstractUser): groups = models.ManyToManyField( Group, verbose_name=_("groups"), blank=True, help_text=_( "The groups this user belongs to. A user will get all permissions " "granted to each of their groups." ), related_name="user_set", related_query_name="user", ) ` and point in settings.py: AUTH_USER_MODEL=myusers.User AUTH_GROUP_MODEL=myusers.Group All is ok but when get group permissions (a_user.get_all_permissions() or a_user.get_group_permissions()) raise error: ValueError: Cannot query “a_user”: Must be “Group” instance. (a_user here is the user user instance) what is wrong? The get_group_permissions() return error. -
retrieving media files on render with django
Hopefully a simple issue that I cannot find any answer to online so far. Background : I have an django web app that is hosted on render.com. Everything is working apart from the media files that are hosted on a bought disk (mounted at /var/data) for my project. I have followed the documentation and added the following to settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = '/var/data' media context is set: "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", "django.template.context_processors.media", ], I have urlpatterns configured for media: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) whitenoise is configured: STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' requirements.txt asgiref==3.8.1 click==8.1.8 dj-database-url==2.3.0 Django==5.1.4 django-crispy-forms==2.3 gunicorn==23.0.0 h11==0.14.0 packaging==24.2 pillow==11.0.0 psycopg2-binary==2.9.10 sqlparse==0.5.3 typing_extensions==4.12.2 uvicorn==0.34.0 whitenoise==6.8.2 index.html {% extends "airfryer_app/base.html" %} {% block body %} <div class="product-container flex flex-wrap justify-content-center"> {% for recipe in recipes %} <div class="product shadow-lg w-1/5 rounded-lg m-10"> <div class="product-image"> <img src="{{ recipe.image.url }}" alt=""> </div> <div class="p-5"> <div class="font-bold"> {{ recipe.name }} </div> <div> {{ recipe.description }} </div> <div class="text-orange-700 font-bold text-orange"> {{ recipe.time }} minutes </div> <div class="mt-5"> <a class="bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded" href="{% url 'recipe' recipe.id %}">View Details</a> </div> </div> </div> {% if forloop.counter|divisibleby:3 %} <div class="w-full"></div> {% endif %} {% endfor %} </div> {% endblock %} Using … -
How to reuse mysql persistant connection in uwsgi + django + multi threading?
My Env: DJANGO 4.1 UWSGI 2.0.26 processes + gevent mode And I Use concurrent.futures.ThreadPoolExecutor as my thread pool I know that django mysql connecition is thread local. If I create thread pool in request thread, then pool thread id is different in each request so mysql connection is not reused.But if I create thread pool in uwsgi processes,the connection cannot be recycled after request finished and it will throw "Mysql server has gone away" afeter a few time. So how to reuse mysql connection correctly in my run env? -
Django REST + API Gateway CORS Issue with Cognito Authentication
I have issues with CORS, most likely due to Frontend (Amplify) being https and backend (ElasticBeanstalk) being http. Tried to fix unsuccessfully with API Gateway. Frontend: React app hosted on AWS Amplify Backend: Django REST framework on Elastic Beanstalk Authentication: AWS Cognito API Gateway as proxy between frontend and backend Issue: Getting CORS error when frontend tries to access backend through API Gateway. With Chrome CORS disabled, the request reaches backend but fails with Django auth error. Frontend (React/TypeScript): const fetchVideos = async () => { const session = await fetchAuthSession(); const token = session.tokens?.idToken?.toString(); // Token looks valid: eyJraWQiOiJxTHpReFZa... const fullUrl = `${BASE_URL}/api/premium-content`; const response = await fetch(fullUrl, { method: 'GET', credentials: 'include', headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json', } }); } Django Settings (base.py): CORS_ALLOWED_ORIGINS = [ "https://my-frontend.amplifyapp.com", "http://localhost:5173", "http://localhost:3000" ] CORS_ALLOW_CREDENTIALS = True API Gateway Configuration ANY method: HTTP Proxy integration to EB endpoint OPTIONS method: Mock integration with headers: Access-Control-Allow-Origin: 'https://my-frontend.amplifyapp.com' Access-Control-Allow-Methods: 'GET,OPTIONS' Access-Control-Allow-Headers: 'Content-Type,Authorization' Access-Control-Allow-Credentials: 'true' Gateway responses: 4XX and 5XX enabled for CORS Seeing the error message in the console log: Access to fetch at 'https://[api-gateway-url]/prod/api/premium-content' from origin 'https://my-frontend.amplifyapp.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control … -
font Tag issue in summer note
<font style="background-color: rgb(255, 255, 0);" color="#ff0000">Write something</font> Above tag generated by Summernote; the color property came outside of the style attribute. How can I fix this issue?" anyone found same problem that iam facing if you found let me know it will help me lot -
Why does Auth0 use /login/callback instead of my configured callback URL in the redirect to Azure AD?
I am implementing Okta - Auth0 with Azure Active Directory (Azure AD) as the identity provider (IdP) in my Django project. Here's a breakdown of my setup: Django OAuth Configuration: Callback URL in Django: https://mydomain/api/auth/callback/. My Django app redirects users to the Auth0 /authorize endpoint with the correct redirect_uri. Auth0 Application Settings: Allowed Login URLs: https://mydomain/api/auth/login/. Allowed Callback URLs: https://mydomain/api/auth/callback/. Allowed Logout URLs: https://mydomain/api/auth/logout/. Azure AD Application Settings: Redirect URI: https://mydomain/api/auth/callback/. Problem: When I delete the default callback (https://dev-xxxxx.ca.auth0.com/login/callback) from Azure AD, the login process fails with the following error from Azure AD: AADSTS50011: The redirect URI 'https://xxxxxxca.auth0.com/login/callback' specified in the request does not match the redirect URIs configured for the application. However, I have not included the okta default /login/callback in my Auth0 configuration. I only use /api/auth/callback/. The flow seems to depend on this default callback URL, even though I expect Auth0 to use my configured callback (/api/auth/callback/) throughout the login flow. Questions: Why does Auth0 internally use https://dev-xxxxxx.ca.auth0.com/login/callback instead of the configured callback URL (/api/auth/callback/) when redirecting to Azure AD? How can I eliminate the dependency on the default callback (/login/callback) and ensure the entire flow uses my custom callback (/api/auth/callback/)? Steps I’ve Tried: Ensured https://mydomain/api/auth/callback/ is … -
Switching Django USE_TZ to True
I have a site which is pretty old (started at Django 1.6) but has been upgraded over time and is now at Django 4.2. It has always had USE_TZ=False and TIME_ZONE='America/Chicago'. We have a lot of critical dates (subscriptions, purchase records, etc), many of which are fed from external webhooks from our payment processor. I'm looking at adding another Django app, but it requires USE_TZ=True. Anyone have any insight into what might happen if I turn it on? I've turned it on in my development environment and I don't see any obvious issues, but can't easily replicate the webhooks I receive and daily tasks that extensively use date calculations. Where should I be looking for issues? -
убрать надпись в регистрации This field is required [closed]
Я использую встроенную в джанго форму UserCreationForm для создания формы регистрации, но есть лишние предписания 'This field is required.' о том что эти поля обязательны, я хочу убрать их, помогите пожалуйста, ну или хотя бы перевести на русский что-б надпись была на русском, если так же сможете помочь исправить clean_email в формах так что б он не всегда выкидывал эту надпись после 1 тестового ввода существующего email вот скрин результата enter image description here views.py: class RegisterUser(CreateView): form_class = RegisterUserForm template_name = 'users/register.html' extra_context = {'title': 'Регистрация'} success_url = reverse_lazy('users:login') forms.py: class RegisterUserForm(UserCreationForm): username = forms.CharField(label="Логин:", widget=forms.TextInput(attrs={'class': "form-input"})) password1 = forms.CharField(label="Пароль:", widget=forms.PasswordInput(attrs={'class': "form-input"})) password2 = forms.CharField(label="Повтор пароля:", widget=forms.PasswordInput(attrs={'class': "form-input"})) class Meta: model = get_user_model() fields = {'username', 'email', 'first_name', 'last_name', 'password1', 'password2'} labels = { 'username': 'Логин', 'email': 'E-mail', 'first_name': 'Имя', 'last_name': 'Фамилия', 'password1': 'Пароль', 'password2': 'Повторить пароль', } widgets = { 'username': forms.TextInput(attrs={'class': "form-input"}), 'first_name': forms.TextInput(attrs={'class': "form-input"}), 'last_name': forms.TextInput(attrs={'class': "form-input"}), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.order_fields(['username', 'email', 'first_name', 'last_name', 'password1', 'password2']) def clean_email(self): email = self.cleaned_data['email'] if get_user_model().objects.filter(email=email).exists(): raise forms.ValidationError("Такой E-mail уже существует") return email users/register.html: {% extends 'users/base.html' %} {% block title %}Регистрация{% endblock %} {% block content %} <h1>Регистрация</h1> <form method="post"> {% csrf_token %} {{ … -
Wagtail - add custom link option
I would like to customize External link type in Wagtail links in admin RichText field - I need to change (or at least disable) the link validation (e.g., to my custom regex) in admin frontend, as my links have different format to https://<something>. Does anybody know how to do that without forking wagtail and making own addition in this and this file? Any help would be appreciated. -
How can I override settings for code ran in urls.py while unit testing django
my django app has a env var DEMO which, among other thing, dictate what endpoints are declared in my urls.py file. I want to unit tests these endpoints, I've tried django.test.override_settings but I've found that urls.py is ran only once and not once per unit test. My code look like this: # settings.py DEMO = os.environ.get("DEMO", "false") == "true" # urls.py print(f"urls.py: DEMO = {settings.DEMO}") if settings.DEMO: urlpatterns += [ # path('my_demo_endpoint/',MyDemoAPIView.as_view(),name="my-demo-view") ] # test.test_my_demo_endpoint.py class MyDemoEndpointTestCase(TestCase): @override_settings(DEMO=True) def test_endpoint_is_reachable_with_demo_equals_true(self): print(f"test_endpoint_is_reachable_with_demo_equals_true: DEMO = {settings.DEMO}") response = self.client.get("/my_demo_endpoint/") # this fails with 404 self.assertEqual(response.status_code, 200) @override_settings(DEMO=False) def test_endpoint_is_not_reachable_with_demo_equals_false(self): print(f"test_endpoint_is_not_reachable_with_demo_equals_false: DEMO = {settings.DEMO}") response = self.client.get("/my_demo_endpoint/") self.assertEqual(response.status_code, 404) when running this I get: urls.py: DEMO = False test_endpoint_is_reachable_with_demo_equals_true: DEMO = True <test fails with 404> test_endpoint_is_not_reachable_with_demo_equals_false: DEMO = False <test succeed> urls.py is ran only once before every test, however I want to test different behavious of urls.py depending on settings Using a different settings file for testing is not a solution because different tests requires different settings. Directly calling my view in the unit test means that the urls.py code stays uncovered and its behaviour untested so this is also not what I want. How can I override settings for code … -
Add buttom from admin panel to ModelForm in Django
In the admin panel of a django app when you are adding a database entry that links data from another table on a foreign key you get a dropdown to select the entry and 3 buttons to edit, add or view an entry like this: However when you create a form for this model to take data from a user, the linked data only shows the dropdown menu and no buttons: Is there any way that I can add the 'add' and 'view' button on the input form so that the user can view an entry in more detail if unsure or add a new entry if the required information is not already in the database? It seems like it should be pretty simple if the functionality is already there for admin panel and would be neater than implementing some custom pages to load the data for viewing or redirecting to another form to add the new data? -
How to properly configure python path in Microsoft Dev Containers?
I have configured Microsoft Dev Containers for a Django project but I'm not able to properly set the python path since vscode is raising an error regarding a package that it is not able to find (i.e. Import "django.contrib.auth.models" could not be resolved from sourcePylancereportMissingModuleSource) and it is installed in the venv within my dev container. My approach has been to declare a variable in devcontainer.json but it has not worked since the warning is still appearing: "customizations": { // Configure properties specific to VS Code. "vscode": { "settings": { "python.pythonPath": "/opt/venv/bin/python3.11" } } } Any suggestion about how to fix this warning? -
After switching to postgresql - connection reset by peer
According to this tutorial I switched to postgresql code. # django_project/settings.py DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": "postgres", "USER": "postgres", "PASSWORD": "postgres", "HOST": "db", # set in docker-compose.yml "PORT": 5432, # default postgres port } } Here is docker-compose.yml # docker-compose.yml version: "3.9" services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db db: image: postgres:13 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - "POSTGRES_HOST_AUTH_METHOD=trust" volumes: postgres_data: Everything worked before editing DATABASES section. When I run $ curl 127.0.0.1:8000 curl: (56) Recv failure: Connection reset by peer -
Dynamic type annotation for Django model managers custom method
I need help with type hint for a custom model manager method. This is my custom manager and a base model. I inherit this base model to other models so that I don't have to write common fields again and again. class BaseManager(models.Manager): def get_or_none(self, *args, **kwargs): try: return self.get(*args, **kwargs) except self.model.DoesNotExist: return None class BaseModel(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, verbose_name="ID", editable=False ) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = BaseManager() # Set the custom manager class Meta: abstract = True This is an example model: class MyModel(BaseModel): category = models.CharField(max_length=10) Now for this: my_object = MyModel.objects.get_or_none( category="...", ) The type annotation is like this when I hover in my IDE: my_object: BaseModel | None = MyModel.objects. get_or_none(... But I want the type annotation like this: my_object: MyModel | None = MyModel.objects. get_or_none(... How can I do that? This works for the default methods like get and filter. But how to do this for custom methods like get_or_none? Please help me. Thanks -
Django unit tests suddenly stopped working
My unit tests were working fine, but for the past two days, they have been failing without any apparent reason. No new code additions or major changes have been made, yet they are failing. The same logic is working in other test cases, but for five specific tests, it has started to fail. I tried running the tests by checking out a previous branch where the tests were working fine, but now they have stopped working even under those conditions. I am completely clueless about what to do next. Below is the snippet which was implemented by sr dev, but he left the company two weeks ago. I don’t know this might not be filtering the data or there might be a scenario of overlapping of date for the data that we want to filter. Kindly help. class EntityBestDataSourceChange(models.Model): scope = models.TextField() scope_category = models.TextField() entity_id = models.IntegerField() child_id = models.IntegerField() year = models.IntegerField() source = models.TextField() operation = models.TextField() class Meta: unique_together = [ 'scope', 'scope_category', 'entity_id', 'child_id', 'year', 'source', 'operation'] @classmethod @transaction.atomic def perform_recalculate(cls): ebds_changes = ( EntityBestDataSourceChange.objects .select_for_update(skip_locked=True) .all() ) number_of_changes = len(ebds_changes) additions = set() removals = set() for ch in ebds_changes: key = ( ch.scope, … -
Process the image on the website using Pilgram
I'm completely zero in programming and I'm just trying to take the first steps. I think the solution to my problem is pretty simple, but I can't find it. I want to have 2 fields in the Images model: image and processed_image. I am using Django 5.1.4, Python 3.13.1, Pillow 11.1.0 and Pilgram 1.2.1 I want the user to upload an image to a form on the website. The image was processed using pilgram. And then the processed image was saved in the processed_image field. But when I save the picture, the processed_image field in the database remains empty. Please tell me what my mistake is? postcard/images/models.py from django.db import models from PIL import Image import pilgram import os from django.urls import reverse from django.contrib.auth.models import User from .services.utils import unique_slugify class Images(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user') title = models.CharField('Название', max_length=255) slug = models.SlugField("URL", max_length=255, unique=True, db_index=True) image = models.ImageField('Изображение', upload_to="images/%Y/%m/%d/") processed_image = models.ImageField('Отработанное изображение', upload_to="processed/%Y/%m/%d/", blank=True, null=True) time_create = models.DateTimeField('Дата создания', auto_now_add="True") def __str__(self): return self.title def save(self, *args, **kwargs): super().save(*args, **kwargs) if self.image: self.process_image() def process_image(self): img_path = self.image.path img = Image.open(img_path) img = pilgram._1977(img) processed_path = os.path.join(os.path.dirname(img_path),f"processed_{os.path.basename(img_path)}") img.save(processed_path) self.processed_image = processed_path super().save(update_fields=['processed_image']) class Meta: verbose_name = … -
In the Wagtail admin panel, the person's image is not showing on the blog edit page
I have used a person as an author on the blog page, but when I open the blog edit page, I can only see the text, not the person's image. How can I display the image as well? -
Not able to connect to PostgreSQL database in Linux Fedora via VS Code terminal
So I'm using Linux Fedora. I'm in my current Django project directory. When I dual booted, I did save my postgresql application and saved my database backup with pg_dump onto my removable drive before I booted to Linux. I'm in VS Code, I installed all of the necessary packages/dependencies for my Django project. But before I can run Django server, I have to migrate my models to my db. The problem, is that I'm not able to connect to my postgresql db and I need to do this before I run python manage.py migrate running python manage.py makemigrations CMD works fine. So I'm new to Linux and I just need some help connecting to my db so that I can get my server running. Please keep in mind I'm using Fedora. I was able to install postgresql for Fedora with the following command sudo dnf install postgresql-server postgresql-contribsudo dnf install postgresql-server postgresql-contrib Here is the error I get in the console Is the server running on that host and accepting TCP/IP connections? connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections?` To be clear, I already have … -
Django frontend detect if user is logged in
I use django at backend and html/javascript for frontend. I am looking for a way to know in frontend if the user is logged in. If user is not logged in, upon pressing some buttons, the website shows a login overlay form. By just checking whether sessionid exists in the cookies or not you can find it out. But, the problem is SESSION_COOKIE_HTTPONLY in django settings is True and I do not want to turn it off. Thus, the document.cookies does not include the sesstionid due to security reason. Is there still any way to find the user is logged in without contacting the backend? -
Django queryset with annotate, order_by and distinct raises error when values is called
Can somebody explain to me why the following call works fine Order.objects.filter(part_description__icontains=search_query) .annotate(part_description_lower=Lower('part_description')) .order_by("part_description_lower", '-pk') But the following raises the error Cannot resolve keyword 'part_description_lower' into field Order.objects.filter(part_description__icontains=search_query) .annotate(part_description_lower=Lower('part_description')) .order_by("part_description_lower", '-pk') .values('pk') Thank you in advance. -
How to access submitted form request data in Django
I want value of submitted data in init . I can get data after form.valid() through cleaned_data but can't access those data in init after submitting form form.py class MyForm(forms.Form): def __init__(self, *args, **kwargs): // Want to access submitted source and medium data here super(MyForm, self).__init__(*args, **kwargs) // or Want to access submitted source and medium data here view.py I am getting two different value source and medium in request.GET myform = MyForm(request.GET) -
Why doesn't the Python TimedRotatingFileHandler rollover, if there are Celery jobs running?
Python 3.12.3, Celery 5.3.6, Django 4.2.11, Ubuntu 22.04.4 I have an infrastructure of Django and Celery servers running simultaneously on an Ubuntu server. For logging I use DiscordHandler and customized TimedRotatingFileHandler defined as so: class CustomizedTimedRotatingFileHandler(TimedRotatingFileHandler): ''' log_name.date.log.log -> log_name.date.log ''' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.namer = lambda name: name.replace(".log", "") + ".log" The project logging is configured in the settings file: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { **{ f"{k}_file": { "level": "INFO", "class": "api.logging.CustomizedTimedRotatingFileHandler", "filename": "log/sync.log", "when": "midnight", "backupCount": 2, "formatter": v, } for k, v in {"django": "verbose", "celery": "celery"}.items() } }, 'loggers': { 'django': { 'handlers': ['django_file'], 'level': 'INFO', 'propagate': True, }, 'django.server': { 'handlers': ['django_file'], 'level': 'INFO', 'propagate': False, }, 'celery': { 'handlers': ['celery_file'], 'level': 'INFO', 'propagate': False, } } } Right now I have 2 log files and then a file of today (which gets logs in only from Django, not Celery). I've looked through the discord logs and have seen that there were some celery jobs working at midnight. And this is not the first occurrence, in fact, all the times the case has been that in the midnight there were ongoing tasks, which interrupted the rollover. How do … -
socialaccount + mfa: how to bypass the mfa code form?
on an older version of django-allauth (0.61.1) I used totp for the two-auth. Now I've udpdated to django-allauth[mfa]==65.3.0 and I have an issue by using the socialaccount auth. Before I used a customer AccountAdapter to check if the user coming from a microsoft: class AccountAdapter(DefaultAccountAdapter): def has_2fa_enabled(self, user): """Returns True if the user has 2FA configured.""" return user.has_2fa_enabled if user.is_authenticated else False def login(self, request, user): # Require two-factor authentication if it has been configured. if ( self.has_2fa_enabled(user) and not request.path == "/auth/microsoft/login/callback/" ): redirect_url = reverse("two-factor-authenticate") # Add GET parameters to the URL if they exist. if request.GET: redirect_url += "?" + urlencode(request.GET) raise ImmediateHttpResponse(response=HttpResponseRedirect(redirect_url)) return super().login(request, user) Now, with the new update, the 2FA code is asked AFTER the super().login How can I bypass the MFA code? I've checked the documentation and I see only "is_mfa_enabled" in the DefaultMFAAdapter but this is not nice as it will just say False on is_mfa_enabled but not only change if the app asks the code or not. Is there any other way for that? -
Why is my @import in CSS not working when importing other CSS files?
I'm building a Django project and trying to organize my CSS files by importing them into a single index.css. However, the styles from the imported files are not being applied when I include only index.css in my base.html. Here's what I've done: File Structure: static/ ├── css/ │ ├── index.css │ ├── footer.css │ └── courses/ │ └── courses.css index.css: @import url("footer.css"); @import url("courses/courses.css"); .verticalSpace { padding-top: 100px; } base.html: <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="{% static 'css/index.css' %}"> </head> <body> {% block content %} {% endblock %} </body> </html> Observations: If I directly include footer.css or courses/courses.css in the HTML, the styles work. <link rel="stylesheet" href="{% static 'css/courses/courses.css' %}"> The styles do not work when I rely on @import in index.css. Questions: Why are the imported styles not applying when using @import in index.css? Is there a better way to structure CSS imports in Django to only link index.css in the HTML? Could this issue be related to Django's STATIC_URL or how @import resolves paths? What I've Tried: Checked that static files are correctly set up in settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [BASE_DIR / 'static'] Verified that the CSS files load correctly when linked directly. Tried … -
Circular import in Django
Im getting this error : does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import whenever i try python manage.py runserver app urls.py from django.urls import path from . import views urlpatterns = [ path ('', views.index, name='index'), ] project urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('myapp.urls')), ] app Views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse('<h1> Hello man</h1>') Im using Django 4.1, and Python 3.10.10, I also tried this with python 3.12 and Django 5.1.4, still error persisted. Without this particular line of code below in the parent app, the program runs fine. path('', include('myapp.urls')), but when I include the above line of code I get the following error: "does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import." I tried changing python environments, directories, rewriting the code and trying out in different python and django versions …