Django authentication problem in HTML not working - python

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"),

Related

Program not save and update new data in Django

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>

NoReverseMatch at /login - error with LOGIN_URL or reverse function?

I am developing an app in Django.
I am developing users authentication.
I have a registration.html and a login.html templates inside path:
templates > authentication
Everything, including the registering function, works fine, but as I try to access to login template, the browser returns:
NoReverseMatch at /login
'app' is not a registered namespace
I bet the problem lies in the LOGIN_URL that I added in settings.py to enable authentication system (I am following a tutorial).
In fact, all the others view work fine, just the one pointing to login.html is not.
Here below are all my lines relating to the authentication system:
In my settings.py:
LOGIN_URL = '/login'
In my base.html:
{% if user.is_authenticated %}
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">{{ user_form.username }}</a>
<div class="dropdown-menu">
<a class="dropdown-item" href="">profilo</a>
<a class="dropdown-item" href="{% url 'logout' %}">Log out</a>
</div>
</li>
{% elif not user.is_authenticated %}
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">Login</a>
<div class="dropdown-menu">
<a class="dropdown-item" href="{% url 'registration' %}">Registrati</a>
<a class="dropdown-item" href="{% url 'login' %}">Accedi</a>
</div>
</li>
{% endif %}
In my authentication > login.html:
{% extends 'base.html'%} <!-- vuol dire inserisci qui la navigation toolbar contenuta in base -->
{% block content %}
<h1>Login</h1>
<br>
<div class="jumbotron">
<form action="{% url 'app:login' %}" method="post">
{% csrf_token %}
<label for="username">Username:</label>
<input type="text" name="username" value="" placeholder="nome utente">
<label for="password">Password:</label>
<input type="password" name="password" value="" placeholder="password">
<input type="submit" name="" value="Login">
</form>
</div>
{% load static %} <!-- Qui il tag è obbligatorio nonostante sia stato inserito dentro base.html -->
<!-- CSS -->
{% comment %} <link rel="stylesheet" type="text/css" href={% static "css/file.css" %}> {% endcomment %}
<!-- Javascript -->
{% comment %} <script type="text/javascript" src={% static "js/file.js" %}></script> {% endcomment %}
{% endblock %}
In my app > urls.py, Inside urlpatterns list:
path('authentication/registration', views_users_authentication.registration, name="registration"),
path('login', views_users_authentication.user_login, name="login"),
in my project > urls.py, Inside urlpatterns list:
path('admin/', admin.site.urls),
path('', include('app.urls')),
Then I have a separate sheet to contain views functions related to the authentication system, that is views_users_authentication.py , which contains:
def registration(request):
registered = False
# se l'utente ha lanciato il post
if request.method=="POST":
print("post eseguito!")
user_form = UserForm(data=request.POST)
profile_form = UserProfileInfoForm(data=request.POST)
# condizione di validità del form
if user_form.is_valid() and profile_form.is_valid():
print("form validi!")
user = user_form.save()
user.set_password(user.password) # questa linea hasha la pasword
user.save()
# registra l'utente
profile = profile_form.save(commit=False)
profile.user = user
registered=True
print("Utente registrato con successo!")
# condizione per registrare l'utente
if 'profile_pic' in request.FILES:
profile.profile_pic = request.FILES['profile_pic']
print("Acquisita la fotografia dell'utente!")
profile.save()
# attenzione al salvataggio dei form e dei modelli che sono due cose diverse
# registra le info aggiuntive
else:
print("Registrazione fallita:")
print(user_form.errors, profile_form.errors)
else:
user_form = UserForm()
profile_form = UserProfileInfoForm()
context_dict = {'user_form':user_form, 'profile_form':profile_form, 'registered':registered}
return render(request, 'authentication/registration.html', context_dict)
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('home'))
else:
HttpResponse("Account non attivo")
else:
print("qualcuno ha cercato di loggarsi e ha fallito")
print("Username: {} and password {}".format(username,password))
return HttpResponse("Inseriti parametri non validi per il login!")
else:
return render(request, "authentication/login.html", {})
In your login.html you should use just login as url name instead app:login:
<form action="{% url 'login' %}" method="post">
Since you didn't specify namespace in urlpatterns.py file. If you want to use app namespace you can change urlpatern like this:
path('', include('app.urls', namespace='app')),

