image file is not uploading in django? - ajax

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!

Related

Django generics view not showing HTML template (using AJAX to access the Django view)

I am trying to access Django view via AJAX and show the data returned by view in HTML page. I am using using Django Rest generics view.
Django view returns response successfully. Then, the page reloads.
But html page has not been shown.
HTML code:
Apply filters
Javascript code:
$("apply-link").click(function(){
filterData(j_data);
});
function filterData(j_data) {
let url = "filter";
const csrftoken = getCookie('csrftoken');
$.ajax({
method: 'POST',
headers: {'X-CSRFToken': csrftoken},
url: url,
data: j_data,
success: function (result) {
console.log(result);
},
error: function (response) {
console.log("error");
}
});
}
views.py
class FilterView(generics.CreateAPIView):
template_name = 'pwa_app/filters.html'
serializer_class = ProductSerializer
def post(self, request):
data = request.data
page = self.paginate_queryset(all_products)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(all_products, many=True)
return Response(serializer.data)
urls.py
path('filter', FilterView.as_view(), name="filter")

display the UpdateView form on the same page as CreateView form in django

I want to display the UpdateView form on the same page as CreateView form so whenever "Edit" button is clicked the UpdateView form is displayed on the same page
<button type="button" class="edit_btn" data-url="{% url 'parts:stock_update_view' stock.id %}">Edit</button>
ajax for edit button:
$.ajax({
url: $(this).data('url'),
data: {
},
dataType: 'json',
success: function (data) {
alert(data.name);
}
});
}
});
class stock_update_view(UpdateView):
model = part_stock
fields = ['part_id','entry_date','supplier','amount','remaining']
success_url = reverse_lazy('parts:part_list')
template_name = 'part_detail.html'
def get_context_data(self, **kwargs):
context = super(stock_update_view, self).get_context_data(**kwargs)
context['update_form'] = context.get('form')
return context
def get(self, request, *args, **kwargs):
username = request.GET.get('username', None)
data = {
}
return JsonResponse(data)
I want to get back the UpdateView form as jsonResponse so that I can render it in my template.after returning context['update_form'] = context.get('form') will I be able to render the pre-filled form in my template if yes then how can I return it?
You can define get_initial() function like this:
def get_initial(self):
initial = {
'part_id' : self.request.user.part_id
'entry_date: self.....
}
return initial
This function will pre-populate the form which you are passing in the context.

Unable to display queryset using ajax and Django

I'm not able to display queryset while using ajax
here is my views.py:
if request.user.is_authenticated():
productid = request.GET.get('productId')
print productid
if request.is_ajax():
try:
queryset= StoreProduct.objects.get_size(productid)
except:
queryset= None
data = {
"queryset" : queryset
}
return JsonResponse(data)
Here is my ajax script:
<script type="text/javascript">
function getStoreView(event, productId) {
event.preventDefault();
var data = {
productId : productId
}
$.ajax({
type: "GET",
url: "{% url 'storeView' user=store.user %}",
data: data,
success: function(data) {
console.log(data.queryset)
},
error: function(response, error) {
alert(error);
}
});
};
</script>
What should I do to solve the problem above?
Thanks in advance
If you look at the error message from Django, you will see it complaining that the queryset is not JSON serializable. For ajax requests, you can see the response using your web browser's development tools when DEBUG=True.
The first thing to do is to use values(), which returns a queryset containing dictionaries for each instance in the queryset. Secondly, you need to coerce the queryset into a list.
queryset = StoreProduct.objects.get_size(productid)
values_list = list(queryset.values())
You cannot send queryset directory as json, because json is just a string. You could use django serializer to apply to your queryset:
from django.core import serializers
serialized_qs = serializers.serialize('json', queryset)
data = {"queryset" : serialized_qs}
return JsonResponse(data)
Also in your javascript you have to do data['queryset'] to access your queryset as json.

display json data in the django template

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).

Json does not work in Django with Ajax

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

Resources