Forbidden (403) CSRF verification failed - django

When I click on ok button in add_tech.html then it will redirect me on upload_type.html.
But it show error while clicking on ok button.
ERROR -
Forbidden (403)
CSRF verification failed. Request aborted.
Help
Reason given for failure:
CSRF token missing or incorrect.
My template(add_tech.html) -
<form action="/uploads/type/" method="post">
<label for="your_name">New Tech: </label>
<input id="your_name" type="text" name="your_name" value="{{ current_name }}">
<input type="submit" value="OK">
</form>
My Template(upload_type.html)-
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{form}}
</form>
My View.py -
def upload_type(request):
if request.method =='POST':
details = NameForm(request.POST)
if details.is_valid():
return render(request, "core/upload_type.html", {'form':details})
else:
details = NameForm()
return render(request, 'core/upload_type.html', {'form': details})
My Url.py -
urlpatterns = [
url(r'^uploads/type/$', views.upload_type, name='upload_type'),]
My form.py -
from uploads.core.models import Name
class NameForm(forms.ModelForm):
class Meta:
model = Name
fields = ('your_name', )
My Models.py-
class Name(models.Model):
your_name = models.CharField(max_length=100)

You need to have the csrf token like this for your post method in the django template
<form action="/uploads/type/" method="post">
{% csrf_token %}
<label for="your_name">New Tech: </label>
<input id="your_name" type="text" name="your_name" value="{{ current_name }}">
<input type="submit" value="OK">
</form>

