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 }}
Related
here is my loginHtml code
<form method="post" action="handleLogin_url" enctype="multipart/form-data">
{{ tryAgain }}
<br>
{% csrf_token %}
<label for="username">Enter Username</label><input id="username" name="username" type="text">
<label for="password">Enter password</label><input id='password' name="password" type="password">
<input type="submit" value="Lets Go">
views.py
def handleLogin(HttpRequest):
if HttpRequest.method=='POST':
enteredname = HttpRequest.POST['username']
# user = User.objects.get(username=enteredname)
enteredpassword = HttpRequest.POST['password']
user = authenticate( HttpRequest, username=enteredname,password=enteredpassword)
# return render(HttpRequest, 'seeData.html',
# {'User': user, 'enteredname': enteredname, 'enteredpassword': enteredpassword})
if user is not None:
return render(HttpRequest, 'seeData.html', {'Users':user, 'enteredname':enteredname, 'enteredpassword':enteredpassword})
else :
tryAgain = "Invalid username or password try again"
return render(HttpRequest, 'LoginHtml.html', {'tryAgain':tryAgain})
else:
return render(HttpRequest,'LoginHtml.html')
seeDataHtml code
{{ User.username }},{{ User.password }}||{{ enteredname }} {{ enteredpassword }}
when I try using superuser credentials a superuser object is returned but when I use a user credential no object is returned but when I log into admin site I can see user objects
You doing here a lot of mistakes first thing your HTML should look like this:
<div class="container py-5">
<form method="POST" enctype="multipart/form-data">
<div class="mb-3">
{% csrf_token %}
{{login_form}}
</div>
<input type="submit" name="Log in" class="btn btn-primary"></input>
</form>
{% for message in messages %}
{% if message.tags %}
<span class="{{ message.tags }}"> </span>
{{ message }}
{% endif %}
{% endfor %}
<br>
Forgot Password
</div>
In views.py
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import login as login_auth, authenticate
from django.contrib import messages
from django.shortcuts import redirect, render
def login(request):
if request.user.is_authenticated: #to check if user is authenticated
return redirect('home')
if request.method == "POST":
form = AuthenticationForm(request, data=request.POST)
if form.is_valid(): #If form is valid returns True
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(username=username, password=password)
if user is not None:
login_auth(request, user)
return redirect('home')
else:
messages.error(request,"Invalid username or password.")
else:
messages.error(request,"Invalid username or password.")
else:
form = AuthenticationForm()
return render(request, 'login.html', {'login_form': form})
Also, I saw that you create a new page to show a message error you can do that using Django messages from django.contrib import messages
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.
guys i need a small help
here is my views.py
def signup(request):
if request.method == 'POST':
form = UserRegistrationForm(request.POST)
verification=VerificationForm(request.POST)
if form.is_valid():
userObj = form.cleaned_data
username = userObj['username']
email = userObj['email']
password = userObj['password']
return HttpResponseRedirect('/index/verification/')
# if
if not (User.objects.filter(username=username).exists() or User.objects.filter(email=email).exists()):
User.objects.create_user(username, email, password)
user = authenticate(username = username, password = password)
login(request, user)
return HttpResponseRedirect('/')
else:
raise forms.ValidationError('Looks like a username with that email or password already exists')
else:
raise forms.ValidationError('a valid')
else:
form = UserRegistrationForm()
verification = VerificationForm()
return render(request, 'question/signup.html',context= {'verification':verification,'form' : form})
here you can see i have declared two context variables one is form and the other one is verification now i want to use
now this is my signup.html
{% extends 'question/index.html '%}
{% block body_block %}
<div class="conrainer">
<form method="POST">
{% csrf_token %} {{ form.as_p }}
<button type="submit">Submit</button>
</form>
facebook auth
</div>
{% endblock %}
now i have used form variable in this page
and i want to use verification varible in another page as django views are not made to use two templates in a single view
after searching a lot in online forums i came to know about {% include tag %}
after trying to use that tag after going through documentation
this is how my verification.html is
{% include 'question/signup.html' with obj=verification only%}
<div class="container">
<form method="post">{% csrf_token %}
<p>{{verification.as_p}}</p>
<p>{{obj.as_p}}</p>
<input type="submit" name="verify" value="" action='.' align='center'name='submit'>
</form>
</div>
here is my urls.py file
urlpatterns = [
# url(r'^/',views.home,name='home'),
url(r'^home/',Home,name='home'),
url(r'^ques/',Create.as_view(success_url="/index/home/"),name='ques'),
url(r'^signup/',signup,name='signup'),
# url(r'^signup/',MyFormView.as_view(),name='signup'),
url(r'^verification/',TemplateView.as_view(template_name="question/verification.html")),
url(r'^logout/$', auth_views.logout,name='logout'),
url(r'^search/',Search,name='search'),
url(r'^accounts/', include('allauth.urls')),
# url(r'^verify/',verificationView,name='signup'),
# CreateView.as_view(model=myModel, success_url=reverse('success-url'))
]
but after trying it so many ways either obj or verification shows up in the site is there any way where i can only get the context object instead of getting the subit button and all from my signup.html using INCLUDE any kind of help is appreciated
When I tried to register in my site, it's instantly buffering,
The server is working properly and others were coded finely.
The urls.py
urlpatterns = [
#Login Page
url(r"^login/$", login, {'template_name':'users/login.html'},
name='login'),
#Logout Page
url(r"^logout/$", views.logout_view, name="logout"),
# Registration Page
url(r"^register/$", views.register, name='register'),
]
The views.py
def register(request):
"""Register a new user."""
if request.method != "POST":
#display blank register form.
form = UserCreationForm()
else:
# process completed form.
form = UserCreationForm(data=request.POST)
if form.is_valid():
new_user = form.save()
# Log the user in and then redirect to home page
authenticate_user = authenticate(username=new_user.username,
password=request.POST['password1'])
login(request, authenticate_user)
return HttpResponseRedirect(reverse('learning_logs:index'))
context = {'form': form}
return render(request, 'users/register.html', context)
Double checked I am in the right views.py
The register.html is:
{% extends "learning_logs/base.html" %}
{% block content %}
<form action="{% url "users:register" %}" method="post">
{% csrf_token %}
{{ form.as_p }}
<button name="submit">log in</button>
<input type="hidden" name="next" value="{% url "learning_logs:index" %}">
</form>
{% endblock content %}
Where might be the problem live?
I've built a "firewall" login form that I want to put in front of my
actual production website while I develop the site. The idea is to try
and keep the "bad guys" out of the site and at the same time see what
usernames and passwords they're using. The problem I'm having is that
if I enter an invalid username/password pair, my form's error message
doesn't get displayed. I realize that for my purposes, it it might be
better to not display any error message at all but I'd still like to
understand what the problem is. Can anyone see what I'm doing wrong?
Thanks.
# views.py
import logging
logger = logging.getLogger(__name__)
from django.contrib.auth import authenticate
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.views import login
from django.http import HttpResponseRedirect
def firewall_login(request, *args, **kwargs):
if request.method == "POST":
form = AuthenticationForm(request, data=request.POST)
username = request.POST['username']
password = request.POST['password']
if form.is_valid():
fw_username = form.cleaned_data['username']
fw_password = form.cleaned_data['password']
user = authenticate(username=fw_username, password=fw_password)
if user is not None:
if user.is_active:
login(request, user)
logger.info("User '%s' logged in." % fw_username)
return HttpResponseRedirect("/accounts/profile/")
else:
logger.info("User '%s' tried to log in to disabled account." % fw_username)
return HttpResponseRedirect("/accounts/disabled/")
else:
logger.info("User '%s' tried to log in with password '%s'." % (username, password))
form = AuthenticationForm(request) # Display bound form
else:
form = AuthenticationForm() # Display unbound form
return render(request, "registration/login.html", {"form": form,})
# login.html
{% extends "base.html" %}
{% block content %}
{% if form.errors %}
<p class="alert alert-error">Sorry, that's not a valid username or password</p>
{% endif %}
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div class="alert alert-error">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% for field in form.non_field_errors %}
<div class="alert alert-error">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endif %}
<form action="" method="post">
{% csrf_token %}
<p><label for="username">Username:</label>{{ form.username }}</p>
<p><label for="password">Password:</label>{{ form.password }}</p>
<input type="hidden" name="next" value="{{ next|escape }}" />
<input class="btn btn-primary" type="submit" value="login" />
</form>
{% endblock %}
It's because you pass new form instance. Validation occurs on is_valid call.
So, just remove form = AuthenticationForm(request) in else block:
def firewall_login(request, *args, **kwargs):
if request.method == "POST":
form = AuthenticationForm(request, data=request.POST)
username = request.POST['username']
password = request.POST['password']
if form.is_valid():
fw_username = form.cleaned_data['username']
fw_password = form.cleaned_data['password']
user = authenticate(username=fw_username, password=fw_password)
if user is not None:
if user.is_active:
login(request, user)
logger.info("User '%s' logged in." % fw_username)
return HttpResponseRedirect("/accounts/profile/")
else:
logger.info("User '%s' tried to log in to disabled account." % fw_username)
return HttpResponseRedirect("/accounts/disabled/")
else:
logger.info("User '%s' tried to log in with password '%s'." % (username, password))
else:
form = AuthenticationForm() # Display unbound form
return render(request, "registration/login.html", {"form": form,})