TemplateDoesNotExist at /blog/create/ - html

When I click on create post it takes me to .../blog/create/ and I get this error: TemplateDoesNotExist at /blog/create/
base.html
<!DOCTYPE html>
<html lang*en>
<head>
<title>This is the Title</title>
{% include 'snippets/header.html' %}
</head>
<body>
<!-- Body -->
<style type="text/css">
.main{
min-height: 100vh;
height: 100%;
}
</style>
<div class="main">
{% block content %}
{% endblock content %}
</div>
{% include 'snippets/footer.html' %}
</body>
</html>
blog/Template/blog/create.html
{% extends 'base.html' %}
{% block content %}
<p>Create a new blog...</p>
{% endblock content %}
blog/urls.py
from django.urls import path
from blog.views import(
create_blog_view,
)
app_name = 'blog'
urlpatterns = [
path('create/', create_blog_view, name="create"),
]
main urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from personal.views import (
home_screen_view,
)
from account.views import (
registration_view,
logout_view,
login_view,
account_view,
)
urlpatterns = [
path('admin/', admin.site.urls),
path('', home_screen_view, name="home"),
path('register/', registration_view, name="register"),
path('blog/', include('blog.urls', 'blog')),
path('logout/', logout_view, name="logout"),
path('login/', login_view, name="login"),
path('account/', account_view, name="account"),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
blog/views.py
from django.shortcuts import render
from blog.models import BlogPost
def create_blog_view(request):
return render(request, "blog/create.html", {})
personal/Template/snippets/home.html
{% extends 'base.html' %}
{% block content %}
<style type="text/css">
#media (max-width: 768px) {
.right-column{
margin-left: 0px;
}
}
#media (min-width: 768px) {
.right-column{
margin-left: 20px;
}
}
.blog-post-container{
background-color: #fff;
margin-bottom: 20px;
width: 100%;
}
.create-post-bar{
background-color: #fff;
margin-bottom:20px;
}
.left-column{
padding:0px;
}
.right-column{
padding:0px;
}
</style>
<div class="container">
<div class="row">
<div class="create-post-bar d-lg-none col-lg-7 offset-lg-1">
Create post
</div>
<div class="left-column col-lg-7 offset-lg-1">
<div class="blog-post-container">
<p>Thingy</p>
</div>
<div class="blog-post-container">
<p>Thingy</p>
</div>
<div class="blog-post-container">
<p>Thingy</p>
</div>
</div>
<div class="right-column col-lg-3 d-lg-flex d-none flex-column">
<div class="create-post-bar">
<p>Stuff</p>
<p>Stuff</p>
<p>Stuff</p>
<a class="p-2 btn btn-outline-primary" href="{% url 'blog:create' %}">Create post</a>
</div>
</div>
</div>
</div>
{% endblock content %}
settings.py
from pathlib import Path
import os
BASE_DIR = Path(__file__).resolve().parent.parent
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'personal',
'account',
'blog',
#Djangos apps
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
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 = 'mysite.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',
],
},
},
]
AUTH_USER_MODEL = 'account.Account'
WSGI_APPLICATION = 'mysite.wsgi.application'
...
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
os.path.join(BASE_DIR, 'media'),
]
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static_cdn')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media_cdn')
I was expecting it to redirect me to the new page but it shows an error.

With APP_DIRS enabled Django searches for templates inside each app /templates/ subfolder. Lowercase, plural.
You have Template - wrong case, missing s in the end. So yes, the template does not exist for Django because it cannot be found at any expected location.

Apparently your app doesn't look into blog's template folder. It only looks into personal
and account's template folders. You can check that in the attached picture under template-loader postmortem. It usually means that the app is not installed properly.
There are lots of reasons for such a thing, among them:
You might have located it in a wrong directory. The app must be at ./src/. It seems that it's not the case as the url.py is working properly.
It might be the case that you forgot to save settings.py after you added the blog app.
It might be your virtual environment. A restart and a migrate command might help.
Otherwise you might have changed the app's template directory somewhere.

