i am trying to save the form values using ajax. i have already done that, now the form data is being saved into db. what i want now is to display that saved data in that django template only without refreshing it. but on form submission json data string(only the result) is being displayed
models.py
from django.db import models
class TestModel(models.Model):
title = models.TextField(max_length=255)
views.py
import json
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils import simplejson
from vijayapp.forms import *
from django.http import *
from vijayapp.models import *
def main(request):
return render_to_response('index.html',
{'form':TestForm()}, RequestContext(request))
def index(request):
if request.method == "POST":
form = TestForm(request.POST)
#message = 'something wrong'
if form.is_valid():
message=request.POST['title'] #model field name
form.save()
dict = {}
dict['value']=message
#return HttpResponse(json.dumps({'message': message}))
return HttpResponse(json.dumps(dict), content_type="application/json")
else:
form = TestForm()
return render_to_response('index.html',
{'form':TestForm()}, RequestContext(request))
index.html
<body>
<h1>Leave a Suggestion Here</h1>
<div class="message"></div>
<div class="hello">
<form action="/forms/" method="POST" id="MY_FORM">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit Feedback" id="button"/>
</form>
<p></p><p></p>
<div id="result">
</div>
</div>
</body>
<script type="text/javascript">
$(document).ready(function() {
$("#button").click(function() {
e.preventDefault();
var input_string1 = $(".textclass").val();
alert(input_string1);
$.ajax({
url :"forms",
type : "POST",
dataType: "json",
data: $(this).serialize(),
success : function(json) {
$('#result').html(json.value);
alert(json['value']);
},
error : function(xhr,errmsg,err) {
alert("wrong entry");
}
});
return false;
});
});
</script>
forms.py
from django.forms import ModelForm
from vijayapp.models import TestModel
from django import forms
class TestForm(ModelForm):
class Meta:
model = TestModel
widgets={
"title":forms.TextInput(attrs={'placeholder':'Name','name':'Name','id':'common_id_for_imputfields','class':'textclass'}),
}
Yes, you are getting json data as a string so what you can do it is parse the json in your jquery code using $.parseJson. now you will get a data-structure(dict,tuple,list) of your data.Now you can display each data from your data-structure(dict,tuple,list).
Related
I am trying to upload the images via ajax and the front-end code seems to be working and I have the image data in the request.FILES. but the images are not being uploaded on the server side.
here is my django view:
#login_required
def update_profile_image(request):
print(request.FILES)
if request.method == 'POST':
p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)
if p_form.is_valid():
p_form.save()
context = {'None': 'none'}
return JsonResponse(context)
else:
return HttpResponse('None')
the form is valid but the image is not uploaded in the MEDIA directory.
my model:
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
def __str__(self):
return f'{ self.user.username } Profile'
and form:
from django.db import models
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Profile
class ProfileUpdateForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['image']
btw this is my AJAX call (which as I said seems to be working).
$(document).on('submit', '#profile_edit_form', function(event){
event.preventDefault();
$.ajax({
url : "/users/update_profile_image/",
type : 'POST',
//enctype : "multipart/form-data", //it is done inside jquery
data : formdata,
cache : false,
contentType : false,
processData : false,
success : function(data) {
console.log('success');
//$('#profile_picture').html(data.)
},
error: function(data) {
console.log('image-fail');
}
});
});
What am I doing wrong in my view function?
thanks!
I'm trying to use Django Ajax to Modify user's avatar, but it doesn't work.There is no any error information, just doesn't work.
Here is my form in template:
<form class="clearfix" id="jsAvatarForm" enctype="multipart/form-data" autocomplete="off" method="post" action="{% url 'users:image_upload' %}" target='frameFile'>
<img id="avatarShow" src="{{ MEDIA_URL }}{{ request.user.image }}"/>
<input type="file" name="image" id="avatarUp" class=""/>
<button type="submit">Modify Avatar</button>
{% csrf_token %}
</form>
Here is my Ajax:
$("#jsAvatarForm").submit(function(){
var image = $("#avatarShow").val()
$.ajax({
cache: false,
type: "POST",
url:"{% url 'users:image_upload' %}",
data:{'user_pk':{{ user.pk }}, 'image':image},
async: true,
beforeSend:function(xhr, settings){
xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
},
success: function(data) {
if(data.status == 'fail'){
if(data.msg == '用户未登录'){
window.location.href="login";
}else{
alert(data.msg)
}
}else if(data.status == 'success'){
window.location.reload();//refresh current page.
}
},
});
return false;
});
Here is views.py:
class UploadImageView(LoginRequiredMixin, View):
def post(self, request):
user_pk = request.POST.get("user_pk", 0)
image = request.FILES.get('image')
user_change = UserProfile()
user_change.id = user_pk
user_change.image = image
user_change.save
return HttpResponse('ok')
Actually I also have a forms.py but I don't know how to use it with ajax:
class UploadImageForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ['image']
Here is my user model, note:I have rewrote my own USER:
class UserProfile(AbstractUser):
image = models.ImageField(upload_to="image/%Y/%m", default="image/default.png", max_length=100,verbose_name='头像')
class Meta:
verbose_name = "用户信息"
verbose_name_plural = verbose_name
def __str__(self):
return self.username
Any friend can help?Thank you so much!
Obviously You can send file such as image to django via js, depending of what you have posted in your question, I am showing you a way that you can proceed, there are lots of other ways to accomplish this fairly.
Feel free to comment, if anything is not working.
$("#jsAvatarForm").submit(function(){
var form = this;
// var image = $("#avatarShow").val() You can not retrieve the image like this
var formData = new FormData($(form)[0]);
// Everything inside the html form is serialized in the formData
// No need to add X-CSRFToken, {% csrf_token %} is inside the form
formData.append("NEW_KEY","NEW_VALUE"); # In case of further values
$.ajax({
url:$(form).attr('action'),
type:$(form).attr('method'),
data:formData,
processData: false,
contentType: false, //Don't set any content type header
success: function(){
// all your stuffs here
$('#avatarShow').attr('src',data.avatar_url)
},
error:function(){
alert("error");
}
});
return false;
});
Django
from django.http import JsonResponse
# codes here
user_change.image = image
user_change.save()
return JsonResponse({'avatar_url':user_change.image.url})
Note: Show the post view that rendering this template.
I am writing a small test app for a bigger project. I would like to use asynchronously FileReader() to read a txt file from client side and pass the textbody to the Django server by using AJAX. When the server succeeds to get the "posted" text, it will return the length of the text. It worked well on the server and I got what I expected. But now I would like to pass the size of the text(length) back to the client and display it somewhere on the web page asynchronously. But failed... Here is my code:
HTML
<script type="text/javascript">
var render_text = function(csvFile, onLoadCallback){
var reader = new FileReader();
reader.onload = onLoadCallback;
reader.readAsText(csvFile);
}
$(document).ready(function(){
$("#id_csvFileInput").on("change", function(e){
render_text(this.files[0], function(e){
var text = e.target.result;
$.ajax({
url: "",
type: 'POST',
async: true,
data: {'text': text},
success: function(data){
$("#id_test").text(data.size);
}
});
});
});
});
</script>
<p>
<input type="file" name="csvFileInput" id="id_csvFileInput" accept=".csv">
</p>
<div>
<p>Waiting for reponse context....</p>
<span id="id_test">?</span>
</div>
View.py
# Home page.
#csrf_exempt
def home(request):
template = 'hbvapp/home.html'
context = {}
if request.method == "POST" and request.is_ajax():
context['test'] = request.POST.get('text')
context['size'] = len(context['test'])
print context['size']
return render(request, template, context)
else:
return render(request, template)
ANY HELP WILL BE DEEPLY APPRECIATED !
Reagards
try it
from django.http import JsonResponse
if request.method == "POST" and request.is_ajax():
context['test'] = request.POST.get('text')
context['size'] = len(context['test'])
print context['size']
return JsonResponse(context)
# ^^^^^
more details jsonresponse
you can send it this way also:
context['test'] = request.POST.get('text')
context['size'] = len(context['test'])
print context['size']
return HttpResponse(json.dumps(context), content_type='application/json')
and in you js you can access it like this:
success: function(data){
$("#id_test").text(data['size']);
}
I want to make an ajax request in a Django framework. However, I don't pass to get data from the client in json. It works when I don't use Json.
If I use dataType:'json' with a {'a': 'value'} in the ajax, I can't get it in the view.py, the result is nothing...
However if I use data:$(this).serializeArray() in the ajax I can get result with request.POST. However, I really need to customize my data and send to my view.py other data than the data from the form. I would like to send a {'a', 'mydata', 'form': myformdata}...
Is there a way to do it?
template:
<form id="ajax2" action="/seghca/test-post/" method="post">{% csrf_token %}
Nom : <input type="text" name="nom" value="" id="nom"/><br/>
prenom : <input type="text" name="prenom" value=""/><br/>
<input type="submit" value="Envoyer"/>
</form>
<div id="result"></div>
javascript:
$(document).ready(function(){
// POST AJAX
$("#ajax2").submit( function() {
var urlSubmit = $(this).attr('action');
var data = $(this).serializeArray();
data.push({
key: "keyName",
value: "the value"
});
$.ajax({
type: "POST",
url: urlSubmit,
dataType: "json",
data : data,//$(this).serializeArray(),
success: function(response){
var json_response = JSON.parse(response);
// now get the variables from the json_response
$('#result').html(json_response.html);
}
});
return false;
});
});
view.py (the ajax launch the test_post view, home2 is the view of the formular):
from datetime import datetime
from django.http import HttpResponse, Http404
from django.shortcuts import redirect, render
from seghca.models import Article
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.template import RequestContext
from django.views.decorators.csrf import csrf_exempt
import json
def home2(request):
return render_to_response('seghca/form.html', context_instance=RequestContext(request))
#csrf_exempt
def test_post(request):
data = {'html': request.POST['key']}
return HttpResponse(json.dumps(data), mimetype="application/json")
When you are using ajax view you should return the data back from your view in the json form:
data = {'html': request.POST['input']}
return HttpResponse(json.dumps(data), mimetype="application/json")
Second it is necessary to parse the response first on client side:
success: function(response){
var json_response = JSON.parse(response);
// now get the variables from the json_response
$('#result').html(json_response.html);
}
Third if you need to pass the form data along with some more info you can do:
var data = $(this).serializeArray();
data.push({
key: "keyName",
value: "the value"
});
Fourth you are missing csrf token.
change data: data, to data: {'data': JSON.stringify(data)},
and you'll be able to access the serialized version of your data via POST['data'] in django. Keep in mind that if you want to use this in django you have to deserialize it, for instance json.loads(POST['data'])
I have your same needs. My solution was:
The AJAX request:
var posturl = $('#'+formid).prop('action');
$.ajax({
async:false,
type: "POST",
dataType: "json",
contentType: "application/x-www-form-urlencoded",
url : posturl,
data : $('#'+formid).serialize() + '&mode=ajax', //&mode=ajax is my custom data
success:function(response){
console.log(response);
alert(response.message);
},
timeout:10000
});
In the views.py:
data = {'error': '0', 'message': 'all was ok'}
return HttpResponse(json.dumps(data), mimetype="application/json")
The above should work for you. My test was with Django 1.6 and Python 2.7.5
I am not able to get the input text field data with id city_name from the form via jQuery-Ajax method.
The error that I keeps getting is "NetworkError: 403 FORBIDDEN - http://127.0.0.1:8000/dashboard".
I know how to get the data using hidden field type, but that option cannot be used here and moreover, getting data from hidden field is now an outdated method. So, how can I get data using Django-AjaxJquery method.
HTML
<form type = "POST">
{% csrf_token %}
<input type="text" placeholder = "Enter City Name" id = "city_name">
<input type="button" value = "On" id="on">
<input type="button" value = "Off" id="off">
</form>
JS File
$(function(){
$("#on").click(function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "dashboard",
data : {
'city_name' : $("#city_name").val(),
},
});
});
});
View.py
#login_required
def dashboard(request):
ctx = {}
if request.is_ajax():
city_name = request.POST['city_name']
print city_name
return render_to_response('dashboard/dashboard.html',ctx, context_instance = RequestContext(request))
urls.py
urlpatterns = patterns('',
url(r'^dashboard$','apps.dashboard.views.dashboard', name = 'llumpps_dashboard'),
)
It is missing the CSRF token in the request.
You can either use #csrf_exempt decorator for your view like:
#login_required
#csrf_exempt
def dashboard(request):
...
Or send the token along with the request:
$.ajax({
type: "POST",
url: "dashboard",
data : {
'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val();
'city_name' : $("#city_name").val(),
},
complete: function () {
// do whatever here
}
});
Read more about CSRF and AJAX in Django here: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax
Hope it helps.