Django CSRF verification failed even with {% csrf_token %} [duplicate] - python

This question already has an answer here:
CSRF token missing or incorrect, even after including the token tag
(1 answer)
Closed 5 years ago.
POST requests to the Django view below result in (403) CSRF verification failed. I've confirmed that the hidden csrf token gets rendered in the page's source. I am also able to make POST requests without errors in other views. I'm unsure how to debug further.
views.py:
def email(request):
if request.method == 'POST':
email = request.POST['email']
fd = open('emaildb.csv','a')
fd.write(email+',somefile\n')
fd.close()
return render(request, 'receipts/email.html', {'text':'Thanks, we''ll get back to you soon.'})
else:
return render(request, 'receipts/email.html',)
email.html:
<form action="email" method="post" enctype="text/plain">
{% csrf_token %}
E-mail:<br>
<input type="text" name="email">
<input type="submit" value="Send">
</form>

U can't call method like that
<form action="email" method="post" enctype="text/plain">
{% csrf_token %}
E-mail:<br>
<input type="text" name="email">
<input type="submit" value="Send">
</form>
in your urls.py u must write
url(r'^email/$', views.email, name='email')
and call this method using form like that
<form action="{% url 'your_folder_name_where_located_your_urls.py:email'%}" method="post" enctype="text/plain">
{% csrf_token %}
E-mail:<br>
<input type="text" name="email">
<input type="submit" value="Send">
</form>

Related

Two HTML Forms in one DJango views

I have two simple HTML forms on one page. I want to create Django view to submit multiple Django forms. I can submit form1 but I have no clue how to submit form2.
There is lot of material on internet but they are all about Djanog forms. Please help me with HTML form submission.
HTML Form
<form action="" method=post name="form1" id="form1">
<input type="text" id="input_form1" name="input_form1">
<button type="submit">Submit</button>
</form>
<form action="" method=post name="form2" id="form2">
<input type="text" id="form2" name="form2">
<button type="submit">Submit</button>
</form>
Views.py
def index(request):
if request.method == 'POST':
input_form1 = request.POST.get('input_form1')
return render(request, 'index.html', params)
Please elaborate how to integrate form2 in Views.py
you can put hidden input inside of each form to identify them
index.html
<form action="" method="post">
{% csrf_token %}
<input type="text" id="input_form1" name="input_form1">
<button type="submit">Submit</button>
<input type="hidden" name="which_form_is_it" value="this_is_form_1">
</form>
<form action="" method="post">
{% csrf_token %}
<input type="text" id="input_form2" name="form2">
<button type="submit">Submit</button>
<input type="hidden" name="which_form_is_it" value="this_is_form_2">
</form>
views.py
def index(request):
if request.method == 'POST':
#watch output in console
print(request.POST)
which_form_is_submiting = request.POST["which_form_is_it"]
if str(which_form_is_submiting) == "this_is_form_1":
#here is yor logic for data from form 1
form_1_input = request.POST["input_form1"]
if str(which_form_is_submiting) == "this_is_form_2":
#here is your logic for data from form 2
form_2_input = request.POST["input_form2"]
return render(request, 'index.html', params)

Reset Password Using Django