You have, in your settings.py, the configuration
'DIRS': [os.path.join(BASE_DIR, 'Templates')],
so you need to have the Templates directory in your base directory, not inside each app, it should be
Template/blog/create.html
and not
blog/Template/blog/create.html

Related

Django reverse for 'password_change_done' not found

I have a small application that I'm writing, but I have came into some trouble with the password changing elements used with the Django authentication framework. But I always get the error after changing a password that: Reverse for 'password_change_done' not found. 'password_change_done' is not a valid view function or pattern name. Here is my code below:
#account urls.py
from django.urls import path, include
from django.contrib.auth import views as auth_views
from . import views
app_name = 'account'
urlpatterns = [
#Password Changes URLs
path('password_change/', auth_views.PasswordChangeView.as_view(), name='password_change'),
path('password_change/done/', auth_views.PasswordChangeDoneView.as_view(), name='password_change_done'),
]
This is my directory structure for the login system:
Directory Structure
Here's the password_change.html file:
<h3 style="text-align: center;">Change your password</h3>
<div class="login-form" style="text-align: center; ">
<form method="post">
{{ form.as_p }}
<p><input type="submit" value="Change"></p>
{% csrf_token %}
</form>
</div>
Any help would be greatly appreciated!
Since you use an app_name, you will need to include the namespace in the success_url of the PasswordChangeView:
# account urls.py
from django.urls import path, include
from django.contrib.auth import views as auth_views
from . import views
from django.urls import reverse_lazy
app_name = 'account'
urlpatterns = [
#Password Changes URLs
path('password_change/', auth_views.PasswordChangeView.as_view(
success_url=reverse_lazy('account:password_change_done')
), name='password_change'),
path('password_change/done/', auth_views.PasswordChangeDoneView.as_view(), name='password_change_done'),
]
some other class-based views of the auth package have success_urls, these thus should be updated as well.

NoReverseMatch at 'url' in Django, Reverse for 'my_app' not found. 'my_app' is not a valid view function or pattern name

