MultiValueDictKeyError at /signup/ 'password11' - python

I'm trying to signup user but getting some weird error.
please help me to solve it
This is my view file with the function named signup
def signup(request):
if request.method=='POST':
username = request.POST['username']
email = request.POST['email']
password1 = request.POST['password1']
password11 = request.POST['password11']
if password1==password11:
if User.objects.filter(username=username).exists():
messages.info(request,'Username Taken')
return redirect('/account')
elif User.objects.filter(email=email).exists():
messages.info(request,'Email Taken')
return redirect('/account')
else:
user=User.objects.create_user(username=username, password=password1, email=email)
user.save();
auth.login(request,user)
print('user created')
else:
messages.info(request,'Password not Matching')
return redirect('/account')
return redirect('/')
else:
return render(request,'account.html')
And this is my signup file. I've save file with the name account.html.
<form id="regform" style="margin-top: -40px;" action="/signup/" method="post">
{% csrf_token %}
<input type="text" placeholder="Username" name="username">
<input type="email" placeholder="Email" name="email">
<input type="password" placeholder="Password" name="password1">
<input type="password" placeholder="Confirm Password" name="Password11">
<button type="submit" id="btn2">Register</button>
<div>
{% for message in messages %}
<h6>{{message}}</h6>
{% endfor %}
</div>
</form>

Related

Multivaluedict key error wventhough i have set name to input field

I have made a form and set method=post and while taking request.post['name'] to a variable MultiValueDictKeyError is Coming why is that ?
<form action="verify_user" method="post">
{% csrf_token %}
<input required type="text" placeholder="Name" name="name"><br><br>
<input required type="password" placeholder="Password" name="password"><br><br>
<input required type="passord" placeholder="Confirm password" name="confirm_password" id=""> <br><br>
<br><br><h1>{{ messages }}</h1>
<button type="submit">Create</button>
</form>
this is my form ------
def verify_user(request):
inputname = request.POST['name']
inputpass = request.POST['password']
inputconfirmpass = request.POST['confirm_password']
if not inputpass == inputconfirmpass:
messages.info(request,"Passwords don't match")
else:
messages.info(request,"Passwords match")
return redirect('/verify_user')
this is my function in views.py -------------
MultiValueDictKeyError at /verify_user
'name'
Request Method: GET
Request URL: http://127.0.0.1:8000/verify_user
Django Version: 4.1.2
Exception Type: MultiValueDictKeyError
Exception Value: 'name'
this is the error --------
Try to provide another name as name for e.g. person_name something like that, also I'd recommend you to use .get() so that you can also provide some other default value.
views.py:
def verify_user(request):
if request.method=="POST":
inputname = request.POST.get('person_name', False)
inputpass = request.POST.get('password', False)
inputconfirmpass = request.POST.get('confirm_password', False)
if not inputpass == inputconfirmpass:
messages.info(request,"Passwords don't match")
else:
messages.info(request,"Passwords match")
return redirect('/verify_user')
else: # GET request
return render(request, "some_folder_name/your_template.html")
Template file:
<form method="POST">
{% csrf_token %}
<input required type="text" placeholder="Name" name="person_name"><br><br>
<input required type="password" placeholder="Password" name="password"><br><br>
<input required type="passord" placeholder="Confirm password" name="confirm_password" id=""> <br><br>
<br><br><h1>{{ messages }}</h1>
<button type="submit">Create</button>
</form>

error login or password in authentication in flask

