django request.POST is None - django

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

Related

Why edit is not working even code is correct

when I click on update, it is not updating. I don't know what to do. Everything is working except edit.
views.py:
def addnew(request):
if request.method == "POST":
form = BookForm(request.POST)
if form.is_valid():
try:
form.save()
return redirect('/')
except:
pass
else:
form = BookForm()
return render(request,'book/index.html',{'form':form})
def index(request):
books = Book.objects.all()
return render(request,"book/show.html",{'books':books})
def edit(request, id):
book = Book.objects.get(id=id)
return render(request,'book/edit.html',{'book':book})
def update(request, id):
book = Book.objects.get(id=id)
form = BookForm(request.POST,instance=book)
if form.is_valid():
form.save()
return redirect('/')
return render(request,'book/edit.html',{'book': book})
def destroy(request, id):
book = Book.objects.get(id=id)
book.delete()
return redirect("/")
urls.py:
from django.contrib import admin
from django.urls import path
from book import views
urlpatterns = [
path('admin/', admin.site.urls),
path('',views.index,name='index'),
path('addnew',views.addnew),
path('edit/<int:id>',views.edit),
path('update/<int:id>',views.update),
path('delete/<int:id>',views.destroy),
]
templates/books:
edit.html:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap4.min.js"></script>
</head>
<body>
{% block content %}
<div class="col-md-12">
<form method="post" class="post-form" action="/update/{{ book.id }}">
{% csrf_token %}
<div class="container">
<br>
<div class="form-group row">
<label class="col-sm-1 col-form-label"></label>
<div class="col-sm-4">
<h3>Update Details</h3>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Book Id:</label>
<div class="col-sm-4">
<input type="text" class="form-control" name="id" id="id_id" required maxlength="20" value="{{book.id}}"/>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Book Name:</label>
<div class="col-sm-4">
<input type="text" class="form-control" name="name" id="id_name" required maxlength="100" value="{{book.book_name}}" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-1 col-form-label"></label>
<div class="col-sm-4">
<button type="submit" class="btn btn-success btn-lg">Update</button>
</div>
</div>
</div>
</form>
{% endblock content %}
</body>
</html>
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap4.min.js"></script>
</head>
<body>
{% block content %}
<div class="col-md-12">
<form method="post" class="post-form" action="/addnew">
{% csrf_token %}
<div class="container">
<br>
<div class="form-group row">
<label class="col-sm-1 col-form-label"></label>
<div class="col-sm-4">
<!-- <h3>Enter Details</h3> -->
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Book Name:</label>
<div class="col-sm-4">
{{ form.book_name }}
</div>
</div>
<div class="form-group row">
<label class="col-sm-1 col-form-label"></label>
<div class="col-sm-4">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</div>
</form>
</div>
{% endblock content %}
</body>
</html>
show.html:
{% block content %}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap4.min.js"></script>
</head>
<body>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<h4>Book Records</h4> <span>Add New Book</span>
<br>
<div class="table-responsive">
<table id="bootstrapdatatable" class="table table-striped table-bordered" width="90%">
<thead>
<th><input type="checkbox" id="checkall" /></th>
<th>ID</th>
<th>Book Name</th>
<th>Edit</th>
<th>Delete</th>
</thead>
<tbody>
{% for book in books %}
<tr>
<td><input type="checkbox" class="checkthis" /></td>
<td>{{ book.id }}</td>
<td>{{ book.book_name }}</td>
<td><span style="color:brown;" class="glyphicon glyphicon-pencil"></span></p></td>
<td><span style="color:brown;" class="glyphicon glyphicon-trash"></span></p></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
<script>
$(document).ready(function() {
$('#bootstrapdatatable').DataTable({
"aLengthMenu": [[3, 5, 10, 25, -1], [3, 5, 10, 25, "All"]],
"iDisplayLength": 3
}
);
} );
</script>
</body>
</body>
</html>
{% endblock content %}
Here, edit is not working. when I click on update, it is not updating. I don't know what to do. Everything is working except edit.
please anyone tell me what to do.
I have tried several times.
forms.py:
from django import forms
from book.models import Book
class BookForm(forms.ModelForm):
class Meta:
model = Book
fields = ['book_name']
widgets = { 'book_name': forms.TextInput(attrs={ 'class': 'form-control' })}
models.py:
from django.db import models
# Create your models here.
class Book(models.Model):
book_name = models.CharField(max_length=100)
class Meta:
db_table = "book"
The template of your form is wrong. Pay attention that your form is waiting for you to send it a field called book_name:
class BookForm(forms.ModelForm):
class Meta:
model = Book
fields = ['book_name']
widgets = { 'book_name': forms.TextInput(attrs={ 'class': 'form-control' })}
However, in the template you are sending it the id field and a field called name:
<input type="text" class="form-control" name="id" id="id_id" required maxlength="20" value="{{book.id}}"/>
<input type="text" class="form-control" name="name" id="id_name" required maxlength="100" value="{{book.book_name}}" />
So, according your forms.py, you must to change the template like this:
<form method="post" class="post-form" action="/update/{{ book.id }}">
{% csrf_token %}
<div class="container">
<br>
<div class="form-group row">
<label class="col-sm-1 col-form-label"></label>
<div class="col-sm-4">
<h3>Update Details</h3>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Book Name:</label>
<div class="col-sm-4">
<input type="text" class="form-control" name="book_name" id="id_book_name" required maxlength="100" value="{{book.book_name}}" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-1 col-form-label"></label>
<div class="col-sm-4">
<button type="submit" class="btn btn-success btn-lg">Update</button>
</div>
</div>
</div>
BTW, you could simplify all of this, using the power of Django like this:
<form method="post" class="post-form" action="/update/{{ book.id }}">
{% csrf_token %}
{{ form }}
<button type="submit" class="btn btn-success btn-lg">Update</button>
</form>
You should study the way in witch Django builds forms: https://docs.djangoproject.com/en/dev/topics/forms/