I'm new to Django, and today when I tried to run a website with a database, I have encountered this error.
I have searched for all solutions on StackOverflow and Django documents, but I can not fix it.
This is the problem that similar to me, but it doesn't work.
I want to create a link that moves user from user.html in user to index.html in citizens
Here is my project structure. I'm sorry because I can't attach an image, so I will try to explain it in easiest way.
[MYPROJECT]
->manage.py
->citizens (folder)
-->templates (inside this folder I have citizen.html, index.html, layout.html)
-->admin.py
-->models.py
-->tests.py
-->urls.py
-->views.py
->myproject (folder)
-->setting.py
-->urls.py
-->etc that I think not important
->user (folder)
-->templates (inside this folder I have login.html, user.html, layout.html)
-->urls.py
-->views.py
-->etc that I think not important
As you can see, I have user.html inside templates folder of user, and index.html inside templates folder of citizens.
Here is my code:
index.html inside citizens
{% extends "citizens/layout.html" %}
{% block body %}
<h1>Hệ thống quản lý XNC</h1>
<table class="table">
<thead>
<tr>
<th scope="col">Số TT</th>
<th scope="col">Họ và tên công dân</th>
<th scope="col">Giới tính</th>
<th scope="col">Số Hộ chiếu</th>
<th scope="col">Chi tiết</th>
</tr>
</thead>
<tbody>
{% for citizen in citizens %}
<tr>
<th scope="row">{{ forloop.counter }}</th>
<td>{{ citizen.name }}</td>
<td>{{ citizen.sex }}</td>
<td>{{ citizen.sID }}</td>
<td>Truy cập</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}
user.html inside user
{% extends "users/layout.html" %}
{% block body %}
<h1>Chào mừng, {{ request.user.username }}</h1>
<ul>
<li>Username: {{request.user.username }}</li>
</ul>
Truy cập Cơ sở dữ liệu
{% endblock %}
urls.py inside citizens
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("<int:citizen_id>", views.citizen, name="citizen"),
#path("<int:citizen_id>/passports", views.passport, name="passports")
]
views.py inside citizens
from django.shortcuts import render
from django.http import HttpResponseBadRequest, HttpResponseRedirect, Http404
from django.urls import reverse
from .models import Citizen
# Create your views here.
def index(request):
return render(request, "citizens/index.html", {
"citizens": Citizen.objects.all()
})
def citizen(request, citizen_id):
try:
citizen = Citizen.objects.get(sID=citizen_id)
except Citizen.DoesNotExist:
raise Http404("Citizen not found")
return render(request, "citizens/citizen.html", {
"citizen": citizen,
})
urls.py inside myproject
"""htql2 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('citizens/', include('citizens.urls')),
path('accounts/', include('django.contrib.auth.urls')),
path('users/', include('users.urls')),
]
urls.py inside users
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
]
views.py inside users
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth import authenticate, login, logout
from django.shortcuts import render
from django.http import HttpResponseBadRequest, HttpResponseRedirect, Http404
from django.urls import reverse
#csrf_exempt
# Create your views here.
def index(request):
if not request.user.is_authenticated:
return HttpResponseRedirect(reverse("login"))
return render(request, "users/user.html")
def login_view(request):
if request.method == "POST":
username = request.POST["username"]
password = request.POST["password"]
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return HttpResponseRedirect(reverse("index"))
else:
return render(request, "users/login.html", {
"message": "Invalid credentials."
})
else:
return render(request, "users/login.html")
def logout_view(request):
pass
Inside user.html, I have tried to use
Go to Database
but doesn't work.
Thank you. I'm so grateful.
You have tried to use {% url 'citizen:citizens/' %} here the part before : (citizen) is a url namespace and the part after it (citizens) is the url name. But you haven't used any namespace, and neither do you have a url name as citizens.
You can add a namespace in citizens.urls by specifying app_name:
from django.urls import path
from . import views
app_name = 'citizens' # here
urlpatterns = [
path("", views.index, name="index"),
path("<int:citizen_id>", views.citizen, name="citizen"),
#path("<int:citizen_id>/passports", views.passport, name="passports")
]
Next you need to write the url tag as {% url 'citizens:index' %}:
Go to Database

Django image not loading Page not Found Error

I'm new to Django and I'm facing a problem of loading a static file (image). I got
127.0.0.1/:1707 GET http://127.0.0.1:8000/static/css/static/images/background/1.jpg 404 (Not Found)
I'm pretty sure that the problem is on the path but I can't understand where this /static/css/ comes from. Could you please help me?
My settings.py file:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'evillio/static')
]
My index.html file:
<!-- First Page with Picture and Search Starts -->
<section class="home-one home1-overlay **home1_bgi1**">
<div class="container">
<div class="row posr">
<div class="col-lg-12">
<div class="home_content">
<div class="home-text text-center">
<h2 class="fz55">Find Your Dream Home</h2>
<p class="fz18 color-white">From as low as $10 per day with limited time offer discounts.</p>
</div>
My CSS file:
home1_bgi1{
background-image: url('static/images/background/1.jpg');
-webkit-background-size: cover;
background-size: cover;
background-position: center center;
height: 960px;
When inspecting the page
Did you include {% load static %} at the top ??
For the latest version of Django, it doesn't use that in Setting.py:
`STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'evillio/static')
]`
Instead of this for Django 3.1 change code as bellow:
`STATICFILES_DIRS = [
BASE_DIR / "static",
'/var/www/static/',
]`
Read the documentation of Django 3.1, it has some code updated in the previous version of Django.
https://docs.djangoproject.com/en/3.1/howto/static-files/

Django doesn't accept image submission, method and enctype included in form tag but browser console claims it is missing

I'm following along with a tutorial to build a Django project. Part of the project is being able to upload an image to the test cdn directory. This is what my form looks like currently:
<form method='POST' action="." enctype='multipart/form-data'> {% csrf_token %}
{{ form.as_p }}
<button type="submit">Send</button>
</form>
The method and enctype are very clearly defined.
I've also set up my settings.py
STATIC_URL = '/static/'
LOCAL_STATIC_CDN_PATH = os.path.join(os.path.dirname(BASE_DIR), 'static_cdn_test')
STATIC_ROOT = os.path.join(LOCAL_STATIC_CDN_PATH, 'static')
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'staticfiles')
]
MEDIA_ROOT = os.path.join(LOCAL_STATIC_CDN_PATH, 'media')
MEDIA_URL = '/media/'
set up the files to be received in the view:
form = BlogPostModelForm(request.POST or None, request.FILES or None)
set up the model use ImageField:
image = models.ImageField(upload_to='image/', blank=True, null=True)
and the url patterns:
if settings.DEBUG:
# test mode
from django.conf.urls.static import static
# display images/files saved in the test cdn
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
But even with all this, the console informs me:
Form contains a file input, but is missing method=POST and enctype=multipart/form-data on the form. The file will not be sent.
This is the tutorial in case it helps https://www.youtube.com/watch?v=-oQvMHpKkms&list=PLM39hJgCef42hVok8ZRRE4LpLD-5bOxBh&index=20&t=13385s the part in question starts at 3:48:00.

Django Translations Not Working

I am working in a Django 1.9 / python3.5 application, and trying to make use of Django's translation utility. I have a locale directory which has an 'es' directory for spanish translations that I created a .po file in. I set it up to have a couple translations just to test it out.
msgid "Sign In"
msgstr "Registrarse"
msgid "Create an Account"
msgstr "Crea una cuenta"
I have my setting file correctly configured as well
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'webapp.middleware.LanguageSwitchMiddleware',
)
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'DIRS': [os.path.join(BASE_DIR, 'templates'), ],
'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',
'webapp.context_processors.detail_context',
'django.template.context_processors.i18n'
],
},
},
]
# Internationalization
# https://docs.djangoproject.com/en/dev/topics/i18n/
LOCALE_PATHS = (
os.path.join(PROJECT_ROOT, 'locale/'),
)
from django.utils.translation import ugettext_lazy as _
LANGUAGES = (
('en', _('English')), # first language is the default used by modeltranslations
('es', _('Spanish')),
)
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/Chicago'
USE_I18N = True
In my template I use the Django 'trans' template tag for the words sign in, and create an account. A select box will edit the Content-Language http response header from the application, which I have tested, and it successfully does so. However the headers sign up, and create and account, do not translate to Spanish. Is there some step I'm missing ?
HTML
{% load i18n %}
<ul class="list-inline-xxs">
{% if customer %}
<li>
Welcome,
<a href='{% url "customer:dashboard" %}'>
{{ customer.first_name }}
</a>
</li>
<li>
<a href='{% url "customer:logout" %}'>
{% trans 'Logout' %}
</a>
</li>
{% else %}
<li>
<a href='{% url "customer:login" %}'>
{% trans 'Sign In' %}
</a>
</li>
<li>
<a href='{% url "subscription:customer-subscribe" %}'>
{% trans 'Create an Account' %}
</a>
</li>
{% endif %}
</ul>
I have a locale directory which has an 'es' directory for spanish
translations that I created a .po file in.
That ^^^ line suggests you are creating translation files manually. Let Django create translation files for you:
django-admin makemessages -a
Then put in your translations, save the file and compile with
django-admin compilemessages
Restart your app and it should work.
I've put together a simple example how to do translations with Django: https://github.com/DusanMadar/Django-multilang-demo
EDIT
As django django-admin makemessages -h suggests --ignore PATTERN, -i PATTERN is what you need to use to ignore third party directories. So something like django-admin makemessages -a -i 3rdparty_dir