I've searched through similar questions, but nothing seems relevant to my situation.
Why does this code work fine:
<form action="/signup/" method="post">
{% csrf_token %}
[FORM]
</form>
but
<form id="signup-form">
{% csrf_token %}
[FORM]
</form>
<script type="text/javascript">
$(function() {
$(".submit-signup").on("click", function() {
var user = $("#signup_form").serialize();
console.log(user);
$.post("/signup/", user, function() {
});
});
});
</script>
not work?
Here is signup in views.py:
#requires_csrf_token
def signup(request):
[STUFF]
return render(request, 'signup.html', {[STUFF}})
What else can I provide that would help? Basically I am trying to take a page and turn it into a modal that does the same thing.
Thanks!
you are doing an ajax post call for which you need to give csrf token also:
$.post("/signup/", {
user: user,
csrfmiddlewaretoken: '{{ csrf_token }}'
}, function() {
// success todo
}, function(){
// fail todo
});
Related
I have a Django project with a form in an HTML file, and I'd like to update the text on the submit button of that form WITHOUT a page reload. Essentially:
I click submit on the form
Python handles the submit with the form data
The button text is updated to say "show result"
If I understand correctly, I have to use AJAX for this. The problem is that the form submit relies on an API call in Python, so the HTML essentially has to always be "listening" for new data broadcasted by the views.py file.
Here's the code I have (which doesn't work, since when I hit submit I'm greeted by a page with the JSON response data and nothing else):
views.py:
def home(request):
if request.method == "POST":
print("Got form type", request.content_type)
return JsonResponse({"text": "show result"})
return render(request, 'home.html')
home.html:
<div class="content" onload="document.genform.reset()">
<form name="genform" autocomplete="off" class="form" method="POST" action="" enctype="multipart/form-data">
{% csrf_token %}
<div class="title-sect">
<h1>AJAX Test Form</h1>
</div>
<div class="submit">
<button id="submit" type="submit">Submit</button>
</div>
</form>
</div>
<script type="text/javascript">
function queryData() {
$.ajax({
url: "/",
type: "POST",
data: {
name: "text",
'csrfmiddlewaretoken': '{{ csrf_token }}',
},
success: function(data) {
var text = data['text'];
var button = document.getElementById('submit');
button.innerHTML = text;
setTimeout(function(){queryData();}, 1000);
}
});
}
$document.ready(function() {
queryData();
});
</script>
I've imported jQuery with the script <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js"></script>. Any idea why this doesn't work in its current state? Thanks!
I am doing a project management tool web application. I would like user can choose 'user' from dropdown selection, click 'Add member', then the member will show somewhere under the member?. Here is what I am doing.
Please do not worry about the styling. I have not done UI yet.
view.py
def member_select(request):
if request.method == 'GET':
selection = request.GET.get('id',None)
if selection:
selected_member = User.objects.filter(pk=selection)
return selected_member
project_index.html
<form action="" method="GET" id="selection-form">
{% csrf_token %}
<select id="member_list">
{% for user in user %}
<option>
{{ user.username }}
</option>
{% endfor %}
</select>
<input type="button" value="Add member" id="selection-button">
</form>
base.html
<script>
var url = $( '#selection-form' ).attr( 'action' );
$("selection-button").onclick(function (e) {
e.preventDefault();
$.ajax({
type:'GET',
url:url,
data:{
id:$('#member_list').val()
},
success:function (result) {
alert('okay');
},
error:function (result) {
alert('error');
}
});
});
</script>
Maybe use an empty <p class='member-name'><p> and
after choosing in the jquery success function
change to
success:function (result) {
$('.member-name').text(result);
},
try this (not fully tested)
from django.core import serializers
from django.http import HttpResponse
def member_select(request):
selection = request.GET.get('id',None)
if selection:
data = serializers.serialize('json',User.objects.filter(pk=selection))
else:
data = {}
return HttpResponse(data, content_type='application/json')
from the docs https://docs.djangoproject.com/en/2.0/topics/serialization/
In javascript ajax funtion the response should be a user object if exists or empty json string
<form action="" method="GET" id="selection-form">
{% csrf_token %}
<select id="member_list">
{% for user in user %}
<option value="{{user.pk}}">{{ user.username }}</option>
{% endfor %}
</select>
<input type="button" value="Add member" id="selection-button">
</form>
<di id='res'></div>
$("#selection-button").on('click', function(e) {
e.preventDefault();
var value =$('#member_list').val();
$.ajax({
type:'GET',
url:'.',
data:{
id:value
},
success:function (result) {
alert('okay');
$('#res').append(result);
console.info(result);
},
error:function (result) {
alert('error');
}
});
});
I am trying to take username input and return in ajax call whether the username is taken or not in Django. But the method in DJango is not taking the input. I am sharing the code here.
URL.py
url(r'^search_username/$', user.views.search_product, name="search_username"),
script + HTML
{% load staticfiles %}
{% block content %}
<form method="post">
{% csrf_token %}
<input name="search" id="search" type="text"/>
<button type="submit">Sign up</button>
</form>
{% endblock %}
$("#search").change(function () {
var username = $(this).val();
$.ajax({
url: '/search_username/',
data: {
'username': username
},
dataType: 'json',
error: function(){
alert('failure');
},
success: function (data) {
if (data.is_taken) {
alert("A user with this username already exists.");
}
}
});
});
Views.py
def search_username(request):
print('Entered into search')
username = request.GET.get('search', None)
print(username)
data = {
'is_taken': allproductlist.objects.filter(product_name_english__iexact=username).exists()
}
return JsonResponse(data)
The problem is it prints Entered into search.But when I print username it shows NOne. Can anyone please specify what is happening ?
Your Ajax is sending the data as "username" but your Python is looking for "search".
you are sending username in ajax request but you are getting search in views.py.
you can Update your ajax code:
$("#search").change(function () {
var username = $(this).val();
$.ajax({
url: '/search_username/',
data: {
'search': username
},
dataType: 'json',
error: function(){
alert('failure');
},
success: function (data) {
if (data.is_taken) {
alert("A user with this username already exists.");
}
}
});
});
2nd way is that you can change in views.py.
username = request.GET.get('username', None)
I'd like to create dynamic input system, for example when I enter the folder name - the list of files inside automatically show up another input ChoiceField below, so I can choose the file. The methods are already written, the problem is - How can I make it in Django view?
Here is my view:
def get_name(request):
if request.method == 'POST':
form = NameForm(request.POST)
if form.is_valid():
dir_date = format_date(request.POST['date'])
files = os.listdir(os.path.join(path+dir_date))
return render(request, 'inform/show_name.html', {'data': request.POST['your_name'],
'date': format_date(request.POST['date'])})
else:
form = NameForm()
return render(request, 'inform/base.html', {'form': form})
Here is the form class:
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)
date = forms.DateField(widget=forms.DateInput(attrs={'class': 'datepicker'}))
flights = forms.ChoiceField(choices=?)
Finally, here is my template.
{% extends 'inform/header.html' %}
{% block content %}
<script>
$( function() {
$( ".datepicker" ).datepicker();
$( "#anim" ).on( "change", function() {
$( "#datepicker" ).datepicker( "option", "showAnim", $( this ).val() );
});
} );
</script>
<div class="container" style="color: red; size: auto;">
<form class="form-vertical" action="get_name" role="form" method="post">
{% csrf_token %}
<div class="form-group" style="display: inherit">
<center>
{{form}}
<input type="submit" value="OK">
</center>
</div>
</form>
</div>
{% endblock %}
Is there any way to dynamically read the data from the Date input and give it to the method inside the view without clicking the submit button or creating several others? If it can be solved only by ajax, jQuery or JS, could you please give me a simple sample of how it's done? I'm pretty much frustrated by the inability of creating a simple form.
Thank you in advance!
So basically you are doing it right. You already know that you need the on(change) function for the datepicker
Now as soon as the user changes a date, your on(change) function is triggered. So all you need to do now is to the get the new date value, which you already have when you do $( this ).val(). After that make an ajax call to the url corresponding to your method get_name in views.py
Something like this:
$( function() {
$( ".datepicker" ).datepicker();
$( "#anim" ).on( "change", function() {
$( "#datepicker" ).datepicker( "option", "showAnim", $( this ).val() );
send_changed_date_value(variable_with_new_date);
});
});
function send_changed_date_value(new_date) {
$.ajax({
type: // "POST" or "GET", whichever you are using
url: "/url in urls.py corresponding to get_name method in views.py/",
data: new_date,
success: function(response){
console.log("Success..!!")
}
});
}
This is how you can send the new date value to your views, everytime it is changed. If you want to submit the complete form data, i.e., your_name and flights data as well, then you may directly send serialzed data of the form in the data attribute of ajax.
Note -> You will have to return a HttpResponse from your get_name view as an ajax call requires a HttpResponse from the backend to complete the ajax call successfully. You may simply return a string in the response.
I'm allowing users to remove posts through ajax. Posts have a boolean field live_until_removed. When set to false, the post disappears.
When clicking remove I'm given a 403, referencing:
xhr.send( ( s.hasContent && s.data ) || null );
How do I get this to run smoothly? Why this this error happening?
js:
$('#removeForm').submit(function() { // catch the form's submit event
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function(response) {
$('.close-post').html(response); // update the DIV
console.log(response);
},
error: function(response){
console.log(response);
}
});
return false;
});
template:
<div class="close-post">
{% if not post.live_until_removed %}
<form class="" id="removeForm" method="POST" action="">
<button type="submit" class="btn">Remove</button>
</form>
{% else %}
<button class="btn">Removed</button>
{% endif %}
</div>
views.py:
def post(request, id):
...
if request.is_ajax():
try:
post = Post.objects.get(id=id)
post.live_until_removed = False
post.save()
response = simplejson.dumps({"status": "Removed"})
except:
pass
You might have missed to send CSRF token in your request. Look at here; Django-Ajax