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 %}
Related
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
I created login and signup pages in Django. I am not able to login using that username and password which I set up during sign up. although I am able to login using superuser username and password. I checked that data of signup is going in database. but while I am trying to login it is showing 'Please enter a correct username and password. Note that both fields may be case-sensitive.'.
please help
models.py-
class userprofileinfo(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
phone = models.CharField(blank=False,max_length=10)
hotel_manager = models.BooleanField()
def __str__(self):
# Built-in attribute of django.contrib.auth.models.User !
return self.user.username
views.py-
def HomePage(request):
if request.user.is_authenticated:
print('.................................-')
print(request.user.email)
return render(request,'homepage.html')
else:
print('not online..........................')
return render(request,'homepage.html')
return render(request,'homepage.html')
def register(request):
registered = False
if request.method == 'POST':
user_form = UserCreateForm(data=request.POST)
profile_form = Formextends(data=request.POST)
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()
profile = profile_form.save(commit=False)
profile.user = user
profile.save()
registered = True
return redirect('/login/')
else:
print(user_form.errors,profile_form.errors)
else:
user_form = UserCreateForm()
profile_form = Formextends()
return render(request,'signup.html',
{'user_form':user_form,
'profile_form':profile_form,
'registered':registered})
forms.py-
class UserCreateForm(UserCreationForm):
class Meta:
fields = ("username","email","password1","password2")
# ,"phone","hotel_manager")
model = get_user_model()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["username"].label = "Display name"
self.fields["email"].label = "Email address"
class Formextends(forms.ModelForm):
class Meta():
model = userprofileinfo
fields = ("phone","hotel_manager")
settings.py-
"""
Django settings for Hotel_Booking_Portal project.
Generated by 'django-admin startproject' using Django 2.2.5.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/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__)))
TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')
# 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 = 'ok-r813k26$l9fi8a6w3s0udyc#5n#763e#k^(#5p88%h_kd%*'
# 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',
'firstapp.apps.FirstappConfig',
'bootstrap4',
]
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 = 'Hotel_Booking_Portal.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR],
'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 = 'Hotel_Booking_Portal.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
PASSWORD_HASHERS = [
'django.contrib.auth.hashers.Argon2PasswordHasher',
'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
'django.contrib.auth.hashers.BCryptPasswordHasher',
'django.contrib.auth.hashers.PBKDF2PasswordHasher',
'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
]
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
'OPTIONS':{'min_length':9}
},
{
'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
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
login.html-
<!DOCTYPE html>
{% extends 'base.html' %}
{% load bootstrap4 %}
{% block content %}
 
 
 
 
<div class="container">
<div class="jumbotron">
<h1>Login here</h1>
<form method="POST" class="form">
{% csrf_token %}
{% bootstrap_form form %}
{% buttons %}
<button type="submit" class="btn btn-primary">Login</button>
{% endbuttons %}
</form>
</div>
</div>
{% endblock %}
signup.html-
<!DOCTYPE html>
{% extends 'base.html' %}
{% load bootstrap4 %}
{% load bootstrap4 %}
{% block content %}
 
<div class="container">
<div class="jumbotron">
<h2>Create account</h2>
<form method="POST" class="form">
{% csrf_token %}
{% bootstrap_form user_form %}
{% bootstrap_form profile_form %}
<button type="submit" class="btn btn-primary">Sign Up</button>
</form>
</div>
</div>
{% endblock %}
The UserCreationForm [GitHub] will already set the password through .set_password(..). Indeed:
class UserCreationForm(forms.ModelForm):
# …
def save(self, commit=True):
user = super().save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
by doing this a second time in the view, you thus hash the hashed password. Therefore authentication will indeed not succeed. In the view, you can simply create the user with:
def register(request):
if request.method == 'POST':
user_form = UserCreateForm(data=request.POST)
profile_form = Formextends(data=request.POST)
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save()
profile = profile_form.save(commit=False)
profile.user = user
profile.save()
return redirect('/login/')
else:
print((user_form.errors,profile_form.errors))
else:
user_form = UserCreateForm()
profile_form = Formextends()
return render(
request,
'signup.html',
{'user_form': user_form,
'profile_form': profile_form,
'registered': False}
)
As a beginner, I am trying to skim through the Django documentation.
In order to allow a user to register, I want to create a register view.
Now, I have seen many examples on how to do this with a function-based view which passes the built-in UserCreationForm.
What I am trying to do is to take advantages of all the built-in views, so I was wondering if is possible to pass the UserCreationForm inside, let's say, the built-in FormView.
At the moment I have managed to render the form at the required URL, but once submitted, it doesn't create the user even though it redirects me to the home page (as wanted).
How can I fix this?
Here is my views.py
from django.shortcuts import render
from django.contrib.auth.forms import UserCreationForm
from django.views.generic.edit import FormView
class RegisterView(FormView):
template_name = 'registration/register.html'
form_class = UserCreationForm
success_url = '/home/'
And here my html
{% block content %}
<form method="post" action="{% url 'home' %}">
{% csrf_token %}
<table>
<tr>
<td>{{ form.username.label_tag }}</td>
<td>{{ form.username }}</td>
</tr>
<tr>
<td>{{ form.password1.label_tag }}</td>
<td>{{ form.password1 }}</td>
<td>{{ form.password2.label_tag }}</td>
<td>{{ form.password2 }}</td>
</tr>
</table>
<input type="submit" value="Register">
</form>
{% endblock %}
If it can be of any use, this are my settings:
"""
Django settings for my_project project.
Generated by 'django-admin startproject' using Django 2.2.7.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/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__)))
# 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',
]
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/'
Ok, I have managed to make this work.
Basically my original code was right, the only thing I had to change was the model form which the RegisterView I have defined inherits.
It doesn't work as a subclass of the FormView but has to be a subclass of the CreateView.
If someone could explain to me why in the comments that would be helpful :)
The answer I have found comes from here.
ps. Also, I had to reverse_lazy the successful URL.
#Mirko Oricci,
You did not save the form values to db. That's why it redirects to the success_url without saving the data.
You need to save it. So you should use form_valid method to save the form values.
from django.shortcuts import render
from django.contrib.auth.forms import UserCreationForm
from django.views.generic.edit import FormView
class RegisterView(FormView):
template_name = 'registration/register.html'
form_class = UserCreationForm
success_url = '/home/'
def form_valid(self, form):
form.save() // form data will be saved
return super(RegisterView, self).form_valid(form)
Please change the registration.html form action
{% block content %}
{% if form.errors %} {% for field in form %} {% for error in field.errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %} {% endfor %}{% endif %}
<form method="post" action="{% url 'register' %}">
{% csrf_token %}
<table>
<tr>
<td>{{ form.username.label_tag }}</td>
<td>{{ form.username }}</td>
</tr>
<tr>
<td>{{ form.password1.label_tag }}</td>
<td>{{ form.password1 }}</td>
<td>{{ form.password2.label_tag }}</td>
<td>{{ form.password2 }}</td>
</tr>
</table>
<input type="submit" value="Register" />
</form>
{% endblock %}
in urls.py create a router path:
from django.urls import path, include
from .views import RegisterView
urlpatterns = [
path('', RegisterView.as_view(), name='register')
]
I have checked and also i am getting the new user in admin panel.
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 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.