17π
Use the render
shortcut which adds RequestContext
automatically.
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, render
from steps_count.models import Top_List
from steps_count.forms import Top_List_Form
def index(request):
if request.method == 'POST':
#form = Top_List_Form(request.POST)
return HttpResponse("Do something") # methods must return HttpResponse
else:
top_list = Top_List.objects.all().order_by('total_steps').reverse()
#output = ''.join([(t.name+'\t'+str(t.total_steps)+'\n') for t in top_list])
return render(request,'steps_count/index.html',{'top_list': top_list})
- [Django]-The number of GET/POST parameters exceeded settings.DATA_UPLOAD_MAX_NUMBER_FIELDS
- [Django]-How do I use Django templates without the rest of Django?
- [Django]-Django-taggit β how do I display the tags related to each record
12π
add it to the setting file
CSRF_TRUSTED_ORIGINS = [
'https://appname.herokuapp.com'
]
- [Django]-Generating file to download with Django
- [Django]-Django's Double Underscore
- [Django]-Django catch-all URL without breaking APPEND_SLASH
9π
When you found this type of message , it means CSRF token missing or incorrect. So you have two choices.
-
For POST forms, you need to ensure:
-
Your browser is accepting cookies.
-
In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.
-
-
The other simple way is just commented one line (NOT RECOMMENDED)(βdjango.middleware.csrf.CsrfViewMiddlewareβ) in MIDDLEWARE_CLASSES from setting tab.
MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', # 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
- [Django]-Allow only positive decimal numbers
- [Django]-How can I check if a Python unicode string contains non-Western letters?
- [Django]-How do I get multiple values from checkboxes in Django
6π
One more nicest alternative way to fix this is to use '@csrf_exempt'
annotation.
With Django 3.1.1
you could just use @csrf_exempt
on your method.
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def index(request):
and you donβt need to specify {% csrf_token %}
in your html.
happy learning..
- [Django]-How to understand lazy function in Django utils functional module
- [Django]-Case insensitive urls for Django?
- [Django]-This QueryDict instance is immutable
3π
A common mistake here is using render_to_response (this is commonly used in older tutorials), which doesnβt automatically include RequestContext. Render does automatically include it.
Learned this when creating a new app while following a tutorial and CSRF wasnβt working for pages in the new app.
- [Django]-Getting database values using get_object_or_404
- [Django]-Why do we need to use rabbitmq
- [Django]-CharField with fixed length, how?
2π
In your HTML header, add
<meta name="csrf_token" content="{{ csrf_token }}">
Then in your JS/angular config:
app.config(function($httpProvider){
$httpProvider.defaults.headers.post['X-CSRFToken'] = $('meta[name=csrf_token]').attr('content');
}
- [Django]-How can I get the full/absolute URL (with domain) in Django?
- [Django]-How can I skip a migration with Django migrate command?
- [Django]-Django template comparing string
- [Django]-How to make Django template engine to render in memory templates?
- [Django]-How to repeat a "block" in a django template
- [Django]-Exclude a field from django rest framework serializer
0π
function yourFunctionName(data_1,data_2){
context = {}
context['id'] = data_1
context['Valid'] = data_2
$.ajax({
beforeSend:function(xhr, settings) {
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
if (settings.url == "your-url")
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
},
url: "your-url",
type: "POST",
data: JSON.stringify(context),
dataType: 'json',
contentType: 'application/json'
}).done(function( data ) {
});
- [Django]-Transaction managed block ended with pending COMMIT/ROLLBACK
- [Django]-Django, template context processors
- [Django]-How to use Django model inheritance with signals?
0π
If you put {%csrf_token%}
and still you have the same issue, please try to change your angular version. This worked for me. Initially I faced this issue while using angular 1.4.x version. After I degraded it into angular 1.2.8, my problem was fixed. Donβt forget to add angular-cookies.js and put this on your js file.
If you using post request.
app.run(function($http, $cookies) {
console.log($cookies.csrftoken);
$http.defaults.headers.post['X-CSRFToken'] = $cookies.csrftoken;
});
- [Django]-Numpy Array to base64 and back to Numpy Array β Python
- [Django]-Django Cannot set values on a ManyToManyField which specifies an intermediary model. Use Manager instead
- [Django]-How to show a message to a django admin after saving a model?
0π
USE decorator:
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def method_name():
# body
- [Django]-Django models: Only permit one entry in a model?
- [Django]-Django: 'current_tags' is not a valid tag library
- [Django]-Get django object id based on model attribute
- [Django]-Django 'AnonymousUser' object has no attribute '_meta'
- [Django]-Is Django for the frontend or backend?
- [Django]-Why is using thread locals in Django bad?
0π
<form action="/steps_count/" method="post">
{% csrf_token %}
Name: <input type="text" name="Name" /><br />
Steps: <input type="text" name="Steps" /><br />
<input type="submit" value="Add" />
</form>
Check your alignment it should be one space inside the form. Thatβs where almost everyone makes mistakes.
- [Django]-Django REST Framework: raise error when extra fields are present on POST
- [Django]-Django : mysql : 1045, "Access denied for user
- [Django]-Find all references to an object in python
0π
I got the same error below:
CSRF verification failed. Request aborted.
Because I did not set csrf_token tag in <form></form>
with method="post"
as shown below:
<form action="{% url 'account:login' %}" method="post">
{% comment %} {% csrf_token %} {% endcomment %}
...
</form>
So, I set csrf_token
tag in <form></form>
with method="post"
as shown below, then the error was solved:
<form action="{% url 'account:login' %}" method="post">
{% csrf_token %}
...
</form>
In addition, whether or not you set csrf_token
tag in <form></form>
with method="get"
as shown below, then there is no error. *only get
and post
request methods can be set to method
for <form></form>
but not head
, put
and so on according to the answer:
<form action="{% url 'account:login' %}" method="get">
{% comment %} {% csrf_token %} {% endcomment %}
...
</form>
<form action="{% url 'account:login' %}" method="get">
{% csrf_token %}
...
</form>
- [Django]-Nginx uwsgi (104: Connection reset by peer) while reading response header from upstream
- [Django]-Naming Python loggers
- [Django]-UUID('β¦') is not JSON serializable
-1π
1) {% csrf_token %} is not in template
β or β
2) {% csrf_token %} is outside of html-form
- [Django]-Why does Django's render() function need the "request" argument?
- [Django]-110: Connection timed out (Nginx/Gunicorn)
- [Django]-How can I render a ManyToManyField as checkboxes?