I have two forms:
auth.html
<form class="form-signin pt-5" action="/auth/" method="post" >
{% if error_msg: %}
{{ error_msg }}
{% endif %}
<div class="mt-5 form-label-group">
<p class="text-muted">email</p>
<input type="email" id="inputEmail" class="form-control" name = "email" required autofocus>
</div>
<div class="form-label-group">
<p class="text-muted"> password</p>
<input type="password" id="inputPassword" name="password" class="form-control" required>
<label for="inputPassword"></label>
</div>
<div class="checkbox mb-3"></div>
<button class="btn btn-lg btn-danger btn-block" type="submit">Enter</button>
</form>
success form.html
Success
code in flask is:
app = Flask(__name__)
app.secret_key = "randomstring"
app.config["SECRET_KEY"] = "secret_key"
app.config["EMAIL"] = "test#test.ru"
app.config["PASSWORD"] = "test"
#app.route("/auth/", methods=["GET", "POST"])
def auth_open():
error_msg = "" # Пока ошибок нет
if request.method == "POST":
email = request.form.get("username")
password = request.form.get("password")
if ((email and password) and email == app.config["EMAIL"] and password == app.config["PASSWORD"]):
session["is_auth"] = True
return render_template("/")
else:
error_msg = "Error login or password"
return render_template("auth.html", error_msg=error_msg)
When I input password and login it shows me error message instead of success form.How should I solve this problem?
email = request.form.get("email")

django sessions remember me

I am new to django and have not found a question corresponding to my entry level. And I just can't figure out how to work with sessions. I want to make a checkbox on login to remember me. After I registered in settings SESSION_EXPIRE_AT_BROWSER_CLOSE = True, you need to enter your username and password after closing the browser. How do I change this parameter using the "remember me" checkbox? Thank you
views.py
def login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
return redirect('/')
else:
messages.info(request, 'invalid credentials')
return redirect('login')
else:
return render(request, 'prof/login.html')
login.html
<body>
<div class="text-center mt-5">
<form style="max-width: 480px; margin: auto" method="post">
{% csrf_token %}
<img
src="https://logodix.com/logo/1713894.jpg"
alt=""
width="120"
height="90"
class="d-inline-block mt-4 mb-4"
/>
<p class="hint-text mb-3">Please sign in</p>
<label class="sr-only" for="username"></label>
<input
type="login"
name="username"
class="form-control"
placeholder="username"
required
autofocus
/>
<label for="password" class="sr-only"></label>
<input
type="password"
name="password"
class="form-control mt-2"
placeholder="password"
/>
<div class="checkbox">
<label for="checkbox">
<input type="checkbox" name="checkbox" value="remember-me" /> remember
me
</label>
</div>
<div class="d-grid gap-2 mt-4">
<input type="Submit" class="btn btn-primary" value="sign in" />
</div>
</form>
<div class="messages">
{% for message in messages %}
<h3>{{message}}</h3>
{% endfor %}
</div>
https://docs.djangoproject.com/en/3.1/topics/http/sessions/#browser-length-sessions-vs-persistent-sessions
you need to set request.session.set_expiry(value) when a user logs on and the checkbox is clicked.
the value in this function is filled out using the following datatypes and values: https://docs.djangoproject.com/en/3.1/topics/http/sessions/#django.contrib.sessions.backends.base.SessionBase.set_expiry
for you this will mean the following:
def login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
if request.cleaned_data['remember_me'] == True:
request.session.set_expiry(value)
# ^^^^^^
# insert something here
return redirect('/')
else:
messages.info(request, 'invalid credentials')
return redirect('login')
else:
return render(request, 'prof/login.html')
def login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = auth.authenticate(username=username, password=password)
try:
remember = request.POST['remember_me']
if remember:
settings.SESSION_EXPIRE_AT_BROWSER_CLOSE = False
except:
is_private = False
settings.SESSION_EXPIRE_AT_BROWSER_CLOSE = True
if user is not None:
auth.login(request, user)
return redirect('/')
else:
messages.info(request, 'invalid credentials')
return redirect('login')
else:
return render(request, 'prof/login.html')

Flask dosen't work.Method Not Allowed 405

