I've gotten the NoReverse Match error before and I got it to work with a blind guess. and page not found I've always been able to fix so I'm really not sure what is going on.
As far as I can tell everything should be working correctly, and I even compared this code to a previous project and it looks fine (I have been tinkering with it so it may not be exactly what I originally typed in).
base.html
<!DOCTYPE html>
{% load staticfiles %}
<html lang="en">
<head>
<title>Evverest</title>
<meta name"viewport" content="width=device-width, initial-scale=1">
<meta charset="uft-8">
<link rel="shortcut icon" href="/images/favicon.ico">
<link rel="stylesheet" href="{% static 'css/style.css' %}">
</head>
<body>
<nav>
<div class="container">
<a class="brand" href="{% url 'index' %}">Evverest</a>
<div class="navbar">
<a class="nav-link btn" href="{% url 'index' %}">Home</a>
{% if user.is_authenticated %}
<a class="nav-link" href="{% url 'users:user-profile' %}">New Color Set</a>
<a class="nav-link" href="{% url 'users:user_logout' %}">Logout</a>
{% else %}
<a class="nav-link" href="{% url 'users:user_login' %}">Login</a>
<a class="nav-link" href="{% url 'users:register' %}">Register</a>
{% endif %}
</div>
</div>
</nav>
<div class="container">
{% block content %}
{% endblock %}
</div>
</body>
</html>
app views.py
from django.shortcuts import render
from users.forms import UserForm,UserProfileForm
from users.models import UserProfileInfo
from django.contrib.auth import authenticate,login,logout
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import (TemplateView,ListView,
DetailView,CreateView,
UpdateView,DeleteView)
# Create your views here.
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(reverse('index'))
else:
return HttpResponse("Account now active")
else:
print("Login Unsuccessful")
return HttpResponse("Username and/or password are not correct")
else:
return render(request,'login.html',{})
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 'profile_pic' in request.FILES:
profile.profile_pic = request.FILES['profile_pic']
profile.save()
registered = True
else:
print(user_form.errors,profile_form.errors)
else:
user_form = UserForm()
profile_form = UserProfileForm()
return render(request,'register.html',{
'user_form':user_form,
'profile_form':profile_form,
'registered':registered
})
#login_required
def user_logout(request):
logout(request)
return HttpResponseRedirect(reverse('login'))
class HomeView(ListView):
model = UserProfileInfo
ordering = ['-join_date']
class UserProfileView(DetailView):
model = UserProfileInfo
class UserEditProfileView(LoginRequiredMixin,UpdateView):
login_url = '/login/'
redirect_field_name = '/users_detail.html'
form_class = UserProfileForm
model = UserProfileInfo
Project urls.py
from django.conf.urls import url
from django.contrib import admin
from django.conf.urls import include
from users import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$',views.HomeView.as_view(),name='index'),
url(r'^users/',include('users.urls',namespace='users')),
]
app urls.py
from django.conf.urls import url
from users import views
app_name = 'users'
urlpatterns = [
url(r'^login/$',views.user_login,name='user_login'),
url(r'^logout/$',views.user_logout,name='user_logout',kwargs={'next_page':'/'}),
url(r'^register/$',views.register,name='register'),
url(r'(?P<username>\d+)/$',views.UserProfileView.as_view(),name='user-profile'),
url(r'(?P<username>\d+)/edit$',views.UserEditProfileView.as_view(),name='user-profile-edit'),
]
file structure:
EDIT
Here is the traceback:
As you see in your urls.py:
url(r'(?P<username>\d+)/$',views.UserProfileView.as_view(),name='user-profile')
Your user-profile url takes one parameter, which is username. But in your template you do not pass it:
<a class="nav-link" href="{% url 'users:user-profile' %}">New Color Set</a>
So Django does not know which username to pass and this causes NoReverseMatch.
You just need to to pass the username to the url:
<a class="nav-link" href="{% url 'users:user-profile' username=user.username %}">New Color Set</a>
Figured it out: The problem come up because in another template (which I didn't post because I didn't realize it had any effect on this) I didn't put in the namespace users
Here is that other template:
{% extends "base.html" %}
{% block content %}
<div class="form-base">
<h2>Login</h2>
<form action="{% url 'users:user_login' %}" method="POST">
{% csrf_token %}
<label for="username">Username: </label>
<input type="text" class="login-input" name="username" placeholder="Enter Username" />
<label for="password">Password: </label>
<input type="password" class="login-input" name="password" />
<input type="submit" name="" value="Login" />
</form>
</div>
{% endblock %}
Thank you for the help everyone.
Related
I create program stock management system by using Django. Page of Update_items that create for saving and updating. Program can running but when I will update new data it can't save and update data. It will redirect with same data. I'm not sure whatit's wrong. I am very new so please introduce me.
This is from views.py
from email import header
from multiprocessing import context
from urllib import request
from django.shortcuts import render,redirect
import stockmgmt
from .models import Stock
from .forms import StocksearchForm,StockCreateForm,StockUpdateForm
def home(request):
title = 'ยินดีต้อนรับเข้าสู่ระบบสต็อคสินค้าเซียงกง'
form = 'Welcome: This is the Home Page'
context = {
"title": title,
"test": form,
}
return render(request, "home.html",context)
def list_items(request):
title = 'รายการสินค้า'
form = StocksearchForm(request.POST or None)
queryset = Stock.objects.all()
context = {
"title": title,
"queryset": queryset,
"form":form
}
if request.method == 'POST':
queryset = Stock.objects.filter(category__icontains=form['category'].value(),item_name__icontains=form['item_name'].value(),id_product__icontains=form['id_product'].value(),shop_name__icontains=form['shop_name'].value())
context ={
"form":form,
"header": header,
"queryset": queryset,
}
return render(request, "list_items.html",context)
def add_items(request):
form=StockCreateForm(request.POST or None)
if form.is_valid():
form.save()
return redirect('/list_items')
context={
"form":form,
"title":"Add Item",
}
return render(request,"add_items.html",context)
def update_items(request, pk):
queryset = Stock.objects.get(id=pk)
form = StockUpdateForm(instance=queryset)
if request.method == ' POST':
form = StockUpdateForm (request.POST, instance=queryset)
if form.is_valid():
form.save()
return redirect('/list_items')
context = {
'form':form
}
return render(request, 'add_items.html', context)
This is list_items.html
{% load static %}
{% load crispy_forms_tags %}
<!DOCTYPE html>
<body>
</body>
</html>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="/docs/4.0/assets/img/favicons/favicon.ico">
<title>รายการสินค้า</title>
<link rel="canonical" href="https://getbootstrap.com/docs/4.0/examples/navbar-top-fixed/">
<!-- Bootstrap core CSS -->
<link href ="../../dist/css/bootstrap.min.css" rel ="stylesheet">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<!-- Custom styles for this template -->
<link href="navbar-top-fixed.css" rel="stylesheet">
</head>
<body>
<nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
<a class="navbar-brand" href="#">สต็อคสินค้าร้านเซียงกง</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarCollapse">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="/">หน้าแรก <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="/list_items">รายการสินค้า</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/add_items">เพิ่มรายการสินค้า</a>
</li>
</ul>
<form class="form-inline mt-2 mt-md-0">
<input class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</nav>
<main role="main" class="container">
<div class="jumbotron">
<h1>รายการสินค้า</h1>
<form method='POST' action=''>{% csrf_token %}
{{form|crispy}}
<input type="submit" value='Search'/>
</form>
<br>
<table class='table'>
<thead>
<tr>
<th>รายการสินค้า</th>
<th>ประเภทสินค้า</th>
<th>ชื่อสินค้า</th>
<th>รหัสสินค้า</th>
<th>ชื่อร้าน</th>
<th>ราคา/หน่วย</th>
<th>จำนวนที่มีอยู่ในร้าน</th>
</tr>
</thead>
{% for instance in queryset %}
<tr>
<td>{{forloop.counter}}</td>
<td>{{instance.category}}</td>
<td>{{instance.item_name}}</td>
<td>{{instance.id_product}}</td>
<td>{{instance.shop_name}}</td>
<td>{{instance.price}}</td>
<td>{{instance.quantity}}</td>
</tr>
{% endfor %}
</table>
</div>
</main>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
</body>
</html>
This is url.py
"""djangoproject URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from stockmgmt import views
urlpatterns = [
path('', views.home, name='home'),
path('list_items/', views.list_items, name='list_items'),
path('add_items/', views.add_items, name='add_items'),
path('update_items/<str:pk>/', views.update_items, name="update_items"),
path('admin/', admin.site.urls)
]
This is my error in command promopt
In forms.py
from django import forms
from .models import Stock
# Create your forms here
class StockForm(forms.Form):
class Meta:
model = Stock
# incase you want all fields
fields = '__all__'
In views.py
from .forms import StockForm
from .models import Stock
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.contrib import messages
def update_entry(request, pk):
try:
queryset = Stock.objects.get(id=pk)
except Stock.DoesNotExist:
messages.error(request, "The request entry does not exist.")
# Redirect back some page incase of invalid pk
return HttpResponseRedirect(reverse("app2:listing"))
# Populate the form with old data
form = StockForm(instance=qs)
context = {"form": form}
# When method is post
if request.method == "POST":
# Populate the form with newly posted data
form = StockForm(request.POST, instance=qs)
# Checking data validity in form
if form.is_valid():
form.save()
# Always use HttpResponseRedirect after successfull post request
return HttpResponseRedirect(reverse("some-url-name"))
# When form is not valid re-render page
else:
messages.error(request, "Invalid form received.")
# Update form in context dictionary
context["form"] = form
return render(request, "update-stock.html", context)
# When method is not post
else:
return render(request, "update-stock.html", context)
In update-stock.html
<div class="container-fluid">
<!-- Loop over messages rendered from views -->
{% for message in messages %}
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<strong>{{ message }}</strong>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
{% endfor %}
<form method="post" action="" class="row g-1">
{% csrf_token %}
{{ form }}
<input type="submit" class="btn btn-primary">
</form>
</div>
I am trying to setup user login in the header, that way, the user can login/logout at any point in the web. However I must have missunderstood the Django tutorials. I am kind of a newbie with Django and I am not entirely sure of how to accomplish this, so any help is welcome.
I would like to clarify also, that I do not wish to redirect to another template. If possible, just reload the current page with the user already authenticated.
I tried 2 things:
add action="{% url 'sign_in' %}" in the header form
add action="{% url 'accounts_login' %}" in the header form
And neither seems to work.
My app name is 'web'
My project name is 'core'
# core/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('auth/', include('django.contrib.auth.urls')),
path('rest/', include('rest_framework.urls')),
path('', include('web.urls'))
]
# web/urls.py
from django.contrib.auth.views import LoginView
from django.urls import path
from . import views
urlpatterns = [
path('', views.base),
path('sign_in', views.sign_in, name='sign_in'),
path('accounts/login/', LoginView.as_view(template_name='base.html'), name='accounts_login')
]
# wev/views.py
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.template import loader
from django.contrib.auth import authenticate, login, logout
import requests
def base(request):
context = {
'user': request.user
}
return render(request, 'base.html', context)
def sign_in(request):
if request.POST:
email = request.POST.get('email')
password = request.POST.get('password')
user = authenticate(request, email=email, password=password)
if user is not None and user.is_active:
print(user)
login(request, user)
return base(request)
return base(request)
<!-- base.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<header>
{% include 'header.html' %}
</header>
<main>
{% block main %}
Main content
{% endblock %}
</main>
<footer>
{% include 'footer.html' %}
</footer>
</body>
</html>
<!-- header.html -->
<!-- I am using bootstrap so i removed all extra divs an classes for readibility -->
<nav>
<ul>
<li>Home</li>
<li>Link</li>
</ul>
<div>
{% if user.is_authenticated %}
<p>Welcome, {{ user.username }}!</p>
<button>Sign out</button>
{% else %}
<button>Sign up</button>
<button>Sign in</button>
{% endif %}
</div>
</nav>
<div id="bootstrapModal">
<form method="POST" action="{% url 'accounts_login' %}">
{% csrf_token %}
{{ form.as_p }}
<div>
<h5>Sign in</h5>
<button type="button" aria-label="Close"></button>
</div>
<div>
<div>
<label>Email address</label>
<input name="email" type="email" placeholder="Email address">
</div>
<div >
<label>Password</label>
<input name="password type="password" placeholder="Password" ">
</div>
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
</div>
I wrote a small application for a social media site and I have a problem. I'm using {% if user.is_authenticated %} after I log in I'm getting the options in the navbar which should not be displayed for an authenticated user. The page keeps bouncing between two pages. I have made a video of the problem. Please have a look at it.
Video.
Files tree image:
File tree
base.html
<!DOCTYPE html>
{% load static %}
<html >
<head>
<title>Colab</title>
<link rel="stylesheet" type="text/css" href="{% static 'reg_sign_in_out/style.css' %}">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="#">Colab</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<div class="navbar-nav">
{% if user.is_authenticated %}
<a class="nav-item nav-link" href="{% url 'posts:home' %}">Home</a>
<a class="nav-item nav-link" href="{% url 'logout' %}">Logout</a>
{%else%}
<a class="nav-item nav-link active" href="{% url 'index' %}">Home <span class="sr-only">(current)</span></a>
<a class="nav-item nav-link" href="{% url 'reg_sign_in_out:user_login' %}">Login</a>
<a class="nav-item nav-link" href="{% url 'reg_sign_in_out:registration' %}">Register</a>
{% endif %}
<!-- <a class="nav-item nav-link disabled" href="#">Disabled</a> -->
</div>
</div>
</nav>
<div class="container">
{% block body_block %}
{% endblock body_block %}
</div>
</body>
</html>
posts/urls.py
app_name = "posts"
urlpatterns = [
path('home/',views.home,name='home'),
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
reg_sign_in_out/urls.py
app_name = "reg_sign_in_out"
urlpatterns = [
path('user_login/',views.user_login,name='user_login'),
path('registration/',views.registration,name="registration"),
]
project_colab/urls.py (main)
urlpatterns = [
path('',views.index,name="index"),
path('',include('reg_sign_in_out.urls'),name="reg_sign_in_out"),
path('',include('posts.urls'),name="posts"),
path('admin/', admin.site.urls),
path('logout/',views.user_logout,name='logout'),
path('special/',views.special,name='special'),
]
posts/views.py
def home(request):
post_creation = forms.PostsForm()
if request.method == "POST":
# name = request.POST.get('name')
# time = timezone.now()
# post_text = request.POST.get('post_text')
# temp = Posts(name=name,time=time,post_text=post_text)
# temp.save()
post_creation = forms.PostsForm(request.POST,request.FILES)
if post_creation.is_valid():
post_creation.save()
postx = Posts.objects.all()
return render(request,"posts/index.html",context={"post_info":postx,
"user":post_creation})
reg_sign_in_out/views.py
def index(request):
return render(request,"index.html")
#login_required
def special(request):
return HttpResponse("In!")
#login_required
def user_logout(request):
logout(request)
return HttpResponseRedirect(reverse('index'))
#csrf_protect
def registration(request):
registered = False
if request.method == "POST":
form = forms.UserForm(request.POST)
profileform = forms.RegistrationForm(request.POST,request.FILES)
if form.is_valid() and profileform.is_valid():
user = form.save()
print(user)
user.set_password(user.password)
user.save()
profile = profileform.save(commit=False)
profile.user = user
profile.save()
registered = True
else:
print(form.errors,profileform.errors)
return render(request,"reg_sign_in_out/registration.html",{"tried":"True",
"registered":registered,
"profile_form":profileform,
"user_form":form,
})
else:
user = forms.UserForm()
profileform = forms.RegistrationForm()
return render(request,"reg_sign_in_out/registration.html",{"registered":registered,
"profile_form":profileform,
"user_form":user,
})
#csrf_protect
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(reverse('index'))
else:
return render(request,"reg_sign_in_out/login.html",{'tried':'True'})
else:
return render(request,"reg_sign_in_out/login.html")
I think the error in your file project_colab/urls.py (main) because you execute the function at the main of the project so, it affects whole the project so, I think you have to remove the function from urls.py in the main project and instead, try to put as following:
path('',include("index.urls")),
and in the posts/urls.py file you can put the function you has created and the path will be:
path('',views.index,name="index"),
so i'm working on little django application where users can view and modify there profile ,but i didn't know how to provide a button under the profile picture that allows the user to choose a new one and when he chooses it redirect him to the same page with the new profile picture ,any help or ideas will be usefull , tnks !!
here's what i tried :
forms.py
class picture_form(forms.ModelForm):
class Meta:
model=Profile
fields=('image',)
views.py
def profile(request):
if request.method == 'POST':
form = picture_form(request.POST, request.FILES)
if form.is_valid():
profile = Profile.objects.get(user=request.user)
profile.image = form.cleaned_data['image']
profile.save()
return redirect(reverse('profile'))
else:
for usr in User.objects.all():
if request.user.get_full_name() == usr.get_full_name():
prf = Profile.objects.filter(user=usr)
form = picture_form()
return render(request, 'store/profile.html', {'profile': prf, 'form': form})
template
{% if prf.image %}
<div class="profile-img">
<img src="{{ prf.image.url }}" id="prf_img" alt=""/>
</div>
{% else %}
<div class="profile-img">
<img src="{% static 'img/empty-profile-picture.png' %}" id="prf_img" alt=""/>
</div>
{% endif %}
<!--<a href="{% url 'upload_picture' %}"> <div class="file btn btn-lg " >
Change Photo
<input type="file" name="file"/>
</div></a> -->
<form method="post" action="{% url 'profile' %}" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" class="btn btn-outline-success" value="upload">
</form>
</div>
Django has an awesome generic editing view called UpdateView. You can do something like this:
models.py
class Profile(models.Model):
image = models.ImageField()
views.py
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views.generic.edit import UpdateView
#method_decorator(login_required, name='dispatch')
class UpdateProfileView(UpdateView):
model = Profile
fields = ['image']
template_name_suffix = '_update_form'
success_url = ''
def form_valid(self, form):
form.instance.user = self.request.user
return super().form_valid(form)
profile_update_form.html
<form method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Update">
</form>
urls.py
from . import views
path('<int:pk>/update/', views.UpdateProfileView.as_view(), name='profile-update')
What I am trying to do:
I am trying to log out the user whenever he/she clicks on the logout button.
What problem I am getting:
I get the following problem when I click on logout button:
My Code:-
article.html:
<div class="container">
<nav class="nav blog-nav">
<a class="nav-link" href="#">Library</a>
{% if user.is_authenticated %}
<a style="float: right;" class="nav-link" href="{% url 'librarysystem:Logout' %}">Logout</a>
<a style="float: right;" class="nav-link" href="#">{{ request.user.username }}</a>
{% if user.UserProfile.avatar == None %}
<a style="float: right;" class="nav-link" href="#"><img class="img-thumbnail" src="/static/defaultPic/defaultPic.png" class="img-responsive" alt = "Generic placeholder thumbnail"/></a>
{% else %}
<a style="float: right;" class="nav-link" href="#" class="thumbnail"><img class="thumbnail" src="{{ request.user.UserProfile.avatar }}" class="img-responsive"/></a>
{% endif %}
{% endif %}
</nav>
</div>
login View:
def loginUser(request):
data = {}
if request.method == "POST":
username = request.POST.get('username')
password = request.POST.get('password')
data['responseMessage'] = ''
user = authenticate(username=username,password=password);
if user is None:
data['response'] = False
else:
if user.is_active:
data['responseMessage'] = 'Already logged in.'
else:
login(request,user)
data['redirectTo'] = "/librarysystem/article/"
data['response'] = True
return JsonResponse(data)
logout View:
def logoutUser(request):
logout(request)
template = 'librarysystem/Elib.html'
return render(request, template)
urls.py:
from django.conf.urls import url
from .import views
urlpatterns = [
url(r'^register/$',views.registerUser),
url(r'^$', views.index, name="Index"),
url(r'^validateRegisterForm/$',views.validateRegisterForm),
url(r'^validateLoginForm/$',views.validateLoginForm),
url(r'^article/$', views.article, name="Article"),
url(r'^Login/$',views.loginUser, name="Login"),
url(r'^Logout/$',views.logoutUser, name="Logout"),
]
As the error log suggested:
global name 'logout' is not defined
You need to first import logout from django.contrib.auth.
Use this:
from django.contrib.auth import logout
Like this:
from django.contrib.auth import logout
def logoutUser(request):
logout(request)
template = 'librarysystem/Elib.html'
return render(request, template)
# Redirect to a success page.