Django - If i put 2 formsets together in my view, the function to add multiple times the same views doesnt work

I have this code bellow. Im using formset to add multiple times the same form. But if i put this 2 formsets together, like in my view, just the first data for each form is saved. And if i put just 1 formset in my def, it works, all datas for i put to the form is saved. Someone have any idea why this is happening? (sorry for my eng)
Forms.py
class InsereIdioma(forms.ModelForm):
class Meta:
model = Idioma
fields = '__all__'
exclude = ['usuario']
InsereIdiomaFormset = formset_factory(InsereIdioma, extra=1)
class InsereTecnologia(forms.ModelForm):
class Meta:
model = Tecnologia
fields = '__all__'
exclude = ['usuario']
InsereTecnologiaFormset = formset_factory(InsereTecnologia, extra=1)
Views.py
def cadastro_curriculo(request):
if request.method == 'GET':
formset_idioma = InsereIdiomaFormset(request.GET or None)
formset_tecnologia = InsereTecnologiaFormset(request.GET or None)
elif request.method == 'POST':
formset_idioma = InsereIdiomaFormset(request.POST)
formset_tecnologia = InsereTecnologiaFormset(request.POST)
if formset_idioma.is_valid():
for form in formset_idioma:
idioma = form.cleaned_data.get('idioma')
fluencia = form.cleaned_data.get('fluencia')
if idioma and fluencia:
Idioma(
idioma=idioma,
fluencia=fluencia,
usuario=request.user
).save()
if formset_tecnologia.is_valid():
for form in formset_tecnologia:
sistema = form.cleaned_data.get('sistema')
nivel = form.cleaned_data.get('nivel')
if sistema and nivel:
Tecnologia(
sistema=sistema,
nivel=nivel,
usuario=request.user
).save()
return render(request, "personal/curriculo.html", {
'formset_idioma': formset_idioma,
'formset_tecnologia': formset_tecnologia,})
template
<div class="card" style="margin-bottom: 25px;">
<div class="card-header" id="headingFour">
<h5 class="mb-0">Idiomas</h5>
</div>
{{ formset_idioma.management_form }}
<div class="content-inside" id="form_set_idioma">
{% for form in formset_idioma %}
{{form.non_field_errors}}
{{form.errors}}
<table class='no_error'>{{ form }}</table>
{% endfor %}
</div>
<input class="btn btn-primary fixedbutton" type="button" value="Adicionar" id="add_form_set_idioma">
<div id="empty_form_set_idioma" style="display:none">
<table class='no_error'>{{ formset_idioma.empty_form }}<br></table>
</div>
</div>
<div class="card" style="margin-bottom: 25px;">
<div class="card-header" id="headingFive">
<h5 class="mb-0">Tecnologia</h5>
</div>
{{ formset_tecnologia.management_form }}
<div class="content-inside" id="form_set_tecnologia">
{% for form in formset_tecnologia %}
{{form.non_field_errors}}
{{form.errors}}
<table class='no_error'>{{ form }}</table>
{% endfor %}
</div>
<input class="btn btn-primary fixedbutton" type="button" value="Adicionar" id="add_form_set_tecnologia">
<div id="empty_form_set_tecnologia" style="display:none">
<table class='no_error'>{{ formset_tecnologia.empty_form }}<br</table>
</div>
</div>
<script type='text/javascript'>
$('#add_form_set_idioma').click(function(){
var form_set_idioma_index = $('#id_form-TOTAL_FORMS').val(); $('#form_set_idioma').append($('#empty_form_set_idioma').html().replace(/__prefix__/g, form_set_idioma_index));
$('#id_form-TOTAL_FORMS').val(parseInt(form_set_idioma_index) + 1);});
$('#add_form_set_tecnologia').click(function(){
var form_set_tecnologia_index = $('#id_form-TOTAL_FORMS').val(); $('#form_set_tecnologia').append($('#empty_form_set_tecnologia').html().replace(/__prefix__/g, form_set_tecnologia_index));
$('#id_form-TOTAL_FORMS').val(parseInt(form_set_tecnologia_index) + 1);});
</script>
https://i.stack.imgur.com/vhjvX.png
Based on what #Daniel said, I've made some changes to your code and it's working just fine for me.
def cadastro_curriculo(request):
if request.method == 'GET':
formset_idioma = InsereIdiomaFormset(request.GET or None, prefix='idiomas')
formset_tecnologia = InsereTecnologiaFormset(request.GET or None, prefix='tecnologias')
elif request.method == 'POST':
formset_idioma = InsereIdiomaFormset(request.POST, prefix='idiomas')
formset_tecnologia = InsereTecnologiaFormset(request.POST, prefix='tecnologias')
if formset_idioma.is_valid():
for form in formset_idioma:
idioma = form.cleaned_data.get('idioma')
fluencia = form.cleaned_data.get('fluencia')
if idioma and fluencia:
Idioma(
idioma=idioma,
fluencia=fluencia,
usuario=request.user
).save()
if formset_tecnologia.is_valid():
for form in formset_tecnologia:
sistema = form.cleaned_data.get('sistema')
nivel = form.cleaned_data.get('nivel')
if sistema and nivel:
Tecnologia(
sistema=sistema,
nivel=nivel,
usuario=request.user
).save()
return render(request, "image_app/curriculo.html", {
'formset_idioma': formset_idioma,
'formset_tecnologia': formset_tecnologia})
template
<!DOCTYPE html>
<html lang="en">
<head>
<title>Student</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
<form id="curriculo_form" method="post">
{% csrf_token %}
<button id="submitButton" class="btn btn-primary" type="submit">Salvar</button>
<div class="card" style="margin-bottom: 25px;">
<div class="card-header" id="headingFour">
<h5 class="mb-0">Idiomas</h5>
</div>
{{ formset_idioma.management_form }}
<div class="content-inside" id="form_set_idioma">
{% for form in formset_idioma %}
{{form.non_field_errors}}
{{form.errors}}
<table class='no_error'>{{ form }}</table>
{% endfor %}
</div>
<input class="btn btn-primary fixedbutton" type="button" value="Adicionar" id="add_form_set_idioma">
<div id="empty_form_set_idioma" style="display:none">
<table class='no_error'>{{ formset_idioma.empty_form }}<br></table>
</div>
</div>
<div class="card" style="margin-bottom: 25px;">
<div class="card-header" id="headingFive">
<h5 class="mb-0">Tecnologia</h5>
</div>
{{ formset_tecnologia.management_form }}
<div class="content-inside" id="form_set_tecnologia">
{% for form in formset_tecnologia %}
{{form.non_field_errors}}
{{form.errors}}
<table class='no_error'>{{ form }}</table>
{% endfor %}
</div>
<input class="btn btn-primary fixedbutton" type="button" value="Adicionar" id="add_form_set_tecnologia">
<div id="empty_form_set_tecnologia" style="display:none">
<table class='no_error'>{{ formset_tecnologia.empty_form }}<br</table>
</div>
</div>
</form>
</body>
</html>
JS
<script type='text/javascript'>
$('#add_form_set_idioma').click(function(){
var form_set_idioma_index = $('#id_idiomas-TOTAL_FORMS').val();
$('#form_set_idioma').append($('#empty_form_set_idioma').html().replace(/__prefix__/g, form_set_idioma_index));
$('#id_idiomas-TOTAL_FORMS').val(parseInt(form_set_idioma_index) + 1);});
$('#add_form_set_tecnologia').click(function(){
var form_set_tecnologia_index = $('#id_tecnologias-TOTAL_FORMS').val();
$('#form_set_tecnologia').append($('#empty_form_set_tecnologia').html().replace(/__prefix__/g, form_set_tecnologia_index));
$('#id_tecnologias-TOTAL_FORMS').val(parseInt(form_set_tecnologia_index) + 1);
});
</script>

