I am pretty new to Django and I am trying to figure out how to add content dynamically coming from a python script without reloading a page.
Currently, I have two functions in my views.py file. One handles uploading a file (home), and the other handles calling a python script and handling the file (handle). The reason I separated it like this is because I want to sequentially populate a HTML table as the python script works with the uploaded file.
However, my ajax function is not receiving any data from the handle function's http response and I am not sure why. Neither the success nor the error functions are being called. This is really strange because the print statement in the handle function in views.py prints successfully with data.
Views.py
i=0
uploaded_file = None
def home(request):
if (request.method == 'POST'):
file_form = UploadFileForm(request.POST, request.FILES)
if file_form.is_valid():
global uploaded_file
uploaded_file = request.FILES['file']
print(uploaded_file)
else:
file_form = UploadFileForm()
return render(request, 'personal/home.html', {'form': file_form})
def handle(request):
# TODO make ajax wait for a response from 'home'
# so I don't have to wait for 1 second
time.sleep(1)
data = {}
data['Name'] = fileName(uploaded_file)
if(request.is_ajax()):
print(data) # prints succesfully
return HttpResponse(json.dumps(data),
content_type="application/json")
home.html
<script type = "text/javascript" language = "javascript">
function post_tables(data) {
alert(data)
}
$(document).ready(function(post_tables) {
$("#upload").click(function(event){
$.ajax( {
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "get",
url:'/handler',
success: function(data) {
console.log("over here")
post_tables(data)
},
error: function(data) {
console.log("down here")
post_tables("error being thrown")
}
});
});
});
</script>
urls.py
urlpatterns = [
path(r'', views.home, name='home'),
path(r'handler', views.handle, name='handle'),
]
I explained the whole process ajax django to you. Perhaps your problem will be solved. good luck.
views.py
def handle(request):
if request.method == 'POST':
data = request.POST
field_example = data.get('field_example')
return JsonResponse(data)
else:
data = request.GET
field_example = data.get('field_example')
return JsonResponse(data)
home.html
<form id="upload">
{% csrf_token %}
<input type="text" name=field_example>
.
.
.
</form>
urls.py
urlpatterns = [
path(r'', views.home, name='home'),
path(r'handler/', views.handle, name='handle'),
]
js code in home.html:
$("#upload").submit(function (e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: "{% url 'handle' %}",
type: 'GET',
data: formData,
cache: false,
contentType: false,
processData: false,
success: function (data) {
console.log("over here")
post_tables(data)
},
error: function (data) {
console.log("down here")
post_tables("error being thrown")
}
});
});
Related
Views.py (View function)
#csrf_exempt
def updateLogs(request):
print("Log AJAX call")
return HttpResponse("Hello")
javascript file
function updateConsoleLogOnPage(var1){
jobName = var1.value;
alert(jobName);
$.ajax({
type: "POST",
url: "my-logfetch",
data: { csrfmiddlewaretoken: '{{ csrf_token }}', text: jobName },
success: function callback(response){
alert(response);
}
});
}
URLs.py
from . import views
urlpatterns = [
url('my-ajax-test/', views.updateSUTInfo, name='ajax-test-view'),
url('my-logfetch/', views.updateLogs, name='my-logfetch-view'),
]
Calling Javascript function from HTML onchange event of SELECT.
I am trying to send data from javascript/ajax (selected regions and city information) to flask and then return processed data back to javascript. The 'var data' look like {"region1":"Asia","city1":"Taipei","region2":"S America"} on console.log.
I get error within ajax.
javascript:
$(function() {
$('#button').on('click', function() {
var data = {'region1': $('select[name=slct1]').val(),
'city1': $('select[name=slct2]').val(),
'region2': $('select[name=slct3]').val()};
console.log(data);
$.ajax({
url: '/receive',
type: 'post',
dataType: 'json',
contentType: 'application/json',
crossDomain: true,
data: data,
success: function(data2){
alert('success');},
error: function(){alert('failure');}
});
});
});
Flask: Temp1 and other variables (np array) for City1 are extracted from pandas db.
#app.route('/receive', methods=['POST', 'GET'])
def receive():
if request.method == 'POST':
data = request.form['data']
City1 = data['city1']
Temp1 = some_function(City1) # np array
return jsonify({'Temp1': list(Temp1)})
I think the data received in Flask should be parsed like this:
if request.method == 'POST':
data = request.get_data()
data = json.loads(data)
City1 = data['city1']
My template.html:
...
<button class="btn btn-success" onclick="save_post(event, 'publish')">Publish</button>
...
My javascript.js:
function save_post(event, action) {
event.preventDefault();#new line
var tag_string=document.getElementById('id_tags').value;
if (action=='publish' || action=='draft') {
var url_post='/blog/post/new/'
} else {
var url_post='/blog/post_edit/'
};
$.ajax({type: 'POST',
url: url_post,
data: {
tagstring: tag_string,
action: action
},
success: function (lista) {
//code
}
});
};
My views.py:
#staff_member_required
def post_new(request):
context_dict=[]
if request.method == "POST":
if request.is_ajax():
#code
...
else:
form = PostForm()
return render(request, 'blog/post_edit.html', context_dict)
My url.py:
app_name = 'blog'
urlpatterns = [
...
path('post/new/', views.post_new, name='post_new'),
path('post/<int:pk>/edit/', views.post_edit, name='post_edit'),
...
My views is called by the url (browser), then the button call a javascript function and it call (with ajax) again the same view, this time with request.method = "POST" and this works, but request.is_ajax() gives False.
For call post_edit (probabily) I need the id of the post. Where can I get it?
Should I pass it to save_post() from the template?
Edit: ignore these lines below
Also should I use preventDefault() somewhere?
Thank you
Edit: now I use preventDefault() but it gives this error:
Not Found: /blog/post_new/
[26/Jan/2018 19:07:20] "POST /blog/post_new/ HTTP/1.1" 404 10871
and ajax dosn't call the view. Edit: I solved this problem, but I continue tomorrow :)
Your Ajax code some problems and view is correct
I have attached my Code attached Image and code
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'myajaxview', // the url where we want to POST
data :{
'csrfmiddlewaretoken': '{{csrf_token}}',
'text': text,
'search': search,
'email': email,
'url': url,
'telephone': telephone,
'password': password,
'number': number,
},
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
I'm trying to display the error messages that I provided on my forms, but it only display the id name instead of error message.
Here's my code
Form.py
class SecurityCode(forms.Form):
sCode = forms.RegexField(regex=r'^\w+$', widget=forms.TextInput(attrs=dict(id="scode", name="scode", required=True, size=25, placeholder=" Security Code")), error_messages={ 'invalid': "This value must contain only letters, numbers and underscores." })
Views.py
def security(request):
if request.method == 'POST':
securityField = SecurityCode(request.POST)
if taxpayerField.is_valid():
return HttpResponse("success")
else:
return HttpResponse(taxpayerField.errors)
Note: I'm trying to get the error message in this views not on my html because I'm trying to alert that on my javascript. Also this is just my sample code not the original one.
You can try this:
views.py:
from django.http import JsonResponse
def security(request):
form = SecurityCode(request.POST)
if not form.is_valid():
return JsonResponse({
'success': False,
'err_code': 'invalid_form',
'err_msg': form.errors,
})
#[...] Actions if form is valid ...
return render(request, 'template.html')
javascript code:
def submit_form(){
var data = {
field1: '...',
field2: '...',
csrfmiddlewaretoken: 'csrftoken',
};
$.ajax({
url: '/submit/form/',
method: 'POST',
data: data,
dataType: 'json',
success: function (data){
if (data.success){
// Actions ...
}
else if (data.err_code === 'invalid_form'){
for(var key in data.err_msg){
console.log('[error] for ' + key + ': ' + data.err_msg[key][0]);
}
}
},
});
}
I use console.log to illustrate the recovery of the error message for each field.
After having spent hours, I need help to match the javascript code to the django codes.
I am using the "minimal-django-file-upload-example" version django 1.8 from the git https://github.com/axelpale/minimal-django-file-upload-example.
In standalone, it works very well.
Now i try to upload file from javascript and i do not succeed to make it works.
Javascript Code
function UploadBlob(zip)
{
var ZipFileBlob = zip.generate({type:"blob"});
var fd = new FormData();
fd.append('data', ZipFileBlob);
fd.append('fname', 'ZipOfImage.zip');
fd.append('enctype','multipart/form-
$.ajaxSetup({
type: 'POST',
url: 'http://127.0.0.1:8000/myapp/list/',
enctype: "multipart/form-data",
headers: { "X-CSRFToken": getCookie("csrftoken") }
});
$.ajax({
data: fd,
processData: false,
contentType: false
}).done(function(data) {console.log(data);});
}
Django code
in forms.py
class DocumentForm(forms.
docfile = forms.FileField(label='Select a file')
in views.py
def list(request):
# Handle file upload
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile = request.FILES['docfile'])
newdoc.save()
# Redirect to the document list after POST
return HttpResponseRedirect(reverse('myproject.myapp.views.list'))
else:
print "invalid form"
else:
form = DocumentForm() # A empty, unbound form
# Load documents for the list page
documents = Document.objects.all()
# Render list page with the documents and the form
return render_to_response(
'list.html',
{'documents': documents, 'form': form},
context_instance=RequestContext(request)
)
The code run up to the request.method == 'POST'. After, i do not know if i should add field to the ajax requests (and which ones) or if there is a more suitable form in django or do something else.
Please help!