I need to make a multilingual website and have found instructions on how to do this. I did everything according to the instructions but when I write /en/ for example nothing happens
settings.py
from pathlib import Path
from django.utils.translation import gettext_lazy as _
# 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/4.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ''
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# LOGIN_URL = '/users/login'
AUTH_USER_MODEL = 'users.User'
LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home'
# Application definition
SITE_ID = 1
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'MainConv',
'users',
'modeltranslation',
'gettext',
]
LANGUAGES = [
('en', _('English')),
('ru', _('Russian')),
]
LOCALE_PATHS = [
BASE_DIR / 'locale/',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'Converter.urls'
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',
],
},
},
]
WSGI_APPLICATION = 'Converter.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'sxgc1',
'USER': 'postgres',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': '',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.0/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/4.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
USE_L10N = True
DATE_INPUT_FORMATS = ( "%d/%m/%Y", )
DATETIME_INPUT_FORMATS = ( "%d/%m/%Y %H:%M", )
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_URL = 'static/'
MEDIA_URL = '/media/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
html.html
<!DOCTYPE html>
<html lang="en">
<head>
{% load static %}
{% load l10n %}
{% load i18n %}
<meta name="description" content="MainConv"/>
<title>{% block title %}SAP XML-Generator Converter{% endblock title %}</title>
{% block css %}
<link rel="stylesheet" href="{% static 'css/MainConv.css' %}">
{% endblock css %}
</head>
<body>
<header>
{% block menu%}
{% if user.is_authenticated %}
Home
Convertation
{% else %}
SingUp
Login
{% endif %}
{% if user.is_authenticated %}
logout
{% endif %}
{% endblock menu%}
</header>
{% block content %}
<h1>{% trans "Welcome to our website" %}</h1>
<h2>{% trans "Convert your xml to xml" %}</h2>
<button>Convertation</button>
{% endblock content %}
</body>
</html>
there is also a locale folder
enter image description here
I don't get any errors just nothing happens
Related
I cannot solve "django.urls.exceptions.NoReverseMatch: 'XXX' is not a registered namespace" problem with Django3.1.1.
I have seen similar issues on many websites, I cannot solve mine.
The error message on browser is NoReverseMatch at / 'shiharaisaisokumoushitatesho' is not a registered namespace
The error message on terminal is django.urls.exceptions.NoReverseMatch: 'shiharaisaisokumoushitatesho' is not a registered namespace
I just want to show index.html on "http://127.0.0.1:8000/" page.
./conf/settings.py
"""
Django settings for conf project.
Generated by 'django-admin startproject' using Django 3.1.1.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
import os
from pathlib import Path
# 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.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'xxx'
# 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',
'index.apps.IndexConfig',
'shiharaisaisokumoushitatesho.apps.ShiharaisaisokumoushitateshoConfig',
]
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 = 'conf.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 = 'conf.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/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.1/topics/i18n/
LANGUAGE_CODE = 'ja'
TIME_ZONE = 'Asia/Tokyo'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
./conf/urls.py
"""conf URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/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 path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('index.urls')),
]
./index/urls.py
from django.urls import path, include
from . import views
app_name = 'index'
urlpatterns = [
path('', views.index, name='index'),
path('shiharaisaisokumoushitatesho/', include('shiharaisaisokumoushitatesho.urls', namespace='shiharaisaisokumoushitatesho')),
]
./index/views.py
from django.shortcuts import render
def index(request):
return render(request, './index/index.html')
./templates/index/base.html
<!doctype html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Something</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<div class="row">
{% block content %}
This is index
{% endblock %}
</div>
</div>
</body>
</html>
./templates/index/index.html
{% extends './base.html' %}
{% block content %}
<div class="col text-center">
shiharaisaisokumoushitatesho:shiharaisaisokumoushitatesho1<br>
{% endblock %}
I modified below urls.py files, then the problem is solved.
./conf/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('index.urls')),
path('shiharaisaisokumoushitatesho/', include('shiharaisaisokumoushitatesho.urls')),
]
./shiharaisaisokumoushitatesho/urls.py
from django.urls import path, include
from . import views
app_name = 'shiharaisaisokumoushitatesho'
urlpatterns = [
path('', views.shiharaisaisokumoushitatesho1, name='shiharaisaisokumoushitatesho1'),
]
What should I do is I have to specify URL in ./conf/urls.py and empty URL in shiharaisaisokumoushitatesho in urls.py.
This question comes from the book 'Django 2 by example', and has been asked many times before, but even though I checked all the answers I can't fix the problem.
The only thing I am doing differently from the book is creating the 'blog' app inside a 'my_project' project (which contains other apps) rather than inside a 'mysite' project directory.
my error looks like this:
my_project/urls.py:
from django.contrib import admin
from django.urls import path, include
from person import views
from accounts.views import RegisterView # register
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home_view, name='home'),
path('person/', include('person.urls')),
path('create/', include('person.urls')),
path('accounts/', include('django.contrib.auth.urls')),
path('accounts/register/', RegisterView.as_view(), name='register'),
path('shopping-cart/', include('shopping_cart.urls')),
path('blog/', include('blog.urls', namespace='blog')),
]
my blog/urls.py:
from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
path('', views.post_list, name='post_list'),
path('<int:year>/<int:month>/<int:day>/<slug:post>/', views.post_detail, name='post_detail'),
]
my models.py:
from django.contrib.auth.models import User
from django.db import models
from django.utils import timezone
from django.urls import reverse
class PublishManager(models.Manager):
def get_queryset(self):
return super(PublishManager, self).get_queryset().filter(status='published')
class Post(models.Model):
STATUS_CHOICES = (
('draft', 'Draft'),
('published', 'Published'),
)
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250, unique_for_date='publish')
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_post')
body = models.TextField()
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft')
object = models.Manager() # The default manager.
published = PublishManager() # My custom manager
class Meta:
ordering = ('-publish',)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse(
'blog:post_detail',
args=[
'self.publish.year',
'self.publish.month',
'self.publish.day',
'self.slug',
]
)
my views.py:
from django.shortcuts import render, get_object_or_404
from .models import Post
def post_list(request):
posts = Post.published.all()
return render(request, 'blog/post/list.html', {'posts': posts})
def post_detail(request, year, month, day, post):
post = get_object_or_404(Post,
slug=post,
status='published',
publish__year=year,
publish__month=month,
publish__day=day)
return render(request, 'blog/post/detail.html', {'post': post})
list.html:
{% extends 'base.html' %}
{% block content %}
<h1>My Blog</h1>
{% for post in posts %}
<h2>
<a href="{{ post.get_absolute_url }}">
{{ post.title }}
</a>
</h2>
<p class="date">
Published {{ post.publish }} by {{ post.author }}
</p>
{{ post.body|truncatewords:30|linebreaks }}
{% endfor %}
{% endblock %}
details.html:
{% extends 'base.html' %}
{% block content %}
<h1>{{ post.title }}</h1>
{% for post in posts %}
<p class="date">
Published {{ post.publish }} by {{ post.author }}
</p>
{{ post.body|truncatewords:30|linebreaks }}
{% endfor %}
{% endblock %}
and just in case settings.py:
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'skqmec#*-cflm(s-%3rj&-1ti&ayk)%$ihk5h$3$u=0)ym!&+s'
# 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',
# created apps
'person',
'accounts',
'shopping_cart',
'blog.apps.BlogConfig',
]
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 = 'my_project.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'my_project/templates'),
os.path.join(BASE_DIR, 'persons/templates'),
os.path.join(BASE_DIR, 'accounts/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 = 'my_project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.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/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
DATE_INPUT_FORMATS = ['%d-%m-%Y']
DATE_FORMAT = ['%d-%m-%Y']
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, '/my_project/')
MEDIA_URL = '/media/'
LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home'
Also a screenshot of my project directories
please note that if I comment out everything related to the detail view (url patter, view, c.) and I just leave the list view, the path works fine (obviously when clicking on the blog name, which is a link, it doesn't take me anywhere). The problem is that even if I request the 'local host'/blog address, the program seems to be looking for blog/'the detail view'
Thanks in advance for any help
The problem is because of passing strings as args in your get_absolute_url. Simply change it as:
class Post(models.Model):
# ...
def get_absolute_url(self):
return reverse(
'blog:post_detail',
args=[
self.publish.year,
self.publish.month,
self.publish.day,
self.slug,
]
)
and just to clarify it more, as you said, you are seeing this error even when you are trying to access the /blog (list view); that's because the {{ post.get_absolute_url }} in the template of your list view is trying to return reverse object to each post, which will cause the error.
I'm trying to greet the user when they log into my django website, but using the django login has made it too difficult to send a message to my template and redirect to the new url behind the scenes. How can I greet the user(preferrably with that user's name) on the template of the url I redirect to?
I've tried working with messages, but redirecting to the new url always overrides the message and it never appears. Regular logging in and out works fine, I'm just trying to figure out how to display welcome text to the user to let them know they have successfully logged in and are using their own account.
views.py
def loginPage(request):
return render(request, "registration/login.html")
def login(request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
#Success!
messages.success(request, "Welcome " + user) #NOT WORKING :(
login(request, user)
else:
return HttpReponseRedirect("/DataApp/accounts/login/")
settings.py
# Application definition
INSTALLED_APPS = [
'DataApp.apps.DataappConfig',
'session_security',
'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',
'session_security.middleware.SessionSecurityMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'WebscrapeApp.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, '/DataApp/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 = 'WebscrapeApp.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.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/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/New_York'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
LOGIN_URL = "/DataApp/accounts/login/"
LOGIN_REDIRECT_URL = "/DataApp/search/"
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
SESSION_SECURITY_WARN_AFTER = 900
SESSION_SECURITY_EXPIRE_AFTER = 1200
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
base.html
<!-- This is nested in a div tag inside of the html class body -->
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}" {% endif %}>
{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
I wanted the message to appear within base.html after passing it but it appears django's login function overrides the sending of the message behind the scenes.
Solution:
base.html
<p>
{% if not user.is_anonymous %}
<font color="#00ccff">
Welcome {{ user }}
</font>
{% endif %}
</p>
views.html
def login_view(request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
#Success!
login(request, user)
context = {
"user": user
}
return render(request, "base.html", context)
else:
return HttpReponseRedirect("/DataApp/accounts/login/")
first rename login function, like login_view etc.
if that doesn't solve your problem, do these also
if user is not None:
login(request, user)
context = {
"user": user
}
return render(request, "base.html", context)
{% if user %}
Welcome {{ user }}
{% endif %}
I'm developing a new django project ,in the i have created a simple login page, which i want to just login and go to the home page.
when i try to login i'm getting and login is not happening successfully.
Project name: mysite
appname : dsmdata
Below are the codings
project(mysite) Settings.py file below
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 2.1.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
os.environ['REMOTE_USER'] = "dsmuser1"
#LOGIN_URL = '/dsm/login'
# Redirect to home URL after login (Default redirects to /accounts/profile/)
#LOGIN_REDIRECT_URL = '/dsm/logged_in'
LOGIN_REDIRECT_URL = '/'
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'y%cwxi-m5s-0zct+k%$u1$z!#o#u52zu_!z*#8(8saqdx+6t$l'
# 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',
]
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.auth.middleware.RemoteUserMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['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 = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.RemoteUserBackend',
'dsmdata.pmauth.pmauth',
]
# Password validation
# https://docs.djangoproject.com/en/2.1/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/2.1/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/2.1/howto/static-files/
STATIC_URL = '/static/'
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': 'C:/karthik/Projects/Postgres-DB-All/Statistics/debug.log',
},
},
'loggers': {
'django': {
'handlers': ['file'],
'level': 'DEBUG',
'propagate': True,
},
},
}
Login page html:
{% extends 'base.html' %}
{% block content %}
{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}
{% if next %}
{% if user.is_authenticated %}
<p>Your account doesn't have access to this page. To proceed,
please login with an account that has access.</p>
{% else %}
<p>Please login to see this page.</p>
{% endif %}
{% endif %}
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="login-panel panel panel-default">
<div class="panel-heading">
<!-- <h3 class="panel-title">Please Sign In</h3> -->
</div>
<div class="panel-body">
<form method="post" action="{% url 'login' %}">
{% csrf_token %}
<p class="bs-component">
<table>
<tr>
<td>{{ form.username.label_tag }}</td>
<td>{{ form.username }}</td>
</tr>
<tr>
<td>{{ form.password.label_tag }}</td>
<td>{{ form.password }}</td>
</tr>
</table>
</p>
<p class="bs-component">
<center>
<input class="btn btn-success btn-sm" type="submit" value="login" />
</center>
</p>
<input type="hidden" name="next" value="{{ next }}" />
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
{% block javascript %}
<script>
{% if not user.is_authenticated %}
$("ul.nav.navbar-nav.navbar-right").css("display","none");
{% endif %}
</script>
{% endblock %}
forms.py (from my app , appname -dsmdata)
#log/forms.py
from django.contrib.auth.forms import AuthenticationForm
from django import forms
# If you don't do this you cannot use Bootstrap CSS
class LoginForm(AuthenticationForm):
username = forms.CharField(label="Username", max_length=30,
widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'username'}))
password = forms.CharField(label="Password", max_length=30,
widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'password'}))
My custom authentication class derived from RemoterUserBackend class
from django.contrib.auth.models import User
from django.contrib.auth.backends import RemoteUserBackend
import logging
logger = logging.getLogger(__name__)
class pmauth(RemoteUserBackend):
def authenticate(self,request,username=None):
logger.debug("Inside authenticate")
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
# Create a new user. There's no need to set a password
# because only the password from settings.py is checked.
user = User(username=username)
user.is_staff = True
user.is_superuser = True
user.is_authenticated = True
# user.is_anonymous = abc.test
user.save()
return user
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
def configure_user(self,user):
"""Set user groups and privs.
This method is called the first time a non-django user logs in.
A user is created in the django database, this method
adds the new user to the appropriate groups, and
sets privs. """
#Add all remote users to a group
#user.groups.add(s.ALL_USERS_GROUP)
#all remote users are staff - so they can access the admin interface
user.is_staff=True
user.is_superuser=True
user.is_authenticated = True
user.is_anonymous = abc.test
logger.debug("Inside configure_user")
logger.debug(user.username)
#To determine if the user is to have further priviledges
#we consult LDAP
#connect to ldap server
# l = ldap.initialize(s.LDAP_SERVER)
#get list of superusers
# superusers=l.search_s(s.LDAP_SEARCH_TREE,\
# ldap.SCOPE_SUBTREE,\
# s.LDAP_FILTER)\
# [0][1][s.LDAP_FIELD]
#close LDAP Connection
# l.unbind()
#Check if this user should be a superuser.
# if user.username in superusers:
# user.is_superuser=True
#dsm.authenticate = true
user.save()
print("successfully saved the user")
return user
project(mysite) urls.py
"""mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/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
from django.urls import re_path
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from dsmdata.forms import LoginForm
from dsmdata.pmauth import pmauth
urlpatterns = [
#path('polls/', include('polls.urls')),
path('polls/', include('django.contrib.auth.urls')),
path('admin/', admin.site.urls),
re_path(r'', include('dsmdata.urls')),
url(r'^login/$', auth_views.LoginView.as_view() , {'template_name': 'login.html', 'authentication_form': LoginForm}, name="login" ),
#url(r'^login/$', pmauth , {'template_name': 'login.html', 'authentication_form': LoginForm}, name="login" ),
url(r'^logout/$', auth_views.LogoutView.as_view(), {'next_page': '/login'}),
#re_path(r'^dsm/',include('django.contrib.auth.urls')),
#re_path(r'^dsm/login', include('dsm.urls')),
]
dsmdata application views.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from pip._vendor.requests.api import request
# Create your views here.
# this login required decorator is to not allow to any
# view without authenticating
#login_required(login_url="login/")
def home(request):
return render(request,"home.html", testdict)
# Create your views here.
(first of all sorry for my bad english)
I'm trying to show a message in a UpdateView when the users save the changes!
This is my view
class NeedUpdateView(UpdateView):
model = Need
template_name = 'purchases/needs_update_form.html'
pk_url_kwarg = 'need_id'
success_message = 'List successfully saved!!!!'
fields = [
'detail',
]
When you save the app loads the same template! but i like to show a bootstrap alert if save the object!
This is code in the template to show the message
{% if messages %}
<div class="alert alert-success">
{% for m in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ m }}</li>
{% endfor %}
</div>
{% endif %}
and in the settings i add this
MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage'
But the i can't show the messages! The changes in the object are saving fine only need to show the message!
EDIT: i show here my settings to show that i follow all the steps in the docs
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
DJANGO_APPS = [
'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': [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',
'django.template.context_processors.i18n',
'apps.cart.context_processors.cart',
],
},
},
]
To enable the messages in class based views, you need to use the SuccessMessageMixin.
from django.contrib.messages.views import SuccessMessageMixin
class NeedUpdateView(SuccessMessageMixin, UpdateView):
...
success_message = 'List successfully saved!!!!'
You can also override the form_valid method like so:
from django.contrib import messages
from django.http import HttpResponseRedirect
class NeedUpdateView(UpdateView):
...
def form_valid(self, form):
messages.success(self.request, "This is my success message")
super().form_valid(form)
return HttpResponseRedirect(self.get_success_url())