AJAX GET Request Being Ignored

I am brand new to AJAX requests and I am still learning Django, but I have a project where the user enters an Elasticsearch query and then we generate a downloadable document (report) for the user.
I have an AJAX request to continuously check on the existence of a file in my form.html file and it doesn't seem to be getting picked up at all. I can tell this because it isn't giving me any alerts and it's just automatically timing out on big requests after ~30 seconds.
I tried to write a temporary fix in my views.py that is basically attempting to do what the javascript in form.html is doing, but A) I feel like this isn't the best method to use in production, B) it doesn't feel like a good use of time to essentially re-invent the wheel, and C) I want the user to get some sort of alert or indication on their end that the report is in progress, and then when it's ready to download.
How can I modify my code to actually perform the AJAX request? Or why does it appear that the AJAX request isn't working?
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/', include('django.contrib.auth.urls')),
path('form/', include('audit_tool.urls')),
path('report/', include('audit_tool.urls')),
path('check_progress/', views.check_progress, name='check_progress'),
# path('return_doc/', views.return_doc, name='return_doc'),
path('', TemplateView.as_view(template_name='home.html'), name='home'),
] + static(settings.STATIC_URL, document_root=settings.STAT)
audit_tool/urls.py
urlpatterns = [
path('', views.get_query, name='form'),
] + static(settings.STATIC_URL, document_root=settings.STAT)
views.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, JsonResponse, HttpResponseRedirect
from docx import Document
import os
import threading
from .forms import QueryForm
from .models import *
#login_required
def get_query(request):
if request.method == 'POST':
form = QueryForm(request.POST)
if form.is_valid():
query = form.cleaned_data["query"]
fn = str(time.time()).replace(".", "_") + ".docx"
t = threading.Thread(target=generate_doc, args=(query, fn))
t.start()
return HttpResponseRedirect('/check_progress/')
else:
return HttpResponse("Your query does not appear to be valid. Please enter a valid query and try again.")
else:
form = QueryForm()
return render(request, 'icm_audit_tool/form_template.html', {'form': form})
#login_required
def check_progress(request):
"""
Returns whether document generation is complete or in progress
"""
fn = request["filename"]
file = "/app/created_files/" + fn
while not os.path.exists(file):
time.sleep(10)
if os.path.exists(file):
doc = Document(file)
response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document')
response['Content-Disposition'] = 'attachment; filename={}'.format(fn)
doc.save(response)
return response
form.html
{% block javascript %}
<script>
var checkInterval = setInterval(isFileComplete, 10000); //10000 is 10 seconds
function isFileComplete() {
$.ajax({
url: '/check_progress/',
type: 'GET',
dataType: 'json',
success: function (data) {
if (data.file_created) {
alert("Your file is ready to download!");
clearInterval(checkInterval);
} else {
alert("Your report is still being created, please hold.");
checkInterval;
}
}
});
}
</script>
{% endblock %}
base_login.html
<!-- templates/base.html -->
<!DOCTYPE html>
<html>
<html lang="en">
{% load static %}
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}">
<link rel="shortcut icon" href="link/to/company/iconicon.ico" type="image/vnd.microsoft.icon" />
<title>Audit Report Tool</title>
</head>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="#">Dept</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="../">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="../admin">Admin</a>
</li>
</ul>
</div>
</nav>
<div class="container">
<div class="row justify-content-center">
<div class="col-8">
<hr class="mt-0 mb-4">
<img src="{% static "logo.png" %}" alt="Company Logo" align="left"></img>
<img src="{% static "logo.png" %}" alt="Dept Logo" align="right" width="140" height="140"></img>
<h1 align="center"><font size="6"> Audit Report Tool</font></h1>
</div>
</div>
</div>
<body>
<main>
{% block content %}
{% endblock %}
</main>
{% block javascript %}{% endblock %}
</body>
</html>

Django: NoReverse Match error and page not found

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.

How do i logout the user in the following django code?

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.

Categories