request.FILES in Django empty when file transfered through create() in Backbone - javascript

Each todo model can have a file attached FileUpload attribute.
todo model attributes:
title
FileUpload
But when creating a todo model through collection.create(), the attached file is not able to be accessed through request.FILES in django
main.js: (instantiating a todo model and creating it through collection.create )
filePDF = $('input[name="pdfUpload"]')[0].files[0];
var todo = new Todo({title:this.$('#new_todo').val().trim(),FileUpload:filePDF})
this.collection.create(todo);
NOTES: posting here a part of the main.js as I am positively sure, it is the create() part that is creating issues. But if more clarity is needed, do let me know.
views.py
class TaskMixin(object,):
serializer_class = TaskSerializer
permission_classes = (IsOwnerOrReadOnly,)
def get_queryset(self):
if(not self.request.user.is_staff):
return Task.objects.filter(owner=self.request.user)
else:
return Task.objects.all()
class TaskList(TaskMixin, ListCreateAPIView):
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
pass
Question: How should the uploaded file be sent across to django, so that it can be accessed through request.FILES ?

Related

Django why getting this error No user profile found matching the query

I am trying to implement load more button so I am writing this view for load json data but I am not understanding why I am getting this error. No user profile found matching the query Raised by: members.views.UserProfileUpdate
here is my view:
class PostJsonListView(View):
def get(self, *args, **kwargs):
print(kwargs)
upper = kwargs.get('num_posts')
lower = upper - 3
posts = list(Blog.objects.values()[lower:upper])
posts_size = len(Blog.objects.all())
max_size = True if upper >= posts_size else False
return JsonResponse({'data': posts, 'max': max_size}, safe=False)
this is my blog app
urls.py
path('posts-json/<int:num_posts>',PostJsonListView.as_view(),name='json-view')
this is my members app
urls.py
path('<slug:slug>/', UserProfileUpdate.as_view(), name='update-profile'),
if I put any wrong url like this http://127.0.0.1:8000/sassassdsadasdd/ giving me the same error No user profile found matching the query Raised by: members.views.UserProfileUpdate
you are in the UserProfileUpdate view, using the slug for getting the profile object like this:
Profile.objects.get(username=slug)
but!
you should use the get_object_or_404 shortcut functions.
from django.shortcuts import get_object_or_404
get_object_or_404(Profile, username=slug)
refrence

use native postgres query request instead of using rest_framework viewset objects

so here is my problem i am using django rest_framework in backend with reactjs in the frontend and postgres as database and i am tired of trying to understand how works classes and objects in rest viewset i am actually in deadline in my project so i need to speed up i am using postgres since 2 years now and i am new to django rest and reactjs (3 mounth) so i know how to write and get evrything i want by postgres native request so the thing is that i want to a native postgres request to get something from the viewset
for exemple i want to write "SELECT * FROM table" instead of "Table.Objects.all()" BUT i want to use different postgres request depending on the request.query.params
here is some of my code so that u use it for ur reponse:
models.py (part of it)
'''
class Evennement(models.Model):
id = models.BigAutoField(primary_key=True)
date_evennement = models.DateField()
time_evennement = models.TimeField()
class Meta:
managed = False
db_table = 'evennement'
'''
serializer.py
'''
class EvennementSerializer(serializers.ModelSerializer):
class Meta:
model = Evennement
fields = '__all__'
'''
views.py(part of it)
'''
class EvennementViewSet(viewsets.ModelViewSet):
queryset = Evennement.objects.all()
serializer_class = EvennementSerializer
def retrieve(self, request, *args, **kwargs):
if request.query.consultation_evennement: //executing this query if the parameter in the get request is true
//how can i change the queryset variable declared above i use "SELECT * FROM Evennement" instead
self.queryset = //doenst work
queryset = //doesnt work
return super().retrieve(request)
return super().retrieve(request)
'''
thanks in advance for your answer :'(

Using value of an attribute of django object in Javascript function

I have a model named VisitorInfo in models.py which is as follows:
class VisitorInfo(models.Model):
#To maintain clarity i am not showing all the fields.
visitor_id = models.CharField(max_length=120)
pages_visited = models.ManyToManyField(Page,blank=True)
time_zone = models.CharField(max_length=120, null= True, blank=True)
ip = models.CharField(max_length=120, null= True, blank=True)
device_type = models.CharField(max_length=120, null=True)
Following is the view where i am using this model.
class Live_Now(LoginRequiredMixin, TemplateView):
template_name = 'dashboard/live_now.html'
def get_context_data(self, **kwargs):
context = super(Live_Now, self).get_context_data(**kwargs)
search = self.request.GET.get('q')
if search:
if VisitorInfo.objects.filter(Q_filter).filter(active=True).count() >0:
context['list_no'] = VisitorInfo.objects.filter(Q_filter).filter(active=True)
else:
context['list_no'] = "N"
return context
What i need to do as soon as live_now.html page loads and Live_Now view runs, a new tab will open with following url.
url = 54.161.109.227:5000/visitor_id
I know that to open a new tab i have to write down script in live_now.html which is as follows.
<script type='text/javascript>
window.open(url); // Above written url
</script>
But how do i fetch visitor_id of the visitor at runtime. Fetching visitor_id is the task fo python function and opening new tab is the function of javascript. How do i pass value of python variable in javascript program ?
For time being i am fetching visitor_id of first visitor in visitors and i have written the following function to do this.
def myfunc():
visitors= VisitorInfo.objects.all()
for visitor in visitors[:1]:
visitorId = visitor.visitor_id
return str(visitorId)
You're making this much harder than it needs to be. If you need your JS to have a particular value, then pass it there.
def get_context_data(self, **kwargs):
... existing code ...
context['visitor_id'] = Visitor.objects.first().user_id
return context
...
url = "54.161.109.227:5000/{{ visitor_id }}";
window.open(url)
Of course you can just as easily pass the whole Visitor object to the template and do {{ visitor.user_id }}, it's up to you.

Django/AngularJS: How do I access my Python Context Items from my AngularJS Script

Good day SO! I am a beginner thats trying out a Django Project while using AngularJS for my frontend Firebase chat system. Here is a previous question that I asked regarding this project: Firebase/Angular: Messages not showing in HTML, but contain the message objects
I know that it is not wise to use json variables on your html directly while using django/python, but it just so happens that my firebase chat module is using angularJS (and I do not know how to code this chat function in django..), and my angularJS code requires access to my Django's context querysets from View.py.
Is there any way that I can either:
Push json items into my HTML/Template the same way I push context
information into my HTML/Template from Views.py and use it in my
AngularJS Script?
Access my Django/Python's data sets from Context from Views.py?
Here is my AngularJS code for firebase:
var app = angular.module('chatApp', ['firebase']);
app.controller('ChatController', function($scope, $firebaseArray) {
//I want to populate the crisis and sender variables with something from my context
//from Views.py.. Inside planList
var crisis = "Crisis1";
var sender = "Sender1";
//Query
var ref = firebase.database().ref().child(crisis).child('CMO-PMO');
$scope.messages = $firebaseArray(ref);
$scope.send = function() {
$scope.messages.$add({
sender: sender,
message: $scope.messageText,
date: Date.now()
})
}
})
And here is my Views.py Code:
def home(request):
template = loader.get_template('app/home.html')
planList = Plan.objects.filter(plan_crisisID__crisis_status='Ongoing')
context = {
'planList': planList
}
return HttpResponse(template.render(context, request))
Both variables needed in my AngularJS code (crisis and sender) are from the planList context.
Is there any way for me to achieve this? Please give me some assistance.. Thank you so much and I greatly appreciate it :) I will gladly provide any additional information if needed, and will reply promptly too!
I think it's better to use an API for it. You can create an API using DRF very easily. For example:
# Serializer
class SomeSerializer(serializers.ModelSerializer):
class Meta:
model = Plan
fields = ('model_fields',)
# Views:
from rest_framework import generics
Class SomeView(generics.ListView):
queryset = Plan.objects.all()
serializer_class = SomeSerializer
# urls
url(r'^plans$', SomeView.as_view()),
In Angular JS, if you use angular-resource, you can simply get the data by:
res = $resource('/plans')
res.query().$promise.then(function(data) {
console.log(data)}, // You get your data in here
function(error) {
console.log(error)}
)

How do I create property for objects in views.py in order to pass changed object to JS code

I load "endless scroll" feed via AJAX and pagination. Before passing objects to JS code, I need to add property(or is it called attribute ?) to every object, which contains boolean, whether it was liked by current user or not. I thought it might work but something is wrong, because everything is getting undefined in frontend. How do I implement what I want in the right way? It's important to create property for every object, because later it's very practical just to fetch it the loop same as other data.
def loadmore(request,page_number):
answers_to_questions_objects = Question.objects.filter(whom=request.user.profile).filter(answered=True).order_by('-answered_date')
paginator = Paginator(answers_to_questions_objects,10)
current_page = (paginator.page(page_number))
for item in current_page:
if request.user.profile in item.who_liked.all():
item.liked = True
else:
item.liked = False
print(current_page.liked)
answers = serializers.serialize('json', current_page)
data = {
'answers': answers,
}
return Response(data)
serializers.serialize will only include the model fields. It won't include the attribute you set on model objects. Instead make a dict and add liked as a key into it.
import json
def loadmore(request,page_number):
# I added prefetch, so it will avoid making queries inside your loop.
answers_to_questions_objects = Question.objects.filter(whom=request.user.profile).filter(answered=True).order_by('-answered_date').prefetch_related('who_liked')
paginator = Paginator(answers_to_questions_objects,10)
current_page = (paginator.page(page_number))
# I don't know why Question model objects are called answers.
answers = []
for item in current_page:
item_dict = { 'whom': item.whom.name,
'id': item.id,
# Add the other required fields.
}
if request.user.profile in item.who_liked.all():
item_dict['liked'] = True
else:
item_dict['liked'] = False
answers.append(item_dict)
data = {
'answers': json.dumps(answers),
}
return Response(data)
Update:
You should checkout django-rest-framework if you have to implement a lot of views like this. The serializer api and generic views that comes with it makes life a lot easier.
I need to add property(or is it called attribute ?) to every object, which contains boolean, whether it was liked by current user or not.
That fits better as a method on the model itself:
class Question(models.Model):
""" A question on the site. """
# …
def liked_by_user(self, user):
""" Is this question liked by `user`? """
profile_users = {p.user for p in self.who_liked}
liked = (user in profile_users)
return liked
That way, the view has access to Question.liked_by_user(current_user) for any question instance.
You don't show a minimal complete verifiable example of your model definitions here, so I'll guess at a complete example:
# models.py
from django.contrib.auth.models import User
from django.db import models
class UserProfile(models.Model):
""" The profile details for a user. """
user = models.ForeignKey(User)
class Question(models.Model):
""" A question on the site. """
answered_date = models.DateField()
def liked_by_user(self, user):
""" Is this question liked by `user`? """
profile_users = {p.user for p in self.who_liked}
liked = (user in profile_users)
return liked
class Like(models.Model):
""" A flag that a user likes a question. """
question = models.ForeignKey(Question, related_name='who_liked')
user_profile = models.ForeignKey(UserProfile)

Categories

Resources