Edit: I'm using Django dev version so I do have access to JsonResponse (as seen below).
I'm messing around with Django and trying to make it work with AngularJS. Currently I'm attempting to query 4 rows from a database at a time and send the results as a JSON object to an Angular script. I just keep running into issues though - it won't work.
Here's where my code is at right now after a bunch of searching on StackOverflow to try and help myself out:
# views.py
class AJAXListMixin(object):
def dispatch(self, request, *args, **kwargs):
if not request.is_ajax():
raise Http404("Improper access.")
return super(object, self).dispatch(request, *args, **kwargs)
def get_queryset(self):
return Project.objects.filter(added__lte=timezone.now())
def get(self, request, *args, **kwargs):
return JsonResponse(self.get_queryset(), safe=False)
class PageApi(AJAXListMixin, generic.ListView):
paginate_by = 4 # 4 results per page
ordering = '-added' # Most recent to oldest
----------------------
# models.py
class Project(models.Model):
title = models.CharField(max_length=100)
desc = models.TextField()
link = models.URLField(default=None, blank=True, null=True)
slug = models.SlugField(null=True)
added = models.DateField(_("Date Added"), default=datetime.today)
def __str__(self):
return self.title
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(Project, self).save(*args, **kwargs)
def as_dict(self):
return {
"title": self.title,
"description": self.desc,
"link": self.link,
"slug": self.slug,
"date": self.added,
"previews": {
preview.as_dict() for preview in self.preview_set.all()
}
}
class Preview(models.Model):
project = models.ForeignKey(Project)
file = models.FileField(upload_to='project/preview/')
def __str__(self):
return "{project} Preview {id}".format(
project=self.project.title, id=self.id
)
def as_dict(self):
return {
"url": self.file.url
}
And here is the angular code I'm starting off with:
projects = angular.module("Projects", []);
projects.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest";
}]);
projects.controller("ProjectList", ['$scope', '$http', function ($scope, $http) {
$scope.projects = {};
$scope.page = 1;
$http.get('api/page/' + $scope.page)
.success(function (response) {
console.log(response)
})
.error(function (status) {
alert("Error. Check network logs.");
});
}]);
I want to store the response in the projects $scope variable so that I can do things with the data in my angular template.
I'd recommend taking a look the following post:
http://blog.kevinastone.com/getting-started-with-django-rest-framework-and-angularjs.html or this one https://thinkster.io/django-angularjs-tutorial/
It walks through setting up a REST API in Django to serialize your models, and specifying which fields are to serialized and returning JSON data using the Django Rest Framework.
Note that the example uses CoffeeScript and compiles it into JavaScript using GruntJS.
Instead your Angular controller should look more like the following (assuming you have a URL '/api/projects/', that routes to an API view that returns a JSON object containing multiple projects):
$scope.projects = [];
$http.get('/api/projects/').success(function(data) {
$scope.projects = data;
console.log($scope.projects);
});
Not sure how this would work with the additional pagination, but you can read more about it on the Django Rest Framework docs:
http://www.django-rest-framework.org/api-guide/pagination/
Hope this helps!
Related
I am a beginner in Django. I want to send an email on button click. Button is delete button. when press on delete button, i want to send an email to receiver#gmail.com.
As per the below code, email send when the page loaded. And also there was an internal server error. could you please help me to change the as email send on button click.
views.py
class delete_profile(View):
print("nothing")
def post(self, request, *args, **kwargs):
print("nothing")
template = loader.get_template("frontend/subscription-start.html")
email_content = "deletion confirmation"
send_mail(
'No Dowry Marriage - Subscription',
email_content,
'sender#gmail.com',
['reciever#gmail.com'],
html_message=email_content,
fail_silently=False
)
urls.py
path('delete_profile', csrf_exempt(delete_profile.as_view()), name='delete_profile')
user_profile.html
<script>
function delete_profile1() {
var csrftoken = getCookie('csrftoken');
console.log("rhgrjhrj")
$.ajax({
type: 'POST',
url: '{% url "delete_profile" %}',
data: {
csrfmiddlewaretoken: csrftoken
},
success: function () {
toastr.info('Preference Updated Successfully')
}
});
}
</script>
THANKS IN ADVANCE!!!!
first you import JsonResponse and render in your views.py:
from django.http import JsonResponse
from django.shortcuts import render
After change your Class:
class delete_profile(View):
def get(self, request, *args, **kwargs):
# handle the get request
return render(request, 'frontend/subscription-start.html')
def post(self, request, *args, **kwargs):
email_content = "deletion confirmation"
send_mail(
'No Dowry Marriage - Subscription',
email_content,
'sender#gmail.com',
['reciever#gmail.com'],
html_message=email_content,
fail_silently=False
)
return JsonResponse({'some_text': some_text})
# or
# return render(request, 'some_location/some_html_file')
Maybe change your ajax POST request headers:
headers: {
'X-CSRFToken': csrftoken
}
I am trying send a file object of type BytesIO from flask API to angular frontend.
I am using json.dumps(). File object shouldn't be stored on file system. I am using memory for storing file object. Using io.BytesIO().
return json.dumps({'UserId': username, 'file': file_object}), 201
Typerror: <_io.BytesIO object> is not json searializable
You can use send_file with a file like object:
import io
from flask import send_file
#app.route("/send_file")
def send_file():
file = io.BytesIO()
file.write(b"Hello, World!")
file.seek(0)
return send_file(file, attachment_filename=f"example.txt", as_attachment=True)
And then I expect you'll do something with it in Javascript:
fetch('https://example.com/send_file')
.then(res => res.blob())
.then(blob => {
// Do something
});
http://blog.luisrei.com/articles/flaskrest.html
Please check this link and refer "RESPONSES" subtitle.
from flask import Response
#app.route('/hello', methods = ['GET'])
def api_hello():
data = {
'hello' : 'world',
'number' : 3
}
js = json.dumps(data)
resp = Response(js, status=200, mimetype='application/json')
resp.headers['Link'] = 'http://luisrei.com'
return resp
I want to incorporate a drag-and-drop to upload files using Django and HTML. I am able to upload the file and save it to the model "Document". After that, I want to be redirected to 'user:datapreparation', which will display the dataframe in a new page. However, I am not redirected and I stay on the same page ("user:userform").
Do you perhaps know why I am not redirected to datapreparation'?
Hereby the code.
Thank you for your help!
View:
class FileUploadView(View):
form_class = DocumentForm
template_name = 'user/model_form_upload.html'
def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
def post(self, request):
document_name = str(request.FILES['file'])
if request.FILES['file'].size < 31457280: # max 30 mbs allowed
form = self.form_class(request.POST, request.FILES)
document_type = str(document_name.rsplit(".", 1)[1])
valid_document_types = ["txt", "csv", "xlsx"]
if document_type in valid_document_types:
a = Document.objects.all()[0]
a.file = request.FILES['file']
a.description = document_name
a.save()
return redirect('user:datapreparation')
Models:
class Document(models.Model):
description = models.CharField(max_length=255,blank=True)
file = models.FileField(upload_to='documents/')
URL:
from django.conf.urls import url
from . import views
app_name = 'user'
urlpatterns = [
# upload
url(r'^upload/$', views.FileUploadView.as_view(), name='userform'),
# data preparation - dataframe creation
url(r'^datapreparation/$', views.DataPreparation.as_view(), name='datapreparation'),
]
HTML:
<div id="upload"></div>
<form class="dropzone" action="{% url 'user:datapreparation' %}" method="post" enctype="multipart/form-data" id="dropzone">{% csrf_token %}
<div>
Drop files here
</div>
</form>
<script>
(function() {
var form = document.querySelector('form');
var dropzone = document.getElementById('dropzone');
dropzone.ondrop=function(ev){
ev.preventDefault();
this.className='dropzone';
var data = new FormData(form);
var xhr = new XMLHttpRequest();
var file = ev.dataTransfer.files[0]
console.log(file)
xhr.open('POST', "/user/upload/")
data.append('file', file)
xhr.send(data)
};
dropzone.ondragover = function () {
this.className = "dropzone dragover";
return false;
};
dropzone.ondragleave = function () {
this.className = 'dropzone';
return false;
};
}());
The response from django is being handled by the javascript, so you you could return the URL in the django view (using for example the reverse method) and then window.location.href in the javascript.
You can check how to add a callback to XMLHttpRequest here
I believe you're missing the reverse mechanism on your redirect.
from django.urls import reverse
return redirect(reverse('user:datapreparation'))
In my app that uses Gridster I am changing the widget positions and then saving it as a json variable.I want to store this json variable in django database.
For that I am not understanding how should I define a function in views.py and a class in models.py which can store the json variable
My HTML/JS template is
var URL = "{% url 'my_view_url' %}";
$('.js-seralize-update').on('click', function () {
var s = gridster.serialize();
updated_grid=JSON.stringify(s);
$('#log').val(updated_grid);
function updategridster(){
var data = updated_grid;
$.post(URL, data, function(response){
if(response === 'success'){ alert('Yay!'); }
else{ alert('Error! :('); }
});
}
});
My views.py
def save_grid(request):
if request.method == 'POST':
# Some code to get json variable and store it to model
return HttpResponse('success') # if everything is OK
I want to write some kind of class in models.py corresponding to view.py so that JSON variable can be saved
Edit1
My models.py is
from django.db import models
from django.utils import timezone
from django.utils import simplejson as json
class update_grid(models.Model):
data = JSONField(null=True, blank=True)
I just want to send data from views to this model(If it is correct)
Edit 2
My JS Script is updated as follows
var URL = "{% url 'save-grid' %}";
$('.js-seralize-update').on('click', function () {
var s = gridster.serialize();
updated_grid=JSON.stringify(s);
$('#log').val(updated_grid);
function updategridster(updated_grid){
var data = updated_grid;
$.post(URL, data, function(response){
if(response === 'success'){ alert('Yay!'); }
else{ alert('Error! :('); }
});
}
updategridster(updated_grid);
});
Now I get this error
POST http://localhost:8000/calendar_grid/save-grid net::ERR_CONNECTION_ABORTED jquery.min.js:2
You have the built in JSONField if you use PostgreSQL.
Otherwise there are several implementations like django-jsonfield, for admin i pair this with django-jsoneditor
Then you can save the JSON data in a single field, and in the case of the built in, you can even do queries/filter on specific keys inside the JSON structure.
I am trying to get the models from django but nothing is showing up. The app is deployed on Google App Engine.
This is the errors I see:
AttributeError at /get_companies_json
'str' object has no attribute 'status_code'
Request Method: GET
Request URL: http://127.0.0.1:8000/get_companies_json
Django Version: 1.3
Exception Type: AttributeError
Exception Value:
'str' object has no attribute 'status_code'
Below are my urls, view functions:
URL:
('^get_companies_json$', 'companies.views.all_companies_json')
views function:
def all_companies_json(request):
# json_serializer = serializers.get_serializer("json")();
companies_json = serializers.serialize("json", Company.objects.filter(approved = True));
return companies_json;
jQuery:
$.getJSON("/get_companies_json",
function(data){
$.each(data.items, function(i, item){
console.log(item);
});
}
);
I am following the example on jQuery site: http://api.jquery.com/jQuery.getJSON/
What am I doing wrong?
I think that this function
def all_companies_json(request):
# json_serializer = serializers.get_serializer("json")();
companies_json = serializers.serialize("json", Company.objects.filter(approved = True));
return companies_json;
Needs to be changed to
def all_companies_json(request):
# json_serializer = serializers.get_serializer("json")();
companies_json = serializers.serialize("json", Company.objects.filter(approved = True));
return HttpResponse(companies_json, mimetype="application/json")