Multivaluedict key error wventhough i have set name to input field - python

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>

Related

How to get name input type submit modelform in Django

I am facing a problem. Please help me
templates.html
<form action="" method="POST">{% csrf_token %}
{{Form.as_p}}
<input type="submit" name="Save" value="Save">
<input type="submit" name="Delete" value="Delete">
</form>
view.py
Class-based views:
def post(self,request,text_id):
try:
text_data = Text.objects.get(pk=text_id)
a = FormText(request.POST,instance=text_data)
except:
a = FormText(request.POST)
if request.POST.get('name') =='Delete':
a.delete()
else:
try:
a.save()
except:
return HttpResponse('no ok')
You can add this to a button, so:
<form action="" method="POST">
{% csrf_token %}
{{Form.as_p}}
<button type="submit" name="action" value="save">Save</button>
<button type="submit" name="action" value="delete">Delete</button>
</form>
Then in your view, you can access the value of the action key:
from django.shortcuts import get_object_or_404
def post(self,request,text_id):
item = get_object_or_404(Text, pk=text_id)
action = request.POST.get('action')
if action == 'delete':
item.delete()
# …
pass
elif action == 'save':
# …
pass
else:
# invalid action …
pass

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

MultiValueDictKeyError at /signup/ 'password11'

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>

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 %}

when i click the button to update my form CSRF verification failed pop ups

I have two different forms in my index.html template and in both the forms i'm using csrf token.
The problem that i'm facing is when I try to update my form i'm getting "CSRF verification failed. Request aborted." I've searched almost all the questions in this site and other websites and did everything still the error is shown.
This is my first form which adds student entry:
<form action = "{% url 'studentapp:addstudent' %}" id="addform" method = "POST">
{% csrf_token %}
<div class = "form-group">
<label for = "your_name">
Your name:
</label>
<input class = "form-control" id="new_name" type = "text" name="name" value="{{ current_name }}" placeholder="Enter your name">
</div>
<div class="form-group">
<label for = "course_name">
Course:
</label>
<input id="new_course" class = 'form-control' type = "text" name="course" value="{{ current_course }}" placeholder="Enter your course">
</div>
<div class = "form-group">
<label for = "rollno">
Roll No.:
</label>
<input id="new_rollno" type = "text" class = 'form-control' name="roll" value="{{ current_roll }}" placeholder="Enter your roll number">
</div>
<div class = "form-group">
<label for ="addr">
Address:
</label>
<textarea id="new_address" type = "text" name="address" class = 'form-control' value="{{ current_addr }}" placeholder="Enter your address"></textarea>
</div>
<input type = "submit" value="Submit" class = "btn btn-success" style="font-size:18px;" />
</form>
This is my second form which is pre-populated when i click "edit" button on my template. when i click "update" button csrf token verification failed is displayed.
<form action="{% url 'studentapp:editrow' rowid=id %}" id="editform" method="POST">
{% csrf_token %}
<div class = "form-group">
<label for = "your_name">
Your name:
</label>
<input class = "form-control" id="new_name" type = "text" name="name" value="{{ student_detail.name }}" placeholder="Enter your name">
</div>
<div class="form-group">
<label for = "course_name">
Course:
</label>
<input id="new_course" class = 'form-control' type = "text" name="course" value="{{ student_detail.course }}" placeholder="Enter your course">
</div>
<div class = "form-group">
<label for = "rollno">
Roll No.:
</label>
<input id="new_rollno" type = "text" class = 'form-control' name="roll" value="{{ student_detail.roll }}" placeholder="Enter your roll number">
</div>
<div class = "form-group">
<label for ="addr">
Address:
</label>
<input id="new_address" type = "text" name="address" class = 'form-control' value="{{ student_detail.address }}" placeholder="Enter your address"/>
</div>
<input type = "submit" value="Update" id="update" class = "btn btn-success" style="font-size:18px;" />
</form>
</div>
</div>
</div>
</div>
This is my ajax request:
function update_entry(id) {
var id = id
$.ajax({
url: "{% url 'studentapp:index' %}",
type: "POST",
data:{
'csrfmiddlewaretoken': '{{ csrf_token }}',
'id' : id,
},
success: function(response){
$(".response").html(response.template)
$("#editform").modal("show");
}
});
}
function update_property(id) {
window.location.replace("/studentapp/editrow" + id+"/");
}
Since I was using two separate forms, i was using two CSRF tokens. Removing one token was not solving the issue so I just did this:
<input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}">
in one of my forms and added these two lines in my index view:
if request.is_ajax():
#Your Code
csrf_token = request.POST['csrfmiddlewaretoken']
response = {}
response['status'] = False
student_detail = #Your Model name
context = {
"Your dictionary"
"csrf_token": csrf_token
}
and it's working just fine for me.

Categories

Resources