How Django search for the module/apps in project folder - django

This question is related to the following questions. How to import urls from apps in django main urls file
Actually I have the following project structure.
I want to ask why I have to use complete path link to point the apps in INSTALLED_APPS or even anywhere in the django files.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'climemanage.clients',
]
Why I can't use just import climemanage.clients (or any other import statement) and use clients in INSTALLED_APPS ?
Same for the urls.py file I have to use the complete path as climemanage.clients.urls the following.
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('clients/', include('climemanage.clients.urls')),
]
Why not just clients.urls? When I try to use just clients.urls it is giving Module not found 'clients'

Because Django does a number of things upon initialization of the project, that require modules to be loaded in a specific order. Importing things in settings would make that complicated as imports already execute code before Django can do anything about it.
Thus, INSTALLED_APPS is a list of strings that use importlib's import_module, to load modules when Django is ready for them to be loaded. This is done in django.apps.config.
If you want to shorten the path, you could add that path to PYTHONPATH environment variable, but think carefully, since the more paths you have in there, the more chances for duplicate names. It's generally not a good investment of time and resources to try and save typing in configuration files as once you're done configuring, you hardly get back to them.

Related

Local server won't go through my URL pattern on my local server

I'm new to Django and I'm facing a problem that I can't solve despit my research... I'v already made small django projects without this error but since I reformat my computer (I can't see the link but that's context!) i'm having this problem.
So when I'm running a django project this is what my browser shows me despite others urls in my project
Django doesn't go trhough my urls
I'v tried with an almost empty project but a least one more url and still have the same page.
urls.py in the main file (src/mynotes/urls.py):
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('index/', include('dbnotes.urls')),
path('admin/', admin.site.urls),
]
settings.py in the main project (src/mynotes/settings.py):
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'dbnotes'
]
urls.py in the app (src/dbnotes/urls.py):
from django.urls import path
from . import views
urlpatterns = [
path("", views.homepage, name="homepage"),
]
views.py in the app (src/dbnotes/views.py):
from django.http import HttpResponse
def homepage(request):
return HttpResponse("Hello, world. You're at the polls index.")
Even stranger, when i change "path('admin/', admin.site.urls)" I still get the admin page with the same route. Even if i change 'admin/' or admin.site.urls.
It looks like my local server display an over empty django project but in the error page it's written "mynotes.urls" as the url location which is the good folder.
I'm working with a virtual environment.
I'm lost as it's the first time i got this issue despite having created ohter (small) django projects!
If anyone has an idea that would be great! Thank you!
The directory:
Directory
I tried to follow the django documentation to write the smaller project and then having less room to error!
I tried with a new project and a new virtual envirnoment.
I found a topic related to my problem but without an anwer : Django doesn't see urls.py

Why is Django is not loading my template view but it once was

My view was running fine until Ill tried to override an admin view. Which i eventually got to work. However in the process I broke the path to my view that was working. The admin view had nothing to do with my originally working view.
Now I copied my view into every possible level of my project structure. Yet the django template loader fails to find my order_input.html
The error shows the correct path to my order_input.html. I made copies of order_input.html at every single possible level of my project... but django still cant find it.
APP - URLS.PY
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^hw/$', views.helloworld, name='helloworld'),
url(r'^order_input/$', views.order_input, name='order_input'),
url(r'^time/$', views.today_is, name='time'),
url(r'^$', views.index, name='index'),
]
SETTINGS.PY
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
# 'django.contrib.staticfiles',
'import_export',
'hw_app',
]
PROJECT URLS.PY
urlpatterns = [
url('r', include('hw_app.urls')),
url('admin/', admin.site.urls),
path('clearfile', views.clearfile),
path('readfile', views.readfile),
path('writefile', views.writefile),
path('helloworld', views.helloworld),
path('order_input', views.order_input),
path('ajax_view', views.ajax_view),
]
You have the order_input url defined in both your project and your app urls.py files, only in the hw_app version it has a trailing slash. The slashless project URL may be looking in the wrong places for things as it will assume there is a related view at its level.
Try removing that path from the project urls.py file. Assuming it should be going to the same place, it's already included when you include(hw_apps.urls) (as url() is just a more up-to-date path() ). Then try calling the page with a trailing slash.
The only view file then relevant should be hw_apps/views.py. For consistency place the HTML template file is in hw_app/templates/hw_app/order_input.html so you know django should be able to find it.

