I am having a structure of Django Project as:
│ db.sqlite3
│ manage.py
│
├───static
│ │ 1.jpg
│ │ bg1.jpg
│ │
│ └───css
│ login.css
│
├───templates
│ home.html
│ login.html
│ register.html
│
├───User
│ │ admin.py
│ │ apps.py
│ │ models.py
│ │ tests.py
│ │ urls.py
│ │ views.py
│ │ __init__.py
│ │
│ ├───migrations
│ │ │ __init__.py
│ │ │
│ │ └───__pycache__
│ │ __init__.cpython-38.pyc
│ │
│ └───__pycache__
│ admin.cpython-38.pyc
│ apps.cpython-38.pyc
│ models.cpython-38.pyc
│ urls.cpython-38.pyc
│ views.cpython-38.pyc
│ __init__.cpython-38.pyc
│
└───Website
│ asgi.py
│ settings.py
│ urls.py
│ wsgi.py
│ __init__.py
│
└───__pycache__
settings.cpython-38.pyc
urls.cpython-38.pyc
wsgi.cpython-38.pyc
__init__.cpython-38.pyc
Settings.py
"""
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-c*3$w_63#$^8g&_fn%r=-23n^e#nrmxzxt7eh*owsz^mlrk5dr'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'User'
]
MIDDLEWARE = [
'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 = 'Website.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'templates')],
'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 = 'Website.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIR= [os.path.join(BASE_DIR,'static'),
]
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
And my Register.html File
{% load static %}
<html>
<head>
<title></title>
<style>
body
{
background:url({% static 'bg1.jpg' %});
}
</style>
</head>
<body>
<img src="{% static '1.jpg' %}">
<h1> HELOO </h1>
</body>
</html>
I have loaded the static and also the path for the static files still its not able to find image which i am providing in my html page. No issues while using template folder but only for static folder my project is not able to get the images and paste it on the browser.
Changing STATICFILES_DIR to STATICFILES_DIRS in setting.py helped to fix this error.
Thanks to Afzal Saiyed
Related
I can't find a solution for the following error:
RuntimeError: Model class users.models.User.User doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
The INSTALLED_APPS:
LOCAL_APPS = [
"api.users",
"api.achievements",
"api.others",
]
# https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps
INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS
Models folder
users/models/__init__.py:
from .User import * # noqa
from .Profile import * # noqa
users/models/User.py:
""" User related models """
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.urls import reverse
from django_countries.fields import CountryField
from api.others.constants import GENDER
class User(AbstractUser):
"""
Default custom user model for Dezumi API.
If adding fields that need to be filled at user signup,
check forms.SignupForm and forms.SocialSignupForms accordingly.
"""
birth_date = models.DateField(null=True, blank=True)
country = CountryField(null=True, blank=True, blank_label='Select country')
gender = models.CharField(choices=GENDER, max_length=6, null=True, blank=True)
is_verified = models.BooleanField(
default=False,
)
def get_absolute_url(self):
"""Get url for user's detail view.
Returns:
str: URL for user detail.
"""
return reverse("users:detail", kwargs={"username": self.username})
The app is on installed_apps, so what could it be? Something with the init.py?
Directory Structure:
api
├── api
│ ├── __init__.py
│ ├── conftest.py
│ ├── users
│ │ ├── admin
│ │ ├── api
│ │ │ ├── serializers.py
│ │ │ └── views.py
│ │ ├── migrations
│ │ ├── models
│ │ │ ├── __init__.py
│ │ │ ├── Profile.py
│ │ │ └── User.py
│ │ ├── __init__.py
│ │ ├── apps.py
│ │ └── ...
│ └── ...
├── config
│ ├── settings
│ │ ├── __init__.py
│ │ ├── base.py
│ │ ├── local.py
│ │ ├── production.py
│ │ └── test.py
│ ├── __init__.py
│ └── ...
├── requirements
├── utility
├── manage.py
└── ...
Log:
File "path\api\api\users\admin\__init__.py", line 1, in <module>
from .Profile import * # noqa
File "path\api\api\users\admin\Profile.py", line 3, in <module>
from users.models.Profile import Profile
File "path\api\api\users\models\__init__.py", line 1, in <module>
from .User import * # noqa
File "path\api\api\users\models\User.py", line 11, in <module>
class User(AbstractUser):
File "path\lib\site-packages\django\db\models\base.py", line 113, in __new__
raise RuntimeError(
RuntimeError: Model class users.models.User.User doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
apps.py from users
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class UsersConfig(AppConfig):
name = "api.users"
verbose_name = _("Users")
def ready(self):
try:
import api.users.signals # noqa F401
except ImportError:
pass
Explicitly referencing the Users app configuration class might work:
LOCAL_APPS = [
"api.users.apps.UsersConfig",
...
]
First of all: I know, there are a few solutions for this online, but they wont work for me (because they use e.g. Jason or are just outdated)
I work on a project in Django and want to use ajax for one task:
I want to pass data, after it was processed by ajax, from my template file to my views file (with a POST request), to again make it visible in my templates file.
Templates-file --> Proccessed data --> POST-request --> views.py --> Template-file
But it just wont work for me.
My HTML-Templates-File:
...
<script type="text/javascript">
var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val();
function csrfSafeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function (xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
$.ajax({
url: "/save",
data: {
'value': inputDataArray //I have already defined "inputDataArray" before
},
success: function (res, status) {
alert(res);
alert(status);
},
error: function (res) {
alert(res.status);
}
});
</script>
My views.py file:
def save(request):
if request.method == 'POST':
request_getdata = request.POST.get("value", None)
return render(request, "response.html", {"data":request_getdata})
urls.py file:
urlpatterns = [
path('', views.index , name='index'),
path('save', views.save , name='save'),]
So I try display it at "response.html"...
{{data}}
...but it just will reload the current page and does not pass any data to the response.html-file.
Does anyone knows what my error is here?
Thanks a lot in advance
P.S.: This is my project structure:
│ db.sqlite3
│ manage.py
│
├───myapp
│ │ admin.py
│ │ apps.py
│ │ models.py
│ │ tests.py
│ │ urls.py
│ │ views.py
│ │ __init__.py
│ │
│ ├───migrations
│ │ __init__.py
│ │
│ └───__pycache__
│ urls.cpython-39.pyc
│ views.cpython-39.pyc
│ __init__.cpython-39.pyc
│
├───static
│ └───myapp
│ └───css
│ index.css
│
├───templates
│ index.html
│ result.html
│
└───myapp
│ asgi.py
│ settings.py
│ urls.py
│ wsgi.py
│ __init__.py
│
└───__pycache__
...
Instead of
urlpatterns = [
path('', views.index , name='index'),
path('save', views.save , name='save'),]
Try :
urlpatterns = [
path('', myapp.views.index , name='index'),
path('save',myapp.views.save , name='save')
I called a template in the django render function, but django cannot find it
here is the django view code:
from django.shortcuts import render
# Create your views here.
def home_page(request):
return render(request, "index.html")
And after this I tried to check my settings.py and urls.py, but found nothing, and the file is also in the tamplate subfolder of the app
here is the directory structure:
│ .gitignore
│ db.sqlite3
│ funcational_test.py
│ manage.py
│
├─Terminal_equipment_management
│ │ asgi.py
│ │ settings.py
│ │ urls.py
│ │ view.py
│ │ wsgi.py
│ │ __init__.py
│ │
│ └─__pycache__
│
└─webui
│ admin.py
│ apps.py
│ models.py
│ tests.py
│ views.py
│ __init__.py
│
├─migrations
│
├─templates
index.html
the settings.py is:
INSTALLED_APPS = [
"api",
"webui",
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
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',
],
},
},
]
urls.py is:
from django.contrib import admin
from django.urls import path, include
from webui import views
urlpatterns = [
path("", views.home_page, name="home_page"),
]
But when I visit localhost:8000/, Django will report TemplateDoesNotExist at /
here is some Error Message:
Template-loader postmortem
Django tried loading these templates, in this order:
Using engine django:
django.template.loaders.app_directories.Loader: C:\ProgramData\Miniconda3\lib\site-packages\django\contrib\admin\templates\index.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\ProgramData\Miniconda3\lib\site-packages\django\contrib\auth\templates\index.html (Source does not exist)
When I copied the files to the above two folders, the template took effect.
I can't be sure what happened
By Google Translate
Add Template DIRS:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / "template"],
'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',
],
},
},
]
I think you forgot to put s for template folder names
└─webui
│
├─tamplates
index.html
First, tamplates should be templates. Second, django looks inside a folder under templates for the app name. It seems redundant, and I agree, but that caused me issues when I was first using django.
└─webui
│
└─templates
│
└─webui
│
└─index.html
I have seen this tutorial https://samulinatri.com/blog/django-ckeditor-codesnippet-hightlightjs-youtube/ and I have downloaded the youtube plugin here https://ckeditor.com/cke4/addon/youtube
Then I created the youtube folder and pushed it into it. Specifically my_project / static / ckeditor / ckeditor / plugins / youtube /
After I python manage.py runserver, field ['content'] show normal, field ['content1'] it doesn't work (does not display frames textarea).
Someone helped me check, I did something wrong. Thanks !!!
File model.py
class Posts(models.Model):
title = models.CharField(max_length=50)
content = RichTextUploadingField(extra_plugins=['codesnippet'],)
content1 = RichTextUploadingField(
config_name='special',
extra_plugins=['youtube'],
external_plugin_resources=[(
'youtube',
'/static/ckeditor/ckeditor/plugins/youtube/youtube/',
'plugin.js',
)],
)
File setting.py
INSTALLED_APPS = [
'suit',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'ckeditor',
'ckeditor_uploader',
]
CKEDITOR_UPLOAD_PATH = "uploads/"
CKEDITOR_CONFIGS = {
'default': {
'toolbar': 'full',
},
'special': {
'toolbar': 'Special',
'toolbar_Special': [
['Bold'], ['CodeSnippet', 'Youtube'],
],
'extraPlugins': ','.join(['codesnippet', 'youtube']),
}
}
File urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('account/', include(('accounts.urls', 'accounts'), namespace='accounts')),
path('blog/', include(('blog.urls', 'blog'), namespace='blog')),
path('ckeditor/', include('ckeditor_uploader.urls')),
]
if settings.DEBUG:
import debug_toolbar
debug_patterns = [
re_path(r'^__debug__/', include(debug_toolbar.urls)),
]
urlpatterns = debug_patterns + urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
My_project
├── blog <= This my_app
│ ├── view.py
│ ├── form.py
│ ├── model.py
├── project <= Project settings directory
│ ├── __init__.py
│ ├── settings.py <= settings
│ ├── urls.py
│ └── wsgi.py
├── static
│ ├── ckeditor
│ ├── ckeditor_uploader
│ ├── ckeditor
│ ├── plugins
│ └── youtube
│ └── youtube
│ └── images
│ └── lang
│ └── plugin.js
│ └── ....
│ └── ...
│ └── ...
In your models.py file, you need to point to the directory where the plugin.js is.
I believe the directory you should refer to is this:
class Posts(models.Model):
title = models.CharField(max_length=50)
content = RichTextUploadingField(extra_plugins=['codesnippet'],)
content1 = RichTextUploadingField(
config_name='special',
extra_plugins=['youtube'],
external_plugin_resources=[(
'youtube',
'/static/ckeditor/ckeditor/plugins/youtube/',
'plugin.js',
)],
)
I'm developing a django app. It has three apps in it, each with it's own template directory and index.html file. But when I call view from the second app it picks up the template file from the first app rather than the second one.
Is it a must that every template name be unique?
my projects directory:
├───jobs
│ ├───migrations
│ ├───static
│ └───templates
├───job_portal
├───main_app
│ ├───migrations
│ ├───static
│ └───templates
├───project_static
│ ├───css
│ ├───fonts
│ ├───images
│ └───js
└───recruiters
├───migrations
├───static
│ ├───css
│ ├───fonts
│ ├───images
│ └───js
└───templates
In Django you can use templates with the same names for different apps. But you should add subfolders inside app's template directory like this:
my_app/templates/my_app/base.html
second_app/templates/second_app/base.html
Now in views you should include app name to the template name:
return render(request, 'my_app/base.html')
return render(request, 'second_app/base.html').