Django - Is_authenticated method works only on one view - django

I have a following problem. In login.html I added {% If user.is_authenticated %} and there everything work. I also added this in navbar.html and home.html, but there it doesn't work, and I don't know why.
This is my views.py
def index(request):
return render(request, 'website/home.html', {'user': user_panel})
def register(request):
registered = False
if request.method =='POST':
user_form = UserForm(data=request.POST)
profile_form = UserProfileForm(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
if 'picture' in request.FILES:
profile.picture = request.FILES['picture']
profile.save()
registered = True
else:
print (user_form.errors, profile_form.errors)
else:
user_form = UserForm()
profile_form = UserProfileForm()
return render(request, 'website/register.html', {
'user_form': user_form,
'profile_form': profile_form,
'registered': registered})
def auth_login(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user:
if user.is_active:
login(request, user)
return HttpResponseRedirect(reverse('index'))
else:
return HttpResponse("Konto jest nieaktywne")
else:
print ("Invalid login details: {0}, {1}".format(username, password))
return HttpResponse("Invalid login details supplied.")
else:
return render(request, 'website/login.html', {})
basic.html
{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Bootstrap 101 Template</title>
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}" type = "text/css"/>
<link rel="stylesheet" href="{% static 'css/style.css' %}" type = "text/css"/>
<link href='https://fonts.googleapis.com/css?family=Ubuntu' rel='stylesheet' type='text/css'>
</head>
<body>
{% include 'website/navbar.html' %}
{% block body_block %}
{% endblock %}
</body>
</html>
home.html
{% extends 'website/basic.html' %}
{% block body_block %}
{% load staticfiles %}
<div class="container-full-bg" style="background-image:url('{% static 'images/website/jumbotron-website.PNG' %}');" height="100%">
<div class="jumbotron" style="background: transparent">
<div class="container" style="margin-top: 6em"><h1>Agencja Reklamy FUX</h1>
<p>Nasza Agencja to firma z ponad dwudziestoletnią tradycją. Zajmujemy się głównie wielkoformatową
reklamą zewnętrzną, dającą niemalże nieograniczone możliwości przekazu.</p></div>
{% if user.is_authenticated %}
Hello {{ user.username }}
{% else %}
You are not loggin in
{% endif %}
</div>
</div>
{% endblock %}
navbar.html
{% load staticfiles %}
<nav class="navbar navbar-inverse navbar-fixed-top" style="background-color: #363636;">
<div class="container-fluid">
<div class = "container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<a class="navbar-brand" style="padding: 0em"><img src="{% static 'images/website/logo.png' %}"></img></a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li class="active">Home <span class="sr-only">(current)</span></li>
<li>O Firmie</li>
<li>Oferta</li>
<li>Klienci</li>
<li>Praca</li>
<li>Kontakt</li>
{% if user.is_authenticated %}
<li>Wyloguj się</li>
{% else %}
<li>Zaloguj się</li>
{% endif %}
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</div>
</nav>
login.html
{% extends 'website/basic.html' %}
{% block body_block %}
<div class="container" style="margin-top: 8rem">
{% if not user.is_authenticated %}
<form id="login_form" method="post" action="/login/">
{% csrf_token %}
<div class="form-group" style="padding-right: 80rem">
<label for="username">Username</label>
<input type="text" class="form-control" name="username" size="60" />
</div>
<div class="form-group" style="padding-right: 80rem">
<label for="username">Password</label>
<input type="password" class="form-control" name="password" size="60" />
</div>
<div class="form-group" style="padding-right: 80rem">
<button type="submit" class="btn btn-default" value="submit">Submit</button>
</div>
</form>
{% else %}
You are logged! {{ user.username }}
{% endif %}
</div>
{% endblock %}

Related

Flask.flash messages not available through extended template

I am having trouble with sending flashed messages to a route that extends its layout from another template. This message shows up just fine if use the message in the layout.html which makes me believe that rendering login.html first will render layout.html and use the flashed message there and not pass it to my /login route. How are you able to call this message in an extended template? I am using the jijna with syntax taken from here to be able to have the message variable available within my mainblock. Flask's documentation does not specify this either.
app.py
#app.route("/login", methods=["POST", "GET"])
def login():
# Forget any previous user
if session.get("user_id"):
session.pop("user_id")
if request.method == "POST":
# Create connection cursor
cursor = mysql.connection.cursor()
# Query database for email
cursor.execute("SELECT id, email, password FROM users WHERE email = %s", [request.form.get("email")])
row = cursor.fetchone()
print(row)
if row is None:
print("WHY")
flash("Invaid user")
return redirect("login")
My layout.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hoook - {% block title %}{% endblock %}</title>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0, width=device-width">
<link href="/static/favicon-16x16.png" rel="icon">
<link href="/static/style.css" rel="stylesheet">
<!-- Scripts -->
<script src="https://kit.fontawesome.com/542c2d099e.js" crossorigin="anonymous"></script>
<script src="/static/mainJS.js"></script>
</head>
<body>
<div class="page-wrapper">
<header>
<nav class="main-navbar">
{% if request.path == "/login" %}
<div class="navbar-container login-container">
{% else %}
<div class="navbar-container">
{% endif %}
<div>
{% if request.path == "/login" %}
<img src="/static/hoook_logo_blue.png" alt="Hoook Logo" height="50" width="150">
{% else %}
<img src="/static/hoook_logo.png" alt="Hoook Logo" height="50" width="150">
{% endif %}
</div>
{% if request.path != "/login" %}
<div>
{% if session["user_id"] %}
{# change nav bar for logged in users #}
{% else %}
{# work on this nav bar for unlogged in users #}
{% if request.path == "/signup" %}
<a class="navbar-link" href="/login">Sign in</a>
{% endif %}
{% endif %}
</div>
{% endif %}
</div>
</nav>
</header>
</div>
<main>
{% if request.path == "/login" %}
<div class="top-container signup-container">
{% else %}
<div class="top-container">
{% endif %}
{% with messages = get_flashed_messages() %}
{% block main %}{% endblock %}
{% endwith %}
</div>
</main>
<footer>
</footer>
</body>
</html>
My login.html
{% extends "layout.html" %}
{% block title %}
Login
{% endblock %}
{% block main %}
<div class="login-div">
<div>
<h1 class="color-control">Sign in to Hoook</h1>
</div>
<div class="login-input-bx">
<form action="/login" method="post" autocomplete="off">
<div class="form-control login-form-control">
<label class="login-label color-control" for="email">Email address</label>
<input class="login-input" type="text" name="email" id="email" required autofocus>
</div>
<div class="form-control login-form-control">
<label class="login-label color-control" for="password">Password</label>
<input class="login-input" type="password" name="password" id="password" required readonly onfocus="this.removeAttribute('readonly')">
</div>
<button class="btn btn-login" type="submit">Sign in</button>
</form>
</div>
{% if messages %}
{% for msg in messages %}
<div class="flashed-messages-div">
<p class="signup-para" id="login-flashed-messages">Error: {{ msg }}</p>
</div>
{% endfor %}
{% endif %}
<div class="signup-link-div">
<p class="color-control signup-login-font">New to Hoook? <a class="signup-link-anchor" href="/signup">Create an account</a>.</p>
</div>
</div>
{% endblock %}
Update
I guess I could do something like make_response instead as seen here. and just use:
response = make_response(render_template("login.html", message = "Invalid user"), 302)
return response
However I am curious if there is a way to pass the flashed message through instead.
I have had the same issue. Instead of:
return redirect("login")
try with:
return render_template("login.html")
The flashed message works that way for me.

'str' object has no attribute 'socialaccount_set' django allauth

I am trying to change my function based views to class based views
I have this profile view as function based:
#verified_email_required
#login_required
def profile(request, username):
if request.method == 'POST':
u_form = UserUpdateForm(request.POST, instance=request.user)
p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)
if u_form.is_valid and p_form.is_valid():
u_form.save()
p_form.save()
message = messages.success(request, f'Your profile has been updated')
return redirect('profile', username=username)
else:
u_form = UserUpdateForm(instance=request.user)
p_form = ProfileUpdateForm(instance=request.user.profile)
try:
profile = User.objects.get(username=username)
except User.DoesNotExist:
message = messages.warning(request,f'Profile not found for {username}')
return redirect('home')
profile = ''
all_post_by_user = Log.objects.filter(author__username=username)
context = {
'u_form' : u_form,
'p_form' : p_form,
'profile' : profile,
'all_post_by_user' : all_post_by_user
}
return render(request, 'users/profile.html', context)
And this is my class based for the same :
class ProfileDetailView(DetailView):
model = Profile
template_name = "users/profile.html"
context_object_name = 'profile'
def get_object(self):
username = self.kwargs.get('username')
view_profile = Profile.objects.get(user__username=username)
So, I am getting this error:
profile.html:
{% extends 'log/base.html' %}
{% block content %}
{% load socialaccount %}
{% get_social_accounts profile as accounts %}
{%load crispy_forms_tags %}
<title>Error logger - Profile {{ profile.username }}</title>
<div id='profile' class="content-section card p-4">
<div class="media">
{% if profile.username == user.username %}
{% if accounts %}
<img class='rounded-circle account-img' src="{{ profile.socialaccount_set.all.0.get_avatar_url }}" />
{% else %}
<img class="rounded-circle account-img" src="{{ profile.profile.avatar.url }}">
{% endif %}
{% else %}
{% if accounts %}
<img class='rounded-circle account-img' src="{{ profile.socialaccount_set.all.0.get_avatar_url }}" />
{% else %}
<img class="rounded-circle account-img" src="{{ profile.profile.avatar.url }}">
{% endif %}
{% endif %}
<div class="media-body">
<h2 class="account-heading">{{profile.username}}</h2>
<p >{{profile.email}}</p>
<p>Created on: {{ profile.profile.created }}</p>
{% if profile.username == user.username %}
<p>Last updated on : {{ profile.profile.updated }}</p>
{% endif %}
</div>
</div>
<!-- FORM HERE -->
{% if profile.username == user.username %}
<form method='POST' autocomplete="off" enctype="multipart/form-data" >
{% csrf_token %}
<fieldset class='form-group'>
<legend class='border-bottom mb-4'>Update Profile</legend>
{{ u_form | crispy }}
{{ p_form | crispy }}
</fieldset>
<div class='form-group'>
<button class='btn btn-outline-info' type='submit'>Update</button>
</div>
</form>
{% endif %}
<div class="container border-top mt-4 pt-4">
<legend>Posts</legend>
{% for i in all_post_by_user %}
<div id="you-want-lazyload" data-lazyload="<p>Anything you want to lazyload</p>" class='m-4'>
<div class="container main m-4" style="width: 50vw;">
<a class='link' href="{% url 'log-detail' i.slug %}"><h2 >{{ i.title }}</h2></a>
<p>{{ i.content }}</p>
<p class='small'>{{ i.created }}</p>
</div>
</div>
{% endfor %}
</div>
</div>
{% endblock content %}
How to solve the error that I am getting?
I am using django allauth for social login with google
Also can someone explain why I have to query it is user__username=username?
Thanks
Ok, so the error tells us that you've got a string somewhere you aren't expecting it, because you're trying to access an attribute of a variable that is provided by allauth.
This is happening due to your exception handling here;
try:
profile = User.objects.get(username=username)
except User.DoesNotExist:
message = messages.warning(request, f'Profile not found for {username}')
return redirect('home')
profile = ''
If a user doesn't exist, you set profile to an empty string and that gets passed in the context.
So I'd change this a little bit, to fix this error and also to avoid the confusion of looking up User objects and calling them profile (I'd assume a User to be called user or similar)
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
message = messages.warning(request, f'User not found for {username}')
return redirect('home')
user = None
all_post_by_user = Log.objects.filter(author__username=username)
context = {
'u_form' : u_form,
'p_form' : p_form,
'user' : user,
'all_post_by_user' : all_post_by_user
}
return render(request, 'users/profile.html', context)
profile.html:
{% extends 'log/base.html' %}
{% load crispy_forms_tags socialaccount %}
{% block content %}
{% get_social_accounts profile as accounts %}
<title>Error logger - Profile {{ profile.username }}</title>
<div id='profile' class="content-section card p-4">
<div class="media">
{% if profile and profile.username == user.username %}
{% if accounts %}
<img class='rounded-circle account-img' src="{{ profile.socialaccount_set.all.0.get_avatar_url }}" />
{% else %}
<img class="rounded-circle account-img" src="{{ profile.profile.avatar.url }}">
{% endif %}
{% else %}
{% if accounts and profile %}
<img class='rounded-circle account-img' src="{{ profile.socialaccount_set.all.0.get_avatar_url }}" />
{% elif profile %}
<img class="rounded-circle account-img" src="{{ profile.profile.avatar.url }}">
{% endif %}
{% endif %}
{% if profile %}
<div class="media-body">
<h2 class="account-heading">{{profile.username}}</h2>
<p >{{profile.email}}</p>
<p>Created on: {{ profile.profile.created }}</p>
{% if profile.username == user.username %}
<p>Last updated on : {{ profile.profile.updated }}</p>
{% endif %}
</div>
</div>
<!-- FORM HERE -->
{% if profile.username == user.username %}
<form method='POST' autocomplete="off" enctype="multipart/form-data" >
{% csrf_token %}
<fieldset class='form-group'>
<legend class='border-bottom mb-4'>Update Profile</legend>
{{ u_form | crispy }}
{{ p_form | crispy }}
</fieldset>
<div class='form-group'>
<button class='btn btn-outline-info' type='submit'>Update</button>
</div>
</form>
{% endif %} <!-- end username check -->
{% endif %} <!-- end profile check -->
<div class="container border-top mt-4 pt-4">
<legend>Posts</legend>
{% for i in all_post_by_user %}
<div id="you-want-lazyload" data-lazyload="<p>Anything you want to lazyload</p>" class='m-4'>
<div class="container main m-4" style="width: 50vw;">
<a class='link' href="{% url 'log-detail' i.slug %}"><h2 >{{ i.title }}</h2></a>
<p>{{ i.content }}</p>
<p class='small'>{{ i.created }}</p>
</div>
</div>
{% endfor %}
</div>
</div>
{% endblock content %}

Django form not submitting or providing error messages

When I submit my form, it doesn't post the form data and just reloads the form.
It was working beforehand but I'm not sure what I've changed that doesn't make it work anymore. Posting the data through the admin still works fine.
The only 'error' message I can see is in the terminal:
which can be seen here
It sends a get request instead of a post request as well. I've also tested it with removing the JS and bootstrap CDNs but the issue is still the same.
My code is below:
Here is my views.py
def create(request):
if request.method == 'POST':
form = EventCreateForm(request.POST, request.FILES)
if form.is_valid():.
instance = form.save(commit=False)
instance.author = request.user
instance.save()
instance.save_m2m()
return redirect('event:home')
else:
form = EventCreateForm()
return render(request, 'event/create.html', {'form': form})
create.html
{% extends "base.html" %}
{% load crispy_forms_tags %}
{% block content %}
{{ form.media }}
<div class="container-fluid">
<div class="col-md-4">
<div class="page-header">
<p> Create an event!</p>
</div>
<form method="post" action="" enctype="multipart/form-data">
{% csrf_token %}
{{ form | crispy}}
<button type="submit">Submit</button>
<br>
<br>
</form>
</div>
</div>
{% endblock %}
Base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://code.jquery.com/jquery-3.2.1.min.js" crossorigin="anonymous" integrity="sha384-xBuQ/xzmlsLoJpyjoggmTEz8OWUFM0/RC5BsqQBDX2v5cMvDHcMakNTNrHIW2I5f"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" crossorigin="anonymous" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" crossorigin="anonymous" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'event/css/custom.css' %}">
<title>Django Project</title>
</br>
<div class="container-fluid" style='font-family:arial'>
<center>
<h2> Welcome to the django website!</h2>
</center>
</div>
{{ form.media }}
</head>
<!-- body of the text -->
<body>
{% if messages %}
{% for messages in messages %}
{{ message }}
{% endfor %}
{% endif %}
{% if user.is_authenticated %}
<nav class="navbar navbar-expand-md navbar-dark bg-dark sticky-top">
<div class="navbar-nav">
<a class="nav item nav-link active" href="{% url 'event:home' %}">Home</a>
<a class="nav item nav-link" href="{% url 'profiles:profile' %}">Profile</a>
<a class="nav item nav-link" href="{% url 'profiles:edit' %}">Edit profile</a>
<a class="nav item nav-link" href="{% url 'event:create' %}">Create</a>
<a class="nav item nav-link" href="{% url 'profiles:logout' %}">Logout</a>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search">
<button class="btn btn-success" type="submit">Search</button>
</div>
{% else %}
Login
Register
{% endif %}
</nav>
{% block content %}
{% endblock %}
</body>
</html>
Models.py
class Event(models.Model):
title = models.CharField(max_length=100)
link = models.TextField()
author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
image = models.ImageField(default='default.jpg', upload_to='event_images')
image_thumbnail = ImageSpecField(source='image',
processors=[ResizeToFill(100, 100)],
format='JPEG',
options={'quality': 60})
start = models.DateField(blank=True, null=True)
start_time = models.TimeField(blank=True, null=True)
end = models.DateField(blank=True, null=True)
end_time = models.TimeField(blank=True, null= True)
description = HTMLField('description')
tags = models.ManyToManyField(Tags)
subject = models.ManyToManyField(Subject)
attendees = models.ManyToManyField(User, related_name = 'attendees', blank=True)
def __str__(self):
return f'{self.title}'
def get_absolute_url(self):
return reverse('event:detail', kwargs={'pk': self.pk})
Thanks everyone in advance,
All help will be greatly appreciated!
You may have deleted your action. Try adding the url back?
<form method="post" action="{% url "event:create" %}" enctype="multipart/form-data">
I had a problem like this too. I solved it by getting rid of a div tag containing a bootstrap class (<div class="form-group>" to be more precise) located around my form.
same problem existed for me also , the silly mistake you have done is the button thing in your create.html file , replace that with input tap with type submit and class btn , button doesn't submit request
Try this :
<input type="submit" class="btn btn-primary" value="Submit">
i know its bit late but this may seem helpful

django request.POST is None

This is views.py
class RegisterView(View):
def get(self,request):
register_form = RegisterForm()
return render(request,'register.html',{'register_form':register_form})
def post(self,request):
register_form = RegisterForm(request.POST)
if register_form.is_valid():
pass
class LoginView(View):
def get(self,request):
return render(request,'login.html',{})
def post(self,request):
login_form = LoginForm(request.POST)
if login_form.is_valid():
user_name = request.POST.get("username", '')
pass_word = request.POST.get("password", '')
user = authenticate(username=user_name, password=pass_word)
if user is not None:
login(request, user)
return render(request, 'index.html')
else:
return render(request, 'login.html', {"msg": "User name or password error!"})
else:
return render(request, 'login.html', {'login':login_form})
Why does register_form = RegisterForm(request.POST) and login_form = LoginForm(request.POST) return empty,I tried many ways to solve it but failed, so how should I write it?
this is forms.py
from django import forms
from captcha.fields import CaptchaField
class LoginForm(forms.Form):
username = forms.CharField(required=True)
password = forms.CharField(required=True, min_length=5)
class RegisterForm(forms.Form):
email = forms.EmailField(required=True)
password = forms.CharField(required=True,min_length=5)
captcha = CaptchaField(error_messages={"invalid":'captcha is error'})
this is login.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" >
<title>mxonline</title>
<link rel="stylesheet" type="text/css" href="/static/css/reset.css">
<link rel="stylesheet" type="text/css" href="/static/css/login.css">
</head>
<body>
<div class="dialog" id="jsDialog">
<div class="successbox dialogbox" id="jsSuccessTips">
<h1>successful</h1>
<div class="close jsCloseDialog"><img src="/static/images/dig_close.png"/></div>
<div class="cont">
<h2>submit successful!</h2>
<p></p>
</div>
</div>
<div class="noactivebox dialogbox" id="jsUnactiveForm" >
<h1>Email verification prompt</h1>
<div class="close jsCloseDialog"><img src="/static/images/dig_close.png"/></div>
<div class="center">
<img src="/static/images/send.png"/>
<p>We have already sent your email to you<span class="green" id="jsEmailToActive">12#13.com</span>Send email, <br/> to ensure your account security, please check email in time</p>
<p class="a"><a class="btn" id="jsGoToEmail" target="_blank" href="http://mail.qq.com">Check the mailbox</a></p>
<p class="zy_success upmove"></p>
<p style="display: none;" class="sendE2">You can check your spam and the filtered message, and you can send it again(<span class="c5c">60s</span>)</p>
<p class="sendE">You can check your spam and filtered emails,<br/>Can also be<span class="c5c green" id="jsSenEmailAgin" style="cursor: pointer;">Send the validation email again</span></p>
</div>
</div>
</div>
<div class="bg" id="dialogBg"></div>
<header>
<div class="c-box fff-box">
<div class="wp header-box">
<p class="fl hd-tips">mxonlie</p>
<ul class="fr hd-bar">
<li>tel:<span>33333333</span></li>
<li class="active">[login]</li>
<li>[registration]</li>
</ul>
</div>
</div>
</header>
<section>
<div class="c-box bg-box">
<div class="login-box clearfix">
<div class="hd-login clearfix">
<a class="index-logo" href="index.html"></a>
<h1>login</h1>
<a class="index-font" href="index.html">index</a>
</div>
<div class="fl slide">
<div class="imgslide">
<ul class="imgs">
<li><img width="483" height="472" src="/static/images/mysql.jpg" /></li>
<li><img width="483" height="472" src="/static/images/mysql.jpg" /></li>
<li><img width="483" height="472" src="/static/images/mysql.jpg" /></li>
</ul>
</div>
<div class="unslider-arrow prev"></div>
<div class="unslider-arrow next"></div>
</div>
<div class="fl form-box">
<h2>login</h2>
<form action="/login/" method="post" autocomplete="off">
<input type='hidden' name='csrfmiddlewaretoken' value='mymQDzHWl2REXIfPMg2mJaLqDfaS1sD5' />
<div class="form-group marb20 {% if login_form.errors.username %}errorput{% endif %}">
<label> username&nbsp</label>
<input name="username" id="account_l" type="text" placeholder="Mobile phone number/mailbox" />
</div>
<div class="form-group marb8 {% if login_form.errors.username %}errorput{% endif %}">
<label>password</label>
<input name="password" id="password_l" type="password" placeholder="Please enter your password" />
</div>
<div class="error btns login-form-tips" id="jsLoginTips">{% for key,error in login_form.errors.items %}{{ error }}{% endfor %}{{ msg }}</div>
<div class="auto-box marb38">
<a class="fr" href="forgetpwd.html">Forget password?</a>
</div>
<input class="btn btn-green" id="jsLoginBtn" type="submit" value="Login immediately > " />
{# <input type='hidden' name='csrfmiddlewaretoken' value='5I2SlleZJOMUX9QbwYLUIAOshdrdpRcy' />#}
{% csrf_token %}
</form>
<p class="form-p">No online account?[Register now]</p>
</div>
</div>
</div>
</section>
<script src="/static/js/jquery.min.js" type="text/javascript"></script>
<script src="/static/js/unslider.js" type="text/javascript"></script>
<script src="/static/js/login.js" type="text/javascript"></script>
</body>
</html>
The question of register_form = RegisterForm (request.post) has been resolved, but login_form = login_form = LoginForm (request.post) is still empty,so I just uploaded login.html

Django Login form error message

I've created login form for my Django project, and I have a problem with the error message.
This is my function in views.py:
def user_login(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user:
if user.is_active:
login(request, user)
return HttpResponseRedirect('/friends_plans/users/')
else:
return HttpResponse("Your account is disabled")
else:
print "Invalid login details: {0}, {1}".format(username, password)
return HttpResponse("Invalid login details supplied.")
else:
return render(request, 'friends_plans/index.html', {})
The error message ("Invalid login details supplied") appears on a new blank page. Could you please tell me how to show this message if username or password is incorrect on the same login page (index.html)?
This is my template index.html:
{% load staticfiles %}
<html >
<head >
<title> Friends' Plans </title>
<meta charset ="utf -8" />
<link rel="stylesheet" href="{% static 'css/friends_plans.css' %}">
</head >
<body >
<div id ="container">
<div id ="header">
<ul id ="menu">
<span><a id="firstbutton" href ="" >Friends' Plans</a> </span>
<span><a id="helpbutton" href ="" >HELP</a></span>
</ul>
</div>
<div id ="left">
<form id="login_form" method="post" action="">
{% csrf_token %}
Username: <input type ="text" name ="username" value="" size="50" /> <br />
Password: <input type ="password" name ="password" value="" size="50"/> <br />
<input type ="submit" value="submit" />
</form>
{% if user.is_authenticated %}
Logout
{% else %}
Register here<br />
{% endif %}
</div>
<div id ="right">
<h1 id="welcome">Welcome to Friends' Plans</h1>
<img class="cat" src={% static 'images/cat4.jpg' %} />
<img class="cat" src={% static 'images/cat2.jpg' %} />
<img class="cat" src={% static 'images/cat3.jpg' %} />
<img class="cat" src={% static 'images/cat6.jpg' %} />
<img class="cat" src={% static 'images/cat5.jpg' %} />
<img class="cat" src={% static 'images/cat1.jpg' %} />
</div>
<div id ="footer"> Copyright </div>
</div>
</body>
</html>
I had an idea to set a variable error=False and to change if for error=Trueif form.is_valid() is False, and to write {% if error %} in the template, but there was a mistake about csrf_token although there is {% csrf_token %} in the template.
In views.py:
def login_process(request):
try:
user = authenticate(username = request.POST['username'],
password = request.POST['password'])
except KeyError:
return render(request, 'friends_plans/index.html',{
'login_message' : 'Fill in all fields',})
if user is not None:
#'User' and 'Pass' right
if user.is_active:
login(request, user)
else:
return render(request, 'friends_plans/index.html',{
'login_message' : 'The user has been removed',})
else:
return render(request, 'friends_plans/index.html',{
'login_message' : 'Enter the username and password correctly',})
return HttpResponseRedirect('/friends_plans/users/')
In index.html:
{% load staticfiles %}
<html >
<head >
<title> Friends' Plans </title>
<meta charset ="utf -8" />
<link rel="stylesheet" href="{% static 'css/friends_plans.css' %}">
</head >
<body >
<div id ="container">
<div id ="header">
<ul id ="menu">
<span><a id="firstbutton" href ="" >Friends' Plans</a> </span>
<span><a id="helpbutton" href ="" >HELP</a></span>
</ul>
</div>
<div id ="left">
<form id="login_form" method="post" action="">
<div class="add_your_styles">
{{ login_message }}
</div>
{% csrf_token %}
Username: <input type ="text" name ="username" value="" size="50" /> <br />
Password: <input type ="password" name ="password" value="" size="50"/> <br />
<input type ="submit" value="submit" />
</form>
{% if user.is_authenticated %}
Logout
{% else %}
Register here<br />
{% endif %}
</div>
<div id ="right">
<h1 id="welcome">Welcome to Friends' Plans</h1>
<img class="cat" src={% static 'images/cat4.jpg' %} />
<img class="cat" src={% static 'images/cat2.jpg' %} />
<img class="cat" src={% static 'images/cat3.jpg' %} />
<img class="cat" src={% static 'images/cat6.jpg' %} />
<img class="cat" src={% static 'images/cat5.jpg' %} />
<img class="cat" src={% static 'images/cat1.jpg' %} />
</div>
<div id ="footer"> Copyright </div>
</div>
</body>
</html>
You can place {{ login message }} anywhere. It's just a text string.
For something like this, you can uses Django's message framework.
In you imports, add line
from django.contrib import messages
This will make messages framework available to you, now you want to add error messages for this failed login request, so all you have to do is
messages.error(request, 'Invalid login credentials').
Next, on failed attempt render the same login page. In your login template, you will have variable messages available, which is basically list of message that you have sent from views. You can iterate over it and show it on same page.