How can i fix Page not found 404 in django?

Hi ive been coding my first website and then try running the product page I get this error
*Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/products
Using the URLconf defined in myshop.urls, Django tried these URL patterns, in this order:
admin/
The current path, products, 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.*
how can I solve this? Here is my code...
my views page code
from django.http import HttpResponse
from django.shortcuts import render
def index(request):
return HttpResponse('Hello world')
def new(request):
return HttpResponse('New Products')
productsurls code
from django.urls import path
from . import views
urlpatterns = [
path('', views.index),
path('new', views.new)
]
myshopurls
from django.contrib import admin
from django.urls import path, include
urlpatterns = {
path('admin/', admin.site.urls),
path('products/', include('products.urls'))
}
Most probably, you are facing this problem because you have not include your app "products" in the "settings.py" file.
-> After checking your code I can conclude that"myshop" is your project and "products" is your app.
So, you will have to go in settings.py file under which you will find a list "INSTALLED_APPS".
Inside INSTALLED_APPS -> You will have to include your app.
Go to "apps.py" file of the "products" app and copy the name of the "config" class.
After that in your settings.py file, you will have to write 'products.apps.(paste the name of config class)'.
Most probably name of your config class will be "ProductsConfig" -> So, you will have to write 'products.apps.ProductsConfig',
Hope it will work !
You have to include the app under INSTALLED_APPS in settings.py file.
So your settings.py file should read like so
INSTALLED_APPS = [
# Built In Apps
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# User Defined Apps
'product.apps.ProductConfig',
]
Tip - If you are confused as to how to include the name under installed Apps. It should be like so
<myapp>.apps.<name_of_class_in_myapp/apps.py_file>
Basically navigate to your app folder -> apps.py file and check the name of the class. It will be like so
from django.apps import AppConfig
class ProductConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'product'
You want the name of this class. ProductConfig.
Note - Local apps should always be added at the bottom because Django executes the
INSTALLED_APPS setting from top to bottom. We want the core Django apps to be available before our app.
The reason for listing the app like
'product.apps.ProductConfig',
is because it is best practice and helps if in future if you decide to use Django Signals.

Django is not invoking my app's ready method [duplicate]

Trying to catch the basics of Django. Namely how Applications work.
The docs: https://docs.djangoproject.com/en/stable/ref/applications/#methods
And in the code of the class AppConfig we can read:
def ready(self):
"""
Override this method in subclasses to run code when Django starts.
"""
Well, this is my example:
my_app/apps.py
class MyAppConfig(AppConfig):
name = 'my_app'
def ready(self):
print('My app')
I just want to make the ready method work. That is, when Django finds my_app, let it run the ready method.
The app is registered in INSTALLED_APPS.
I execute 'python manage.py runserver'. And nothing is printed.
If I place a breakpoint inside the ready method, the debugger don't stop there.
Could you help me: what is my mistake in understanding here. Thank you in advance.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'my_app',
]
And I created a view
my_app/views.py
def index(request):
print('Print index')
urls.py
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', my_app_views.index, name='home')
]
Well, the view is working. This means that the application is registered.
You need to do one of two things. Either explicitly say which AppConfig you want in INSTALLED_APPS:
INSTALLED_APPS = [
'my_app.apps.MyAppConfig'
]
Or, define a default_app_config in the __init__.py of your app:
# my_app/__init__.py
default_app_config = 'my_app.apps.MyAppConfig'
(and leave INSTALLED_APPS as-is).
As it is currently Django can't find any AppConfig for the app and just assumes there isn't one. So your views etc. will work, but the ready() method will never get called.
Here's the relevant section of the documentation.
Edit: as of Django 3.2, specifying a default_app_config is no longer necessary, and is in fact deprecated - so this answer is redundant for anyone using Django 3.2 or later.