If from begining i start with Register Page it work ,but if i use,int html, a hyperlink to the Register page it will stop working and print(405 Method Not Allowed/The method is not allowed for the requested URL.).
Here is my python code except run and imports:
And i use python 3.8
app = Flask(__name__)
#app.route("/")
def main():
return render_template("MainFacut.html")
#app.route("/register")
def register():
return render_template("Register.html")
#app.route("/register",methods=["GET","POST"])
def settingData():
FullName = request.form['fullname']
Age = int(request.form['age'])
try:
Gender = request.form['Option']
except Exception as ex:
return render_template("Register.html",n = "Gender not selected")
UserName = request.form['username']
Email = request.form['email']
Pass1 = request.form['password']
Pass2 = request.form['password0']
if Age < 13 or Age > 110:
return render_template("Register.html",n = "Age not corresspond")
if Email == "" or FullName == "" or Age == "":
return render_template("Register.html", n = "Not completed spaces!")
if Pass1 != Pass2:
return render_template("Register.html",n = list_of_errors[3])
if len(Pass1) < 6:
return render_template("Register.html",n = "A password have atleast 6 characters")
freespace = validate_existence(UserName)
if freespace == 1:
return render_template("Register.html",n = "User already exist!")
create_NewUser(UserName,FullName,Age,Pass1,Email,"","","","","")
return render_template("after.html",n = "succes")
#app.route("/login")
def login():
return render_template("py.html")
#app.route('/login',methods=["GET","POST"])
def getingData():
UserName = request.form['username']
Password = request.form['password']
step = validate(UserName,Password)
if Password == "":
return render_template('py.html', n=list_of_errors[2])
if UserName == "":
return render_template('py.html', n = list_of_errors[1])
if step == 0:
return render_template('py.html',n=list_of_errors[0])
return render_template('after.html',n = 'Succes')
if (__name__ == "__main__"):
app.run(debug=True)
when i used "/reg" my flask app dosen't work
this is the html used:
<div class="loginbox">
<img src="{{url_for('static',filename = 'Logo_Appelle.png')}}" class="avatar">
<h1>Create an account</h1>
<h1>{{n}}</h1>
<form name="APPelle" action="." method="POST">
<div class="row">
<div class="column" style="background-color:#060517;">
<p>Full Name</p>
<input type="text" name="fullname" placeholder="Enter Full Name"><br><br>
<p>Age</p>
<input type="text" name="age" placeholder="Enter Age"><br><br>
<p>Gender</p>
<input type="radio" name="Option" id="male" name="gender" value="male">
<label for="male">Male</label>
<input type="radio" name="Option" id="female" name="gender" value="female">
<label for="female">Female</label><br><br>
<button class="button">Register</button>
</div>
<div class="column" style="background-color:#03050d;">
<p>Username</p>
<input type="text" name="username" placeholder="Enter Username"><br><br>
<p>Email</p>
<input type="text" name="email" placeholder="Enter Email"><br><br>
<p>Password</p>
<input type="password" name="password" placeholder="Enter Password">
<input type="password" name="password0" placeholder="Confirm Password"><br><br>
</div>
</div>
</form>
</div>
</form>
</body>
</head>
</html
Remove the routes without Methods(POST and get) declared it's conflicting paths.
And method name should be same as the route path
#app.route("/login")
def login():
return render_template("py.html")
#app.route('/login',methods=["GET","POST"])
def getingData():
UserName = request.form['username']
Password = request.form['password']
step = validate(UserName,Password)
if Password == "":
....
....
should be
#app.route('/login',methods=["GET","POST"])
def login():
UserName = request.form['username']
Password = request.form['password']
step = validate(UserName,Password)
if Password == "":
...
...

Captcha verification Python Django