For POST request, csrf token is required. So in your template, add `{% csrf_token %}.
<form action="/uploads/type/" method="post">
{% csrf_token %}
<label for="your_name">New Tech: </label>
<input id="your_name" type="text" name="your_name" value="{{ current_name }}">
<input type="submit" value="OK">
</form>
From the Docs:
Django ships with an easy-to-use protection against Cross Site Request
Forgeries. When submitting a form via POST with CSRF protection
enabled you must use the csrf_token template tag as in the preceding
example.

Related

Submitting dynamically created input field in django

am working on a project with Django, i dynamically created an input field and am trying to submit it, but i could not do so, i searched online and i saw that it could be done with formset_factory but when i tried it, i got this error
CatName = int(float(request.POST.get('CatName')))
TypeError: float() argument must be a string or a number, not 'NoneType'
here is my code
the form.html
<form action="." method="post" id="PostCat__form">{% csrf_token %}
<input type="hidden" name="deyHidden" value="category_hidden">
{% comment %} {{ catForm | crispy }}
<input type="hidden" name="deyHidden" value="category_hidden"> {% endcomment %}
<input type="text" class="form-control" name="CatName[]" >
<input type="text" class="form-control" name="CatName[]" >
<input type="text" class="form-control" name="CatName[]" >
<input type="text" class="form-control" name="CatName[]" >
<div class="form-group">
<h6 id="PostCat__show"></h6>
<img src=" {% static 'images/ajax-loader.gif' %}" style="Display:none;" id="PostCat__img">
<button class="btn btn-outline-info" type="submit" id="PostCat__submit">Create</button>
</div>
</form>
the model.py
class Category(models.Model):
CatName = models.CharField(max_length=100)
the view.py
myFormCat = CatPostForm(request.POST)
CatName = int(float(request.POST.get('CatName')))
# print(CatName)
formset = formset_factory(FormsetForm, CatName=CatName)(request.POST)
if myFormCat.is_valid() and formset.is_valid():
for form_c in formset:
if not form_c.cleaned_data['CatName']:
Category.objects.get_or_create(CatName=CatName)
response_data = {
'SType': 'success',
'message': "Saved Successfully"
}
return HttpResponse(json.dumps(response_data), content_type="application/json")
the forms.py
class CatPostForm(forms.ModelForm):
class Meta:
model=Category
fields = ['CatName']
pls how can i do it so that i can successfully submit the form,
on your views.py
from django.forms import formset_factory
CatPostFormSet = formset_factory(CatPostForm)
catformset = CatPostFormSet() #this goes to your page context. do the validations here also after the post
on your form.html
<form method="post">
{{ formset.management_form }}
{{formset}}
</form>

django-ckeditor request dont get changes in form

I have one form called in ajax function, this function return one django form with one ckeditor field.
This field is displayed without problems, but when I make a request, the field value, dont sended in request, but if I make another, in the same form, with the same values, the value is update and is sended in request.
My form field
class EditCommentForm(IdeiaForm):
content = forms.CharField(
max_length=settings.COMMENT_TEXT_LIMIT if hasattr(settings, "COMMENT_TEXT_LIMIT") else 10000,
required=True,
widget=CKEditorWidget(config_name='question')
)
comment_id = forms.IntegerField(required=True)
My html template
<form class="create-comment" data-group-class=".comment-group" data-ajaxform="true" data-toggle="replace" class="create-comment" data-update="#{{ to_update }}" action="{% url 'comment:edit' %}" method="post">{% csrf_token %}
<div class="comment-group create-comment-body{% if form.content.errors %} has-error{% endif %}">
<textarea name="content" class="form-control" placeholder="Deixe seu comentário">{{ instance.content }}</textarea>
<span class="help-block"></span>
</div>
<input name="comment_id" value="{{ instance.id }}" type="hidden"/>
<div class="create-comment-footer">
<input type="submit" value="Editar" class="btn btn-primary">
</div>
</form>

Django url parsing error

OK,
I have two different views, both in the project site-wide area.
urls.py
url(r'^accounts/login/$', 'taxo.views.login'),
url(r'^accounts/invalid/$', 'taxo.views.invalid'),
...
taxo/views.py
def login(request):
c = {}
c.update(csrf(request))
return render_to_response('login.html', c)
def invalid(request):
return render_to_response('invalid.html',{'title':'invalid'})
templates/login.html
<form action="/accounts/auth/" method="post">{% csrf_token %}
<label for="username">User name</label>
<input type="text" name="username" value="" id="username">
<label for="password">Password</label>
<input type="password" name="password" value="" id="password">
<input type="submit" value="login" />
</form>
templates/invalid.html
<form style="float: right" action="accounts/login/" method="post">
{% csrf_token %}
{{form}}
<input type="submit" value="Login" class="search"/>
</form>
With the above code, I got Page not Found error
Page not found (404)
Request Method: POST
Request URL: http://127.0.0.1:8000/accounts/invalid/accounts/login/
Django parses the requested url as relative to the url of the current page. When I replaced the action with the {% url %} tag. I got a NoReverseMatch at /accounts/invalid/ error
How do I do this correctly?
Try this:
<form style="float: right" action="/accounts/login/" method="post">
{% csrf_token %}
{{form}}
<input type="submit" value="Login" class="search"/>
</form>
And here's the reason:
Request URL: http://127.0.0.1:8000/accounts/invalid/accounts/login/
$ at the end of regex means nothing's after slash:
url(r'^accounts/login/$', 'taxo.views.login', name='login'),
url(r'^accounts/invalid/$', 'taxo.views.invalid', name='invalid'),
therefore you may use those urls:
http://127.0.0.1:8000/accounts/login/
http://127.0.0.1:8000/accounts/invalid/
edit:
why one of your URLs in template redirects begins with slash and one without? Try this one:
<form style="float: right" action="{% url 'login' %}" method="post">

form.is_valid() returning false

I have a Model class.
class Search(forms.Form):
query=forms.CharField()
And, a view function.
def search(request):
c = {}
c.update(csrf(request))
if request.method == 'POST':
form = Search(request.POST)
if form.is_valid():
search_query=form.cleaned_data['query']
return HttpResponse("your query: %s" %search_query , c)
else:
return HttpResponse(form , c)
else:
return render_to_response('polls/search.html', c)
And, here is my search.html:
<form action="/polls/search" method="post">{% csrf_token %}
<p><label for="query_label">query:</label>
<input type="text" name="query_txt" id="query_txt_id" /></p>
<input type="submit" value="Submit" />
</form>
After giving some characters as input, it always show me the following as plain text(Not as error).
"A server error occurred. Please contact the administrator."
The id of your query field is incorrect. Django expects it to be id_query.
You don't need to hardcode your form inputs. If you include {{ form.as_p }} in your template, Django will render the form correctly.
<form action="/polls/search" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
If you really want to hardcode the form in the template, start with the working html that Django produces, and customize it from there. Note that the forms in your template and the snippet below do not display errors. See the docs on customizing the form template for more details.
<form action="/polls/search" method="post">{% csrf_token %}
<p><label for="id_query">Query:</label> <input type="text" name="query" id="id_query" /></p>
<input type="submit" value="Submit" />
</form>

Add an additional form with django-registration

I have a registration form that is rendered by the following urlconf --
url(r'^$',
register,
{'backend': 'registration.backends.default.UserBackend',
'template_name': 'index.html'},
name='auth_index'),
In the template, I have the following --
<form method="post" action=".">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Register" />
</form>
How would I add additional forms and context to this template? I want to be able to have something like the following --
<form method="post" action=".">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Register" />
</form>
...
<form action='{% url waiting_list %}' method='post'>{% csrf_token %}
<p>Enter your email: <input type="text" name="email" value=""></p>
<input type="submit" name="email_submit" value="Submit Email">
</form>
{{message}}
How could I do this? (Preferably, all within a view). Thank you.
Your template is OK. Now you add the waiting_list url to your uelconf and implement it's view:
url(r'^waiting_list/$', 'myapp.views.waiting_list', {}, name='waiting_list'),
and:
# myapp/views.py
def waiting_list(request):
...
Since this is not data critical form, I would probably use #csrf_exempt to bypass csrf validation to makes thing easier. In case of error, redirect to an error page.
(BTW, usability wise, a better implementation for this problem might be posting the email with javascript.)