RuntimeError: Model class django.contrib.sites.models.Site doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS

I am building an application with Django Rest Framework and AngularJs. I am using Django-rest-auth for my authentication purposes, although, I have not been able to set it up. Anyway, I am trying to set up this app with my project. I realized I need to install django-rest-auth-registration to get it running, so I followed this documentation to do the following things:
I ran the commands
pip install django-rest-auth
and
pip install django-allauth
Any my settings.py looks like this:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# 3rd party apps
'rest_framework',
'rest_framework.authtoken',
'rest_auth',
'allauth',
'allauth.account',
'rest_auth.registration',
# My app
'myapp',
]
I have also added the authentication backends, context_processors, and the proper urls.
However, when I try to migrate, my terminal throws the following error:
RuntimeError: Model class django.contrib.sites.models.Site doesn't
declare an explicit app_label and isn't in an application in
INSTALLED_APPS.
Why do I get this error, and how do I solve it to migrate my project? Thanks!
The fix
Just add Django's Sites framework to your apps and set SITE_ID to 1 in your settings.
INSTALLED_APPS = [
...
'django.contrib.sites',
]
SITE_ID = 1
Why does this happen?
Django's Sites Framework is a contributed module bundled with the core library that allows for the use of a single Django application/codebase with different sites (that can use different databases, logic in views, etc). The SITE_ID setting, as stated in the docs, "is used so that application data can hook into specific sites and a single database can manage content for multiple sites."
In this particular case AllAuth requires the Sites Framework in order to function properly. Many other third-party libraries are built to safely handle cases where multiple sites may be present and as such may be best .
I landed on this post via Google search. My problem was running tests that blew up with the error:
RuntimeError: Model class app.taxonomy.models.Term doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
This was running on Python 2.7.x with absolute imports. As mentioned by Colton Hicks in the comments, below, this can also happen with Python 3 (pytest 3.2.3 with Django 1.11.4).
In my tests.py:
from __future__ import absolute_import
[...]
from .models import Demographics, Term
After changing the relative import to an absolute import the problem went away:
from taxonomy.models import Demographics, Term
HTH
Try adding the app_label = 'yourApp' in the models Meta class:
class Meta:
app_label = 'yourApp'
I got the error above. However my problem was the in the urls.py. I was following PyDanny cookiecutter django recipe. My error was to put in the urls.py this line:
url(r'^demo/', include('project.demoapp.urls', namespace='demoapp')),
when I corrected to this:
url(r'^demo/', include('demoapp.urls', namespace='demoapp')),
all was well. I also changed my local apps (I did this first and so the critical error was the url misconfiguration):
LOCAL_APPS = [
# Your stuff: custom apps go here
'demoapp.apps.DemoAppConfig',
]
I have django debug toolbar installed and this was actually causing the/my problem.
INSTALLED_APPS (in settings.py) needs the entry 'django.contrib.sessions'. Make sure to run migrate after adding.
Just add 'django.contrib.sites', to INSTALLED_APPS and set SITE_ID = 1 in your settings.py file.
Upgraded Answer for Django>=4.0 // 2022
Add Django's Sites framework and FlatPages Framework to your INSTALLED_APPS and set SITE_ID in your settings.
INSTALLED_APPS = [
...
'django.contrib.sites',
'django.contrib.flatpages',
]
SITE_ID = 1
Your tests should work like a charm
This error occurred because I had created a new app folder for a subset of sites related to another feature. This needed to be added to my INSTALLED_APPS in settings.py
Django 4.1+ (2023)
After almost an hour digging, what solved for me was this:
INSTALLED_APPS = [
...
'django.contrib.sessions',
]
No need for SITE_ID or additional INSTALLED_APPS entries.
Everything worked as expected after I made a migration
python manage.py migrate
Good luck