Django redirect not working in authentication - django

I am trying to authenticate a registered user . redirect is not working in my case. after clicking the login button it keep on showing the login page again. i want the user to go to home page upon the successful login. Here are my files.
views.py
from django.shortcuts import render, redirect
from django.http import HttpResponseRedirect
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
def register_new_a(request):
saved = False
if request.method == "POST":
# take whatever is posted to the Details Form
form = DetailsForm(request.POST)
if form.is_valid():
form.save()
messages.success(request, 'Your account details have been saved!')
return HttpResponseRedirect('/register_new_a?saved=True')
else:
form = DetailsForm()
if 'saved' in request.GET: # sends saved var in GET request
saved = True
return render(request, 'register1.html', {'form': form, 'saved': saved})
def loginUser(request):
if request.method == "POST":
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
# at backend authenticated the credentials
login(request, user)
return redirect('home') # not working
return render(request, 'login_a.html')
urls.py
from django.contrib import admin
from django.urls import path
from home import views
urlpatterns = [
path("", views.index, name='home'),
path("login", views.loginUser, name='login'),
path("logout", views.logoutUser, name='logout'),
#path("register", views.register, name='register'),
path("register_new_a", views.register_new_a, name='register_new_a'),
path("register_new_b", views.register_new_b, name='register_new_b'),
path("about", views.about, name='about'),
]
login_a.html
{% extends 'base.html'%}
{% block title %}Login{% endblock title %}
{% block body %}
<div class="container my-3" >
<h1 class="display-3" align="center">Login Here</h1>
<br>
<h1 class="display-6" >STEP 1: </h1>
<form method="post" action="">
{% csrf_token %}
<div class="mb-3">
<label for="Username1" class="form-label" >Username </label>
<input type="username"class="form-control" name="username"></input>
</div>
<div class="mb-3">
<label for="Password1" class="form-label">Password</label>
<input type="password" class="form-control" id="Password1" name="password">
</div>
New user? Register Here
<button type="submit" class="btn btn-primary float-end" style="background: #0a9396" > Next</button>
</form>
</div>
{% endblock body %}
Any help would be appreciated.

Related

How to use Django-simple-captcha on the admin login page?

I would like to add captcha on my django login form using Django Simple Captcha found here: http://code.google.com/p/django-simple-captcha/
This works great if you create a new form but I'm using the django.contrib.auth.forms the one that comes with django. Any idea how I might be able to implement captcha with the existing django auth views or any ways? Thank you!
Please do not suggest using Google reCaptcha.
My urls.py
from django.contrib.auth import views as auth_views
urlpatterns = [
path('login/', auth_views.LoginView.as_view(template_name='login.html'), name='login')
,...
]
My login.html
<form class="fadeIn second" method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-primary"> Login </button>
</form>
My Forms.py
from captcha.fields import CaptchaField
class MyFormCaptcha(forms.Form):
captcha = CaptchaField()
This video and this GitHub project solved my problem. You can customize the project code according to your needs. For me it is as follows.
My urls.py
urlpatterns = [
...
path('captcha/',include('captcha.urls')),
path('submit',submit,name='submit')
]
My forms.py
from captcha.fields import CaptchaField
class MyForm(forms.Form):
captcha=CaptchaField()
My login.html
<form action="/submit" method="post">
{% csrf_token %}
<div>
<label for="fullname">Full Name</label>
<input type="text" id="fullname" name="fullname">
</div>
<br>
<div>
<label for="email">Email</label>
<input type="text" id="email" name="email">
</div> <br>
{{form.captcha}}
<button type="submit">Submit</button>
</form>
My views.py How to log a user in?
from django.contrib.auth import authenticate, login
def test(request):
form=MyForm()
return render(request,'captcha/home.html',{'form':form})
def submit(request):
if request.method == 'POST':
form=MyForm(request.POST)
if form.is_valid():
name=request.POST['fullname']
email=request.POST['email']
print('success')
print(name)
print(email)
user = authenticate(request,username=username,password=password)
if user is not None:
login(request, user)
return redirect('/homepage') # Redirect to a success page.
else:
# Return an 'invalid login' error message.
print('fail')
messages.success( request,f 'login failed! username or passwoed is wrong!'
return redirect('login')

Logout function in Django not working as Expected

I have not used any middleware, when i click on logout button on my Home Page template, the logout function execute without any error.but when i go back to main page without jumping to login page.. i see myself as logged in user
here is my authentiCation/views.py
from django.shortcuts import render
from django.http import request,HttpResponseRedirect
# for user creation & login form
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import authenticate, login
# for user related Queries
from django.contrib.auth.models import User
# imports for test purpose
from django.http import HttpResponse
# Create your views here.
# register page
def register_Page(request):
if request.method == 'POST':
form= UserCreationForm(request.POST)
if form.is_valid():
form.save()
username= request.POST['username']
password= request.POST['password1']
user= authenticate(request,username=username,password=password)
login(request,user)
return HttpResponseRedirect('/')
else:
return HttpResponse('Either the user name is not available or you may have filled the form incorrectly')
else:
form = UserCreationForm()
context= {'form':form}
return render(request,'authentication/register_Page.html',context)
# login page
def login_page(request):
if request.method == 'POST':
username= request.POST['username']
password= request.POST['password']
# returns user if credentials are valid
user= authenticate(request, username=username, password= password)
# check if user var contains the user
if user is not None:
login(request, user)
return HttpResponseRedirect('/')
else:
return HttpResponse('Invalid credentials')
return render(request,'authentication/login.html')
# logout Page
def log_out(request):
logout(request)
return HttpResponseRedirect('logout_page')
authentiCation/urls.py
from django.urls import path
from authentiCation import views
urlpatterns = [
path('register/',views.register_Page),
path('login/',views.login_page,name='login_page'),
path('logout/',views.log_out),
]
Main App Files
urls
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('App_wfi_Community.urls')),
path('Ask/',include('askQuestion.urls')),
path('auth/',include('authentiCation.urls')),
]
Home.html
{% extends "basic.html" %}
{% load humanize %}
{% block title %}WFI-Community{% endblock title %}
{% block body %}
<!-- search button -->
<h5>Welcome {{username}},<h5> <!-- I see my username here -->
<form action="/search" method="get">
<div class="container py-3 row">
<div class="col-md-8 offset-2">
<div class="input-group">
<input name="searchfieldText" type="text" class="form-control" placeholder="Search">
<button class="btn btn-danger" type="submit">Search</button>
<span>Logout</span>
</div>
</div>
</div>
</form>
<!-- and some more HTML stuff which is irrelavent here -->
Give a name to this eg
path('logout/',views.log_out, name="logout" ) and change it in the home.html.
eg "{% url 'logout' %}">Logout

