Reputation: 2375
I Know This question asked many time.
My CSRF token was working fine. but now it is giving error:
Forbidden (403) CSRF verification failed. Request aborted 2
I try many things like removing cookie, history and changing the full url in form action but nothing is work.
HTML form
<form method="POST" action="/daily_sale/">
{% csrf_token %}
<div class="panel-heading">
<button class="btn btn-primary pull-right">Search</button>
<span class="pull-right"> </span>
<span class="form-group pull-left">
<input type="text" class="form-control" name="start" placeholder="Start Date" value = "{{start_date}}">
</span>
<span class="pull-right"> </span>
<span class="form-group pull-right">
<input type="text" class="form-control" name="end" placeholder="End Date" value="{{end_date}}">
</span>
</div>
</form>
I also try with changing action in form tag
action="http://localhost:9002/daily_sale/"
view.py
from django.shortcuts import render , redirect
@login_required(login_url='/login_form/')
def dailySale(request):
user_id = request.user.id
reports = Reports()
if request.method == 'GET':
# do some thing
if request.method == 'POST':
print "inside post method"
start_date = request.POST.get('start')
end_date = request.POST.get('end')
print "start = ", start_date,"\n end = ",end_date
year = request.POST.get('year')
month = request.POST.get('month')
sale = reports.getSaleData(start_date,end_date,user_id)
day = sale[0]
sale_value = sale[1]
sale_qty = sale[2]
sale_data = zip(day, sale_value, sale_qty)
sal = reports.get_sale_wise_channel(start_date,end_date,user_id)
channel = sal[0]
brand = sal[1]
category = sal[2]
selling_price = sal[3]
quantity_sold = sal[4]
percentage = sal[5]
returns = reports.getReturns(start_date,end_date,user_id)
order_item_ids = returns[1]
order_date = returns[0]
channel = returns[2]
sku = returns[3]
return_data = zip(order_item_ids, order_date, channel,sku)
sal_data = zip(channel,brand,category,selling_price,quantity_sold,percentage)
context_dict = {'sale_data':sale_data,
'sal_data':sal_data,
'start_date':start_date,
'end_date':end_date,
'month':month,
'year':year}
return render(request, 'daily_sale.html', context_dict)
Its working fine with get method or first time when it run.
But when we try with POST method then it is giving error.
Upvotes: 0
Views: 401
Reputation: 11807
To solve (403) CSRF verification
error, you need to update your csrf toke in the request context each time that you render the form:
So add these to your both GET and POST methods
context_dict.update(csrf(request))
And don't forget to import csrf at top of your views:
from django.views.decorators.csrf import csrf_protect
If you still have problem in processing the form, consider using ModelForms which is recommended and more robust way of processing forms in django.
Upvotes: 1