I am trying to reset password using Django but I am getting the following error:
Method Not Allowed (POST): /reset/done/
Method Not Allowed: /reset/done/
Below are my forms:
Form Which Sent Link To My Email
<form action="{% url 'reset_pass' %}" method="post">
{% csrf_token %}
<div class="form-group">
<input type="email" class="form-control" name="email" placeholder="Email" required autofocus>
</div>
<input type="submit" value="Send Email" class="btn btn-primary btn-block">
</form>
Form Which I Get On Clicking That Link
<form action="{% url 'password_reset_complete' %}" method="post">
{% csrf_token %}
<div class="form-group">
<input type="password" class="form-control" name="new_pass" placeholder="New Password" required autofocus>
</div>
<div class="form-group">
<input type="password" class="form-control" name="confirm_pass" placeholder="Confirm Password" required>
</div>
<input type="submit" value="Update Password" class="btn btn-primary btn-block">
</form>
URL
path('reset/pass/', views.reset_pass, name='reset_pass'),
path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="feebeeapp/reset_form.html"), name='password_reset_form'),
path('reset/done/', auth_views.PasswordResetCompleteView.as_view(template_name='feebeeapp/login.html'), name='password_reset_complete')
Not sure, what I am doing wrong. Can someone please guide me?
Your form is submitting to the wrong view. You are supposed to make a POST request to a PasswordResetConfirmView view.
If your PasswordResetConfirmView is thus registered as:
path('reset/', auth_views.PasswordResetView.as_view(), name='password_reset')
then in your form you work with:
<form action="{% url 'password_reset' %}" method="post">
…
</form>
Normally you already use this view to render the form. So you submit a POST request to the same view.
This view will send an email with a reset link, and then will redirect to the password_reset_complete view.

Django 'float' object has no attribute 'user' while using login decorator

I'm trying to build a django app and the app works, great so far.
Right now i'm in the middle of making sure the user needs a login so they can log in.
if the user is logged in than the user can use an machine-learning model to solve a problem.
The error message I'm getting is 'float' object has no attribute 'user' and this started after I used the #login_required function in django.
NOTE: The user is login in via the localhost:8000/admin/ panel Django provides.
(later I will change that) after I fix this bug
views.py
def home(request):
return render(request, 'home.html')
#login_required
def dashboard(request):
return render(request, 'index.html')
#login_required
def getPredictions(temp_normal, hour,hour_x,hour_y):
import pickle
model = pickle.load(open("test_model.sav", "rb"))
prediction = model.predict([[temp_normal, hour,hour_x,hour_y]])
return prediction
#login_required
def result(request):
temp_normal = float(request.GET['temp_normal'])
hour = float(request.GET['hour'])
hour_x = float(request.GET['hour_x'])
hour_y = float(request.GET['hour_y'])
result = getPredictions(temp_normal, hour,hour_x,hour_y)
return render(request, 'result.html', {'result': result})
html code
index.html
{% extends "base.html" %}
{% block content %}
<div class="content">
<div class="row">
<div class="col-lg-4">
<div class="card card-tasks">
<h1> </h1>
<form action="{% url 'result' %}">
{% csrf_token %}
<p>temp_normal:</p>
<input class="form-control" type="text" name="temp_normal">
<br>
<p>Weging:</p>
<input class="form-control" type="text" name="Weging">
<br>
<p>str:</p>
<input class="form-control" type="text" name="straling">
<br>
<p>hour:</p>
<input class="form-control" type="text" name="hour">
<br>
<p>hour_x:</p>
<input class="form-control" type="text" name="hour_x">
<br>
<p>hour_y:</p>
<input class="form-control" type="text" name="hour_y">
<br>
<input class="form-control" type="submit" value='Bereken'>
</form>
</div>
</div>
</div>
</div>
{% endblock content %}
results.html
{% extends "base.html" %}
{% block content %}
<h1>Prediction</h1>
{{ result }}
<p>resultaat</p>
{% endblock content %}
the decorator login_required is just for views and expects a request object as first param, thats why the error, getPredictions is not a view is just a function. remove the decorator login_required to getPredictions and will work.

Django : How to differentiate post requests from different pages that are coming to the same page?