Log out when sending a form

I've created an app where you can make comment (which sends a form to a database and saves it) if you're login on only, but when I press the button "Create" instead of redirecting me to the page where it show all the comments, it logs me out and bring me back to the "log out" view (which is / )
the create Template:
{% extends 'base.html' %}
{% block content %}
<div class="create_comment">
<h2>Write a comment</h2>
<form class="site-form" action="{% url 'create' %}" method="post">
{% csrf_token %}
{{form}}
<input type="submit" value="Create">
</form>
</div>
{% endblock %}
The Views of Create:
#login_required(login_url='/userprofile/login/')
def comments_create(request):
if request.method == 'POST':
form = forms.CreateComment(request.POST)
if form.is_valid():
form.save()
return redirect('/usercomments')
else:
form = forms.CreateComment()
return render(request,'usercomments/comments_create.html', {'form':form})
Log out view:
def logout_view(request):
if request.method == 'POST':
logout(request)
return redirect('/')
else:
pass
usercomments Urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$',views.comments_list, name="list"),
url(r'^create/$', views.comments_create, name="create"),
url(r'^(?P<slug>[\w-]+)/$',views.comments_detail, name="detail"),
]
userprofile urls.py:
from django.conf.urls import url
from . import views
app_name = 'userprofile'
urlpatterns = [
url(r'^signup/$', views.signup_view, name="signup"),
url(r'^login/$', views.login_view, name="login"),
url(r'^logout/$',views.logout_view, name="logout"),
]

why is my input fields not showing in the website?

