I am sending a Username and password from my HTML form to django backend .
<html>
<style type="text/css">
#center_align{
width: 200px;
margin: 10px auto;
}
</style>
<head>
<title>Login Form</title>
</head>
<body>
<div id = "center_align">
<h1>Login</h1>
<form method = "GET" action="http://127.0.0.1:8000/login/" >
Username :<input type ="text" name = "username"><br>
Password :<input type ="password" name = "password"><br>
<input type="submit" value="Submit">
</form>
</div>
</body>
</html>
In my django , i have wrote a class in my Views
class Login(APIView):
global User_Grps
def get(request,self):
state = ""
username = "Gauss"
password = settings.AUTH_LDAP_BIND_PASSWORD
oLdap = LDAPBackend()
try:
User = oLdap.authenticate(username=username,password=password)
print User.ldap_user.group_dns
if User is not None:
User_Grps = User.ldap_user.group_dns
else:
User_Grps = "Invalid Group"
except Exception as e:
User_Grps = "Error"
return HttpResponse(User_Grps)
How would i retrieve my username and password from the request object ? Like i need to get the data from the request parameter of the method .
Instead of doing that, you should write a custom Django authentication backend which would let you use the default login views from DRF and/or other Django 3rd parties.
Related
I'm want to use some sort of loop to go over all input fields in my form . But I'm unable to find any proper documentation on how to do it. Is it possible to loop over all the elements in my form in some way as well as dealing with multiple checkboxes ?
I tried to follow some online sources . This one outputs null value.
<html>
<body>
<form action = "main.jsp" method = "POST" target = "_blank">
<input type = "checkbox" name = "maths" checked = "checked" /> Maths
<input type = "checkbox" name = "physics" /> Physics
<input type = "checkbox" name = "chemistry" checked = "checked" /> Chemistry
<input type = "submit" value = "Select Subject" />
</form>
</body>
</html>
<%# page import = "java.io.*,java.util.*" %>
<html>
<head>
<title>HTTP Header Request Example</title>
</head>
<body>
<center>
<h2>HTTP Header Request Example</h2>
<table width = "100%" border = "1" align = "center">
<tr bgcolor = "#949494">
<th>Param Name</th>
<th>Param Value(s)</th>
</tr>
<%
Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
out.print("<tr><td>" + paramName + "</td>\n");
String paramValue = request.getHeader(paramName);
out.println("<td> " + paramValue + "</td></tr>\n");
}
%>
</table>
</center>
</body>
</html>
Is there any documentation source from where I can read about request object's methods ?
This part takes care of sending the link to the user. So far it does the job perfectly and I always get the email
app = Flask(__name__)
app.secret_key = 'b11223344AaadD$$r.,IIr]]tP[tu#urr'
app.config.from_pyfile('config.cfg')
mail = Mail(app)
s = URLSafeTimedSerializer(app.config['SECRET_KEY'])
engine = create_engine("postgresql://postgres:andersen23#localhost:5432/test")
db = scoped_session(sessionmaker(bind=engine))
#app.route('/recover', methods=['POST', 'GET'])
def recover():
headline = 'Recover Your Password'
alert = 'Type Your Email'
alert_ = ''
if request.method == 'GET':
return render_template('recover.html', headline=headline, alert1=alert, alert=alert_)
email = request.form.get('email')
session['email'] = email
mail1 = db.execute("SELECT contact0.email FROM person JOIN contact0 ON contact0.id = person.id
WHERE email = :email",
{"email": email}).fetchone()
token = s.dumps(email, salt='confirm')
link = url_for('confirm', token=token, _external=True)
msg = Message('Confirm Email', sender='esdavitnem#gmail.com', recipients=[email])
name = db.execute(
"SELECT person.first_name FROM person JOIN contact0 ON contact0.id = person.id WHERE email =
:username",
{"username": email}).fetchone()
if not isinstance(mail1, type(None)):
alert_ = f"Link Sent to {email}! \n Expires in 5 minutes!"
msg.body = f"Dear {name[0]}, \n\nYour link is {link} \n\nBest,\nDavid from Drunkify"
mail.send(msg)
return render_template('recover.html', headline=headline, alert1=alert, alert=alert_)
if isinstance(mail1, type(None)):
alert_ = f"No user exists with {email} email"
return render_template('recover.html', headline=headline, alert1=alert, alert=alert_)
This part takes care of opening the token and showing an html code to the user.
My main issue is that render_template only works with one html file in my templates.
register1.html is a page for my user to change their password. But the code error message keeps suggesting me to redirect them to register.html
#app.route('/confirm_email/<token>')
def confirm(token):
headline = 'Type Your New Password'
try:
email = s.loads(token, salt='confirm', max_age=300)
except SignatureExpired:
return 'The Token Expired'
return render_template('register1.html', headline=headline)
Register1.html
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Title Page-->
<title>Recover Your Password</title>
<link href="../static/main.css" rel="stylesheet" media="all">
</head>
<body>
<div class="page-wrapper bg-gra-01 p-t-180 p-b-100 font-poppins">
<div class="wrapper wrapper--w780">
<div class="card card-3">
<div class="card-heading"></div>
<div class="card-body">
<h2 class="title">Change Your Password</h2>
<form action = "{{ url_for('confirm') }}" method="post">
<div class="form-group">
<input class="form-control" type="password"
placeholder="New Password" name="password" required>
<div class="help-block with-errors"></div>
</div>
<div class="p-t-10">
<button type="submit" class="btn btn--pill btn--green">
Submit
</button>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
What you're seeing is a mismatch in expectations between
def confirm(token):
which expects an argument, and
{{ url_for('confirm') }}
which isn't providing one, but lives in a form that does provide password as part of the POST parameters (a different mechanism). I'm wondering if you didn't intend to do
{{ url_for('recover') }}
instead.
I passed the id value from html form to views .py. I want to check if the value matches with the one in database. But for some reason it's not working.
list.html
<form method= 'POST' action = "{% url 'jobs:pinned'%}">
{% csrf_token%}
<input type ="text" name = "number">
<input type="submit" value="Submit">
</form>
views.py
def pinned(request,category_slug=None):
users = User.objects.exclude(id=request.user.id)
jobs_list1 = Jobs.objects.all()
if request.method =="POST":
vari = request.GET.get('number')
for evert in jobs_list1:
if evert.Job_Id == vari:
evert.flag = True
evert.save(update_fields=["flag"])
context = {
'job_list1':jobs_list1,
'users':users
}
return render(request, 'jobs/product/list.html',context)
Here, if i put a static value as 511, i.e if evert.Job_Id ==511, it works. But if i change it to request.GET.get('number'), it's not working. How do i send value from form input value to views.py. Thanks.
Firstly method of your form is POST, so for GET method it will work.
for post method try this
vari = request.POST.get('number')
hope it helps
It turns out, I was comparing string with an integer. Thus I solved this problem as:
if request.method =="POST":
vari = request.POST.get('number')
vari = int(vari)
for evert in jobs_list1:
vari1 = evert.Job_Id
.....
I'm working on a simple flask application that displays a basic form with user, pass, verify pass, and email. The way I have it right now, if there are no errors, instead of going to the page i tell it to (welcome.html), it just goes back to my home page (index.html). There are comments in the code to guide you through it. Please help I've been racking my brain and the internet and trying lots and lots of things for the past week, and i need this for school or else im gonna fail. Here is my application code:
from flask import Flask, request, redirect, render_template
import jinja2
import cgi
app = Flask(__name__)
app.config['DEBUG'] = True
#app.route("/", methods=['GET'])
def index():
return render_template("index.html")
#if my form makes a post request at the route / (as defined in the form in the index page), then go to index again, or welcome page
#app.route("/", methods=['POST'])
def welcome():
username = str(request.form.get('username-actual'))
password = str(request.form.get('password-actual'))
verifiedpassword = str(request.form.get('verifedpassword-actual'))
email = str(request.form.get('email-actual'))
#if (not username) or len(username) < 3 or len(username) > 20 or ' ' in username: IGNORE THIS
#If any of the fields have any of these conditions, fill the error message with the message. otherwise, empty
if username == '' or len(username) < 3 or len(username) > 20 or ' ' in username:
usererror = "Invalid username lol"
else:
usererror = ""
if password == '' or len(password) < 3 or len(password) > 20 or ' ' in password:
passworderror = "Invalid password lol"
else:
passworderror = ""
if verifiedpassword != password:
verifiedpassworderror = "Passwords dont match lol"
else:
verifiedpassworderror = ""
if email == '' or len(email) < 3 or len(email) > 20 or ' ' in email or '#' not in email:
emailerror = "Invalid email lol"
else:
emailerror = ""
#if any of the error messages are not empty (meaning there are error messages), render the home page again, with the necessary strings provided for jinja
if len(usererror) > 0 or len(passworderror) > 0 or len(verifiedpassworderror) > 0 or len(emailerror) > 0:
return render_template("index",usererror=usererror,
passworderror=passworderror,
verifiedpassworderror=verifiedpassworderror,
emailerror=emailerror,
username=username,
email=email,)
#otherwise, go to the welcome page, with the necessary username
else:
return render_template("welcome.html",username=username)
app.run()
and here is my two form, index.html and welcome.html, respectively:
<!doctype html>
<html>
<head>
<title>
User Sign-up
</title>
<style>
.error { color:red; }
</style>
</head>
<body>
<h1>Sign-up</h1>
<br>
<form action="/" method="post">
<div>
<label>Username: <input type="text" name="username-actual" value="{{username}}"></label>
<p class="error">{{usererror}}</p>
</div>
<div>
<label>Password: <input type="password" name="password-actual"></label>
<p class="error">{{passworderror}}</p>
</div>
<div>
<label>Verify Password: <input type="password" name="verifiedpassword-actual"></label>
<p class="error">{{verifypassworderror}}</p>
</div>
<div>
<label>Email (optional): <input type="text" name="email-actual" value="{{email}}"></label>
<p class="error">{{emailerror}}</p>
</div>
<div>
<input type="submit" name="sign-up-submit" value="Sign Up!">
</div>
</form>
</body>
</html> <p></p>
Here is my welcome.html:
Welcome, {{username}}!
I have a login form. After pressing the login button the the post data is sent to the view login_auth that authenticates the user data and redirects accordingly. However,after pressing the login button, I am not being redirected to the appropriate page.
views.py
def login_successful(request):
return render(request,"login_successful.html")
def login_invalid(request):
return render(request,"login_invalid.html")
def login(request):
return render(request,'login.html',c)
def loginauth(request):
username=request.POST.get("username",'')
password=request.POST.get("password",'')
user=auth.authenticate(username=username,password=password)
if user is not none:
user.login(request.user)
return redirect(login_successful)
else:
return redirect(login_invalid)
urls.py
urlpatterns = [
url(r'^registration/',views.registration),
url(r'^registration_successful/',views.registration_successful),
url(r'^home/',views.home),
url(r'^login/',views.login),
url(r'^login_successful/',views.login_successful),
url(r'^login_invalid/',views.login_invalid),
url(r'^login/auth',views.loginauth)
]
login.html
<html>
<form action="/login/auth" method="POST">{% csrf_token %}
Username :<input type="textbox" name="username" >
Password :<input type="password" name="password">
<input type="submit" value="Login">
</form>
</html>
Your login url pattern is missing a trailing $. It should be:
url(r'^login/$', views.login),
Without the dollar, the /login/auth is matched by r'^login/, so the request is handled by your login view.
It's a bit unusual to process the form on a different url. Django comes with authentication views, including a login view. I would recommend using this rather than writing your own.
Use name for url
views.py
def login_successful(request):
return render(request,"login_successful.html")
def login_invalid(request):
return render(request,"login_invalid.html")
def login(request):
return render(request,'login.html',c)
def loginauth(request):
username=request.POST.get("username",'')
password=request.POST.get("password",'')
user=auth.authenticate(username=username,password=password)
if user is not none:
user.login(request.user)
return redirect('login_successful')
else:
return redirect('login_invalid')
urls.py
urlpatterns = [
url(r'^registration/',views.registration),
url(r'^registration_successful/',views.registration_successful),
url(r'^home/',views.home),
url(r'^login/$',views.login),
url(r'^login_successful/',views.login_successful, name='login_successful'),
url(r'^login_invalid/',views.login_invalid, name='login_invalid'),
url(r'^login/auth',views.loginauth)
]