I am getting Invalid captcha response for below set up. Contact form worked perfectly fine, I added rule that verifies captcha, I checked secret keys and still getting Invalid Captcha even after solving it. Below is my setup:
views.py
def get_client_ip(request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR')
return ip
def grecaptcha_verify(request):
response = {}
data = request.POST
captcha_rs = data.get('g-recaptcha-response')
url = "https://www.google.com/recaptcha/api/siteverify"
params = {
'secret': settings.RECAPTCHA_SECRET_KEY,
'response': captcha_rs,
'remoteip': get_client_ip(request)
}
verify_rs = requests.get(url, params=params, verify=True)
verify_rs = verify_rs.json()
response["status"] = verify_rs.get("success", False)
response['message'] = verify_rs.get('error-codes', None) or "Unspecified error."
return response
def contact(request):
if request.method == 'POST':
if grecaptcha_verify(request) == "success":
subject = request.POST.get('subject')
message = request.POST.get('message')
email = request.POST.get('email')
if subject and message and email:
try:
send_mail(subject, message, email, ['myemail#gmail.com'],fail_silently= True)
except BadHeaderError:
return HttpResponse('{Bad Header}')
return greatsuccess(request)
else:
return HttpResponse('{Invalid Form}')
else:
return HttpResponse('Invalid Captcha')
return render(request, 'personal/contact.html')
My template:
<div class="form-area">
<form role="form" method="POST">
{% csrf_token %}
<input type="text" class="form-control" id="subject" name="subject" placeholder="Subject" maxlength="70" required>
</div>
<br>
<div class="form-group">
<input type="email" class="form-control" id="email" name="email" placeholder="Email" required>
</div>
<div class="form-group">
<textarea class="form-control" type="textarea" id="message" name="message" placeholder="Message" maxlength="300" rows="7"></textarea>
</div>
<button type="submit" name="submit" class="btn btn-m btn-secondary">Submit</button>
<script src='https://www.google.com/recaptcha/api.js'></script>
<div class="g-recaptcha" data-sitekey="MYKEY"></div>
</form>
I am quite new to Python, how to check what is happening in the background and at which point verification fails?
You are making get request for verification, but you need to make post request to it. That is why captcha verification failing. So try like this:
url = "https://www.google.com/recaptcha/api/siteverify"
headers = {'User-Agent': 'DebuguearApi-Browser',}
params = {'secret': settings.RECAPTCHA_SECRET_KEY, 'response': captcha_rs}
verify_rs = requests.post(url, data=params, headers=headers) # <-- Update Here
... # rest of your code
Please see the documentation on how to verify recaptcha.
Ok.
I got it working. Thanks Ruddra for all the help.
I deleted first </div> as I've noticed this was unnecessary. This allowed g-recaptcha-response to be included in POST data. Apparently it's important to make sure your form is correct and google likes it.
Secondly I did some modifications to main views.py as per advice I received+ some improvements.
def greatsuccess(request):
messages.success(request, "Email sent!")
return render(request, 'personal/contact.html')
def greatfail(request):
messages.error(request, "Invalid Captcha!")
return render(request, 'personal/contact.html')
def grecaptcha_verify(request):
data = request.POST
captcha_rs = data.get('g-recaptcha-response')
url = "https://www.google.com/recaptcha/api/siteverify"
headers = {'User-Agent': 'DebuguearApi-Browser',}
params = {'secret': settings.RECAPTCHA_SECRET_KEY, 'response': captcha_rs}
verify_rs = requests.post(url,params, headers=headers)
verify_rs = verify_rs.json()
response = verify_rs.get("success", False)
return response
def contact(request):
if request.method == 'POST':
response=grecaptcha_verify(request)
if response == True :
subject = request.POST.get('subject')
message = request.POST.get('message')
email = request.POST.get('email')
if subject and message and email:
try:
send_mail('Sent from mywebsite '+subject, message, email, ['email#gmail.com'],fail_silently= True)
except BadHeaderError:
return HttpResponse('{Bad Header}')
return greatsuccess(request)
else:
return HttpResponse('{Invalid Form}')
else:
greatfail(request)
return render(request, 'personal/contact.html')
My template:
<form method="POST">
{% csrf_token %}
<input type="text" class="form-control" id="subject" name="subject" placeholder="Subject" maxlength="70" required>
<br>
<div class="form-group">
<input type="email" class="form-control" id="email" name="email" placeholder="Email" required>
</div>
<div class="form-group">
<textarea class="form-control" type="textarea" id="message" name="message" placeholder="Message" maxlength="300" rows="7"></textarea>
</div>
<div class="g-recaptcha" data-sitekey="key"></div>
<button type="submit" name="submit" class="btn btn-m btn-secondary">Submit</button>
</form>
{% for message in messages %}
{{ message }}
{% endfor %}

Categories

Resources