I have created a login and registration page using the same code. The registration page shows username input fields and other fields but the login page only shows the button. Can anyone help me in this
Code:
Login Page:
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Join Today</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Sign Up</button>
</div>
</form>
<div class="border-top pt-3">
<small class="text-muted">
Already Have An Account? <a class="ml-2" href="{% url 'login' %}">Sign In</a>
</small>
</div>
</div>
Registration Page:
<div class="site-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Log In </legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Login</button>
</div>
</form>
<div class="border-top pt-3">
<small class="text-muted">
Need An Account? <a class="ml-2" href="{% url 'register' %}">Sign Up Now</a>
</small>
</div>
</div>
Registration page
Login page
This is the views of the project
Views.py
from django.shortcuts import render, redirect
from django.contrib import messages
from .forms import UserRegisterForm
from .models import Post
from django.contrib.auth.decorators import login_required
def home(request):
context = {
'posts': Post.objects.all()
}
return render(request, 'blog/home.html', context)
def about(request):
return render(request, 'blog/about.html', {'title': 'About'})
def gallery(request):
return render(request, 'blog/gallery.html', {'title': 'Gallery'})
def foodopedia(request):
return render(request, 'blog/foodopedia.html', {'title': 'Foodopedia'})
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
messages.success(request, f'Account created for {username}!')
return redirect('blog-home')
else:
form = UserRegisterForm()
return render(request, 'blog/register.html', {'form': form})
def login(request):
return render(request, 'blog/login.html', {'title': 'Login'})
#login_required
def profile(request):
return render(request, 'blog/profile.html', {'title': 'Profile'})
def upload(request):
context = {}
if request.method == 'POST':
uploaded_file = request.FILES['document']
fs = FileSystemStorage()
name = fs.save(uploaded_file.name, uploaded_file)
context['url'] = fs.url(name)
context['filename'] = name
pred, probability = process_image(name)
context['prediction'] = pred
context['probability'] = probability
return render(request, 'blog/foodopedia.html', context)
This is the urls.py of the project
from django.contrib import admin
from django.urls import path, include
from blog import views as blog_views
from django.contrib.auth import views as auth_views
from blog import views as blog_views
urlpatterns = [
path('admin/', admin.site.urls),
path('register/', blog_views.register, name='register'),
path('profile/', blog_views.profile, name='profile'),
path('', include('blog.urls')),
path('login/', auth_views.LoginView.as_view(template_name='blog/login.html'), name='login'),
path('logout/', auth_views.LogoutView.as_view(template_name='blog/logout.html'), name='logout'),
]
This is the form.py file:
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
You forgot to create a new form in forms.py, then also dont forget to enhance your login view.
You could try using this, adapted from the example in this tutorial:
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.contrib.auth.forms import AuthenticationForm
def login(request):
if request.user.is_authenticated:
return redirect('/')
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('/')
else:
form = AuthenticationForm(request.POST)
return render(request, 'blog/login.html', {'form': form, 'title': 'Login'})
else:
form = AuthenticationForm()
return render(request, 'blog/login.html', {'form': form, 'title': 'Login'})
To use that you would have to change the login line in your urls.py to this:
path('login/', blog_views.login, name='login'),

Django, fetching data of other users

I used Django’s built in authentication system to create a log in, sign up and log out function. I want to add the ability to change your bio so that other users can view that bio through your profile page.
Below is my code:
register.html template
{% if user.is_authenticated %}
<h3 class="Logged">You must log out first before you can register a new account</h3>
{% else %}
<div class="signup">
<form method="post" action="{% url 'register' %}">
{% csrf_token %}
<p>Username: </p>
{{ form.username }}<br>
<p>Required. 150 characters or fewer. Letters, digits and #/./+/-/_ only. Password: </p>
{{ form.password1 }}<br>
<p>Your password can't be too similar to your other personal information. Your password must contain at least 8 characters. Your password can't be a commonly used password. Your password can't be entirely numeric.</p>
<p>Password Confirmation: </p>
{{ form.help_text}}
{{ form.password2 }}<br>
<p>Enter the same password as before, for verification</p>
{% if form.errors %}
<p class="invalid">What you have entered is invalid</p>
{% endif %}
<input type="submit" = value="Register">
<br><br>
</form>
</div>
{% endif %}
views.py
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data['username']
password = form.cleaned_data['password1']
user = authenticate(username=username, password=password)
login(request, user)
return redirect('index')
else:
form = UserCreationForm()
context = {'form' : form}
return render(request, 'registration/register.html', context)
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('login', views.log, name='log'),
path('register', views.register, name='register'),
path('accounts', views.accounts, name='accounts'),
]
Any help is appreciated
URLS.PY
from yourapp import views as yourapp_views
url(r'^user/(?P<user_login_name>[\w\-]+)/$', extension_views.view_user_profile)
YOURAPP.VIEWS.PY
from django.contrib.auth.models import User
from django.shortcuts import render
def view_user_profile(request, user_login_name):
args = {}
args['user_profile'] = User.objects.get(username=user_login_name)
return render(request, 'your_template_to_render.html', args)
your_template_to_render.html
{{ user_profile }} {{ user_profile.id }} {{ user_profile.firstname }}