I have two pages both containing form. However both the pages are sending post request to the same page. How do I differentiate which page has sent the request.
dummy.html(first page)
<form action="/nda" method='POST'>
{% csrf_token %}
<button type="submit" name="submit" id="submit" value="I Agree" target="_blank">I Agree</button>
<button onclick="window.open('/greeting')" target="_blank"> I Disagree </button></br>
</form>
This page redirects to nda page.
nda.html(second page)
This page also redirects to the same page.
<form action="/nda" method='POST'>
{% csrf_token %}
<button type="submit" name="submit" id="submit" value="I Agree" target="_self">I Agree</button>
<button onclick="window.open('/greeting')" target="_self"> I Disagree </button></br>
</form>
My question is, how do I differentiate in my view that from which page it was coming from the page dummy or the same page that was nda.
views.py
def nda(request):
if request.method=='POST' :
# if this is from dummy I want to do this
return render(request,'mainapp/nda.html',{'user':email.split('#')[0]})
if request.method=='POST' :
# if this is from same page that is nda I want to do this
return render(request,'mainapp/home.html')
I am unable to figure out, how do I handle both cases differently
If I understand your question properly,you can use the name attribute in your submit button
<button type="submit" name="submit1" id="submit" value="I Agree" target="_blank">I Agree</button
<button type="submit" name="submit2" id="submit" value="I Agree" target="_blank">I Agree</button
And in the views
def nda(request):
if request.method=='POST' and 'submit1' in request.POST :
# do something
return render(request,'mainapp/nda.html',{'user':email.split('#')[0]})
elif request.method=='POST' and 'submit2' in request.POST:
#do something else
...
How it works ?
You click on the submit button and the server is accessing ..
A button with type submit follows the "action" path specified in the form tag
That is, so that you have a request for different pages, you need to create an additional url, views and html
Example:
one_html.html
<form action="{% url your_app:name1 %}" method='POST'>
{% csrf_token %}
<button type="submit" name="submit" id="submit" value="I Agree" target="_blank">I Agree</button>
<button onclick="window.open('/greeting')" target="_blank"> I Disagree </button></br>
</form>
urls.py:
...
url(r'^' + app_name + 'some_path', views_one, name='name1'),
views.py:
def views_one(request):
if request.method=='POST':
# do something
Exapmle:
two_html.html
<form action="{% url your_app:name2 %}" method='POST'>
{% csrf_token %}
<button type="submit" name="submit" id="submit" value="I Agree" target="_blank">I Agree</button>
<button onclick="window.open('/greeting')" target="_blank"> I Disagree </button></br>
</form>
urls.py:
...
url(r'^' + app_name + 'some_path', views_two, name='name2'),
views.py:
def views_two(request):
if request.method=='POST':
# do something
The difference is that the action points to a different url and thus will be called different views

Flask request.form[] not pulling data

I am trying to post a simple html form and pull the data into python/flask. request.form does not appear to be pulling my form data.
I have a function created to pull the variables if the request method is POST, but the URL ends up with the variables being blank. See code below
#app.route('/inquire',methods=['POST','GET'])
def inquire():
if request.method == 'POST':
name = request.form['dname']
email = request.form['demail']
message = request.form['dmessage']
return
redirect(url_for('inquire_success',name=name,email=email,message=message))
return render_template('inquire.html')
#app.route('/inquiresuccess/',methods=['POST','GET'])
def inquire_success(name,email,message):
return render_template('inquiresuccess.html',name=name,email=email,message=message)
the html below :
<div class="container">
<div class="main">
<form method="post" class="form" action="{{
url_for('inquire_success' }}">
<h2>Inquire below and we'll get back to you</h2>
<label>Name :</label>
<input type="text" name="dname" id="dname" value="name">
<label>Email :</label>
<input type="text" name="demail" id="demail" value="email">
<label>Project info :</label>
<textarea class="messagebox" name="dmessage" id="dmessage"
value="message">
</textarea>
<input type="submit" name="submit" id="submit" value=Submit>
</form>
I would like the code to redirect me to inquiresuccess.html with the variables displayed. Thanks for any help.
The form looks to be posting to the wrong endpoint. Try changing
<form method="post" class="form" action="{{ url_for('inquire_success' }}">
to
<form method="post" class="form" action="{{ url_for('inquire' }}">

Categories

Resources