Django - Is_authenticated method works only on one view

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 %}

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.

Django custom login form HttpResponseRedirect not working

When my login is successful, I'm either getting redirected to the /login page or HttpResponseRedirect is not working. I want the user upon clicking submit with a successful email and password be redirected to my /successful_login page. Where am I missing something?
views.py
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect
from customauth.forms import RegistrationForm
def login_user(request):
form = RegistrationForm()
logout(request) #logs out user upon reaching the /login/ page
email = password = ''
if request.POST:
form = RegistrationForm(request.POST)
user = authenticate(email=email, password=password)
if user is not None:
if user.is_active:
login(request, user)
return HttpResponseRedirect('/successful_login/')
else:
state = "Your account is not active, please contact the administrator."
else:
state = "Your email and/or password were incorrect."
state = "Please log in below..."
context = RequestContext(request, {
'state': state,
'email': email,
'form': form,
})
return render_to_response('customauth/login.html', {}, context)
#login_required(login_url='/login/')
def successful_login(request):
return render_to_response('customauth/successful_login.html');
forms.py
from django import forms
class RegistrationForm(forms.Form):
email = forms.EmailField(widget=forms.TextInput(attrs={'placeholder':'Email'}))
password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder':'Password'}))
login.html
{% load widget_tweaks %}
<html>
<head>
<title>Login</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'customauth/style.css' %}">
</head>
<body>
<div class="container">
<div id="loginbox" class="mainbox col-md-6 col-md-offset-3 col-sm-6 col-sm-offset-3">
<!--<div class="row">
<div class="iconmelon">
<object type="image/svg+xml" data="customauth/static/customauth/barbell.svg">Your browser does not support SVG</object>
</div>
</div>-->
<div class="panel panel-default" >
<div class="panel-heading">
<div class="panel-title text-center"><b>DATA STRONG</b></div>
</div>
<div class="panel-body" >
{% if form.errors %}
<p>Invalid email or password! Please try again.</p>
{% endif %}
<form name="form" id="form" class="form-horizontal" method="POST">
{% csrf_token %}
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
{{ form.email|add_class:"form-control" }}
</div>
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
{{ form.password|add_class:"form-control" }}
</div>
<div class="input-group checkbox">
<label><input name="remember" type="checkbox">Remember me</label>
</div>
<div class="form-group">
<!-- Button -->
<div class="col-sm-12 controls">
<button type="submit" class="btn btn-primary pull-right" value="{{ next }}"><i class="glyphicon glyphicon-log-in"></i>Log in</button>
</div>
</div>
</form>
</div> <!-----END OF BOOTSTAP CONTAINER----->
</div>
</div>
</div>
</body>
</html>
You need to extract the mail and password from the form, before doing the authentication, otherwise both values will be "".
This can be done the following way:
email = form.cleaned_data['email']
password = form.cleaned_data['password']
user = authenticate(email=email, password=password)