How can I send csrf_token? - javascript

Good afternoon!
Please help me send csrf_token to the POST function for an authorized user. The error is, when I do user registration, error comes out: Forbidden (CSRF token missing.): /data/task.
The link to the library is below (there is also a demo project for this link).
https://docs.dhtmlx.com/gantt/desktop__howtostart_python.html

If you are working with Django, you need to add the csrf_token to your registration form
<form method="post">
{% csrf_token %}
// form here
</form>

Related

django missing csrf token in javascript .submit() function (non ajax)

I am using a javascript to send an html form to django.
js looks like this:
document.getElementById("fooform").submit();
and the html form looks like this:
<form class="form-inline" id="fooform" action ="{% url 'foo:doo' %}" method="post">
{% csrf_token %}
<input type="hidden" id="fooinput" value="" />
</form>
the js can write the data into the input field without any problems and also carry out the submit. my problem is using the crsf token.
I have already put the token {% csrf_token %} in every conceivable place. (Before the form, before the js...). in the html code is the token also correct.
django gives me the error:
Reason given for failure:
CSRF token missing or incorrect.
In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure:
Your browser is accepting cookies.
The view function passes a request to the template's render method.
In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.
If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data.
The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because the token is rotated after a login.
You're seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, and only the initial error message will be displayed.
You can customize this page using the CSRF_FAILURE_VIEW setting.
Edit:
The view.py:
def foo_view(request):
print(request.POST)
urls.py:
app_name = 'foo'
urlpatterns = \
[
path('doo', views.foo_view, name='foo_view'),
]

Send Javascript Push Notification - AFTER Form POST and URL redirection

Use case (Django Project):
I want to log in on my login page -> Therefore I use this form in html (login.html):
<form class="loginform" action="" method="POST">
{% csrf_token %}
<div class="loginform">
{{form.as_p}}
</div>
<br>
<input type="submit" class="btn btn-success loginbtn" value="Login">
</form>
In case of successful log in I will redirect with DJANGO to this URL (localhost/welcome/)-> welcome.html:
LOGIN_REDIRECT_URL = "welcome"
I am able to send javascript notifications with alertify, but only when using simple things such as
click on it or mouseover:
function notification(text) {
console.log(text)
alertify.success(text);
}
I tried it with onsubmit="javascript:notification("")" in the html form tag, however this will
be displayed only BEFORE the URL redirection.
So my question is:
How is it possible to activate /send the push notification AFTER the URL redirection and in
case of successfull POST/ Log in?
I really appreciate your help! Thank you a lot!!
Javascript is client-side. That means your alertify.success(text); will be executed client-side, once server already did his render process.
The authentication process is server-side. So you have to make your server make your alertify a part of the rendered content.
Knowing that, you just have to change your LOGIN_REDIRECT_URL content page to include in it a call to notification:
<!-- your html template comes here -->
<script type="text/javascript">
notification('You are now logged in');
</script>
Be remembered that the notification will then display each time the person visits this page. You may want either to redirect him again, or to introduce a variable in Django to avoid displaying it again.

How to properly append django csrf_token to form in inline javascript?

I have created form element dynamically in javascript:
var selectform = document.createElement("form")
I have added other input elements and these attributes to selectform:
submitnselection.setAttribute('type',"submit");
submitnselection.setAttribute('value',"Submit");
submitnselection.setAttribute("name","submitnpage");
selectform.setAttribute("method", "post")
selectform.setAttribute = ("action", "/test")
"{% csrf_token %}";
In HTML, adding {% csrf_token %} template tag would work, but in this case of javascript i got 403 forbidden error:
CSRF token missing or incorrect.
I have found some solutions but nothing was working for me, is there any way to add {% csrf_token %} to form with only using Django, Javascript and plain Jquery? Also note that this script is inside html, so i think {% csrf_token %} template tag will work.
This should work:
var inputElem = document.createElement('input');
inputElem.type = 'hidden';
inputElem.name = 'csrfmiddlewaretoken';
inputElem.value = '{{ csrf_token }}';
selectform.appendChild(inputElem);
You see, the csrf_token is nothing more that a string which is the value of a hidden input element of a form. That's all!
You can try to append an input field to the form:
// declare an input field
var input = document.createElement('input');
input.type = 'hidden';
input.name = 'csrfmiddlewaretoken';
input.value = '{% csrf_token %}';
// attach field to the form
selectform.appendChild(input);
// submit
If I understand everything, you need to send a csrf token but you don't have any to send to the server from javascript.
From the code in a Django template is very easy to generate a csrf token with the usual {% csrf_token %} Django tag, but this is because the template is being processed in the server to create the final HTML which will be sent to the browser.
When you are in Javascript you can't generate a csrf token so, I think the best solution is creating an invisible tag in the template, probably a hidden input.
<input id="token" type="hidden" value="{% csrf_token %}" ></input>
And when in jQuery get the value with $('#token').attr('value'), I have an example with a jQuery POST method:
token = $('#token').attr('value');
$.post(url, {
'personId': personId,
'csrfmiddlewaretoken': token // This is the important thing
}, function() {}
);
No matter how you do it, you have to send the token with the 'csrfmiddlewaretoken' name and the token value along with the other info you want to send to the server.
I'm editing this with a pure JS solution if you need it. Just say it.

Django: make a POST request on form submit without reloading the page or rendering to another?

I have been struggling with this problem for more than two days, I have looked at similar questions here and to many documentations but nothing helped me. Basically, I am building a Django web application (where people can add themselves as friends) I am using Django package django-friendship, but I want the following to happen: when a user is in someone else profile, the first can click an 'Add friend' button and a friend request must be sent. But I want to achieve this without reloading the page or rendering to another one. The method that has to be triggered in order to send the request is in views.py. Probably I need to use ajax but in what way? My final goal is the button to perform as an 'Add friend' button in facebook, for example (without reloading).
friend_profile.html
<form action="{% url 'users:fr_request' pk=friend.id %}" method="POST">
{% csrf_token %}
<input type="submit" value="Add friend"/>
views.py
def friendship_add(request, pk):
if request.method == 'POST':
to_user = User.objects.get(pk=pk)
from_user = request.user
try:
Friend.objects.add_friend(from_user, to_user)
except AlreadyExistsError as e:
print('Exception when adding a friend ' + e)
else:
return HttpResponse('You added a friend')
return render(request, 'users/friend_profile.html')
urls.py
urlpatterns = [
url(r'users/(?P<pk>\d+)/send/$', views.friendship_add, name='fr_request'),
]
At the moment when submitting the form, I render the page to users/(?P\d+)/send/ which calls the view method and executes Friend.objects.add_friend, but I want this to happen without going to /send/ page or reloading the current?
This can be easily achieved using jQuery. You may want to assign an id to your form in case there are multiple forms in your page:
<form action="{% url 'users:fr_request' pk=friend.id %}" method="POST" id="friend_form">
{% csrf_token %}
<input type="submit" value="Add friend"/>
The script could then look like that:
$(function() {
$("#friend_form").submit(function(event) {
// Stop form from submitting normally
event.preventDefault();
var friendForm = $(this);
// Send the data using post
var posting = $.post( friendForm.attr('action'), friendForm.serialize() );
// if success:
posting.done(function(data) {
// success actions, maybe change submit button to 'friend added' or whatever
});
// if failure:
posting.fail(function(data) {
// 4xx or 5xx response, alert user about failure
});
});
});
For more information and examples refer to the jQuery.post() documentation.

submit form in ruby on rails where action is your full url

So a follow up to this question: getting bad request from ruby on rails ssl post.
I fixed that problem and I make the next step in the transaction no problem. The problem I am facing is that their response is sent to an iFrame as a hidden form on an html document. The form then posts to a url that I provide them.
I have tried giving them localhost:3000/policies/complete making a controller action and a route resource for the post but it doesn't ever show anything.
- It just says javascript error unable to load resource: localhost:3000/policies/complete
So then I tried just /policies/complete (with the coresponding method in my policies controller complete) but for some reason instead of posting to that action - it posted to theirwebserver.com/policies/complete which obviously doesn't exist.
So since it looks like I have to pass in a whole url for it to work correctly the form is going to look like: <form method='Post' action='whatever whole url I give them'>
The form looks like this:
<form name="frmReturn" method="Post" action="localhost:3000/policies/hosted_checkout_complete">
<input name="PaymentID" type="hidden" value="the value you need really badly!">
<input name="ReturnCode" type="hidden" value="0">
<input name="ReturnMessage" type="hidden" value="Your transaction has been approved.">
</form>
Tl:DC How do I set up my app to handle that?
I can request that they use get to send the information back to me. If that would be easier to set up and accept please let me know!
You need to add the protocol (either http:// or https://) to the front of the action=
<form name="frmReturn" method="Post" action="http://localhost:3000/policies/hosted_checkout_complete">
However, I would NOT recommend doing this... You have completely missed the point of Rails routing. You should be doing something like this:
<form name="frmReturn" method="Post" action="<%= resource_url %>">
Ideally, you'd use the Rails form builders:
<%= form_for :resource, :action => 'hosted_checkout_complete' do %>

Categories