Using value of an attribute of django object in Javascript function - javascript

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.

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 :'(

How can I transfer context variable into a html bound javascript code in Django?

I have write down a view:
def Country_names(request):
c_list = []
for c_name in c_names:
c_list.append(c_name)
return render(request, 'DATAPLO/Country_list.html', {'c_list':c_list})
This view transfers a list/array to template further in my html template it try to convert this python variable into javascript array variable.
<script>
//variable defined to store "c_list" array
var c_names = {{c_list}}
//try to access array items like this
c_names[0]
</script>
But his method is not working in my case how can I do this, I have explore dfew similar threads on the web but nothing is working in my case.
thanks
Updated answer which includes a Country model
models.py:
class Country(models.Model)
name = models.CharField(max_length=100)
So if your country model looks like this, we need to make that into a list of strings to be converted to json.
import json
def Country_names(request):
c_list = Country.objects.all().values_list('name', flat=True)
return render(request, 'DATAPLO/Country_list.html', {'c_list':json.dumps(c_list)})
And then output in HTML. Remember to mark it safe, so it doesn't get escaped
<script>
//variable defined to store "c_list" array
var c_names = {{c_list|safe}}
</script>
You can use values_list()
to get the list of country names.
import json
def getCountryNames(request):
country_names = list(Country.objects.values_list('name', flat=True))
return render(request, 'DATAPLO/Country_list.html', {'country_names':json.dumps(country_names)})
rest is same as #Sune's answer

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)

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

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 ?

Categories

Resources