Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
channels.layers.get_channel_layer() is returning None type object | Django Channels 3.0.2
I want to send messages to the channel but for that, I am not able to find the reason why the below code is not working in the shell of the project(justchat): >>> from channels.layers import get_channel_layer >>> print(get_channel_layer()) > None I have followed the complete "channels 3" documentation hence all the configurations are the same as there in the documentation. # justchat.settings ASGI_APPLICATION = 'justchat.asgi.application' CHANNELS_LAYERS = { 'default':{ 'BACKEND':'channels_redis.core.RedisChannelLayer', 'CONFIG':{ 'hosts':[('127.0.0.1',6379)], }, }, } # consumers.py import json from channels.generic.websocket import WebsocketConsumer class ChatConsumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): pass def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] self.send(text_data=json.dumps({ 'message': message })) # justchat.asgi import os from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application from channels.auth import AuthMiddlewareStack import chat.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'justchat.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket":AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns ) ) }) -
How to pass context result as argurment for another function in django?
I have my django app which searches youtube and return result as a dictionary which i render them in template, one of the returned value is link , now I have a download button they way i wish it to function is whenever you click a button it should take the url for the clicked result and pass it to another download function as an argument. How do I accomplish that ? Here is my view.py def index(request): if request.method == 'POST': query = request.POST['video_name'] n = 12 search = SearchVideos(str(query), offset = 1, mode = "json", max_results = n) ytresults = search.result() result_dict = json.loads(ytresults) context = { "result" : result_dict, } template_name = "youloader/results.html" return render(request, template_name, context) else: query = "no copyright sound" n = 12 search = SearchVideos(str(query), offset = 1, mode = "json", max_results = n) index_results = search.result() result_dict = json.loads(index_results) context = { "result" : result_dict } template_name = "youloader/index.html" return render(request, template_name, context) def downloading_video(request): try: with youtube_dl.YoutubeDL(video_opts) as ydl: ydl.download(link) except: pass here are my template.html <div class="my-4" > <div style="padding-top: 20px"> <div class="row" > {% for result in result.search_result %} <div class="col-12 col-sm-6 col-md-4 col-lg-4"> <div class="card shadow-sm border-0 my-2"> … -
Nginx and Uwsgi not working working on Google cloud Platform(Django, Debian-10 vm instance)
I am trying to deploy my django project on google cloud vm instance(debian 10). But when I start nginx and access External ip of instance it shown nginx but when I run uwsgi then it shows 502 bad gateway. I even don't know if my sockets working or not. here is my config files. Nginx config for my project. # the upstream component nginx needs to connect to upstream DemoProject { server unix:///tmp/DemoProject.sock; } server { listen 80; server_name my_vm_instance_external_ip; return 301 https://my_vm_instance_external_ip$request_uri; } server { listen 443 ssl; ssl_certificate /home/User/Production/DemoProject/ssl/DemoProject.crt; ssl_certificate_key /home/User/Production/DemoProject/ssl/DemoProjectkey; server_name my_vm_instance_external_ip; access_log off; error_log /home/User/Production/DemoProject/logs/nginx_error.log; location / { include /etc/nginx/uwsgi_params; uwsgi_pass DemoProject; } location /static/ { alias /home/User/Production/DemoProject/static/; } } Uwsgi config for my uwsgi [uwsgi] # variables projectname = DemoProject base = /home/User/Production/DemoProject # configuration master = true virtualenv = /home/User/Production/djangorest pythonpath = /usr/lib/python3.7 chdir = /home/User/Production/DemoProject env = DJANGO_SETTINGS_MODULE=DemoProject.settings.pro module = DemoProject.wsgi:application socket = /tmp/DemoProject.sock chmod-socket = 666 And allowed host setting in django settings ALLOWED_HOSTS = ['my_vm_instance_ip.com','www.my_vm_instance_ip'] And also I did add this lines on /etc/nginx/nginx.conf include /home/User/Production/DemoProject/config/nginx.conf -
index 33 is out of bounds for axis 1 with size 33
I am getting this error at this line my_predictions = prediction_matrix[:,current_user_id-1]+Ymean.flatten() This is the code. Please tell me how do I fix it? def recommend(request): if not request.user.is_authenticated: return redirect("login") if not request.user.is_active: raise Http404 df=pd.DataFrame(list(Myrating.objects.all().values())) nu=df.user_id.unique().shape[0] current_user_id= request.user.id # if new user not rated any movie if current_user_id>nu: movie=Movie.objects.get(id=15) q=Myrating(user=request.user,movie=movie,rating=0) q.save() print("Current user id: ",current_user_id) prediction_matrix,Ymean = Myrecommend() my_predictions = prediction_matrix[:,current_user_id-1]+Ymean.flatten() pred_idxs_sorted = np.argsort(my_predictions) pred_idxs_sorted[:] = pred_idxs_sorted[::-1] pred_idxs_sorted=pred_idxs_sorted+1 print(pred_idxs_sorted) preserved = Case(*[When(pk=pk, then=pos) for pos, pk in enumerate(pred_idxs_sorted)]) movie_list=list(Movie.objects.filter(id__in = pred_idxs_sorted,).order_by(preserved)[:10]) return render(request,'web/recommend.html',{'movie_list':movie_list}) -
How to disable autoescape when using django template from_string() and render()?
I am sending an email using django-post_office, which renders the subject line using django templates: subject = engine.from_string(self.template.html_content).render(self.context) Django templates automatically sets autoescape=True for security, which means if you have an HTML character such as Here's an email it will produce a string with the character escaped: Here&#x27;s an email. How can I disable autoescape when using from_string and render in this way to display the email subject appropriately? An alternative example: from django.template import engines template = engines['django'].from_string("My name is {{ my_name }}.") context = {"my_name": "<FooBar's>"} print(template.render(context)) Results in: My name is &lt;FooBar&#x27;s&gt;. -
TemplateDoesNotExist at /wiki/CSS/edit_entry error in djano
I have tried other answers in StackOverflow, but didn't find a solution. I have a function that edits the page content: def edit_entry(request, title): content = util.get_entry(title) if request.method == 'POST': form = AddForm(request.POST) if form.is_valid(): title = form.cleaned_data["title"] util.save_entry(title, content) return redirect('edit_entry', title) return render(request, "encyclopedia/edit_entry", { "title": title, "content": content }) My urls.py looks like: from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:title>", views.entry, name="entry"), path("search", views.search, name="search"), path("add_entry", views.add_entry, name="add_entry"), path("wiki/<str:title>/edit_entry", views.edit_entry, name="edit_entry") ] Here is my edit_html template: {% extends "encyclopedia/layout.html" %} {% block title %} Edit page {% endblock %} {% block body %} <form action="{% url 'edit_entry' title %}" method="POST"> {% csrf_token %} {{ title }} {{ content }} <input type="submit" value="Save Editing"> </form> {% endblock %} As you see, the template exists here: But it says TemplateDoesNotExist at /wiki/CSS/edit_entry The template belongs to my application, so, I guess, no need to add it to DIRS = [], which is located in settings.py. And other routes except this one are working fine. -
'ForwardManyToOneDescriptor' object has no attribute 'id' - Error
I am having model: class TextBook(models.Model): code = models.CharField(max_length=200, unique=True) type = models.CharField(max_length=200) name = models.CharField(max_length=200) open_qty = models.DecimalField( max_digits = 4, decimal_places = 0,default = 0) recived_qty =models.DecimalField( max_digits = 4, decimal_places = 0,default = 0) return_qty=models.DecimalField( max_digits = 4, decimal_places = 0,default = 0) issue_qty=models.DecimalField( max_digits = 4, decimal_places = 0,default = 0) bal_qty = models.DecimalField( max_digits = 4, decimal_places = 0,default = 0) avgcost =models.DecimalField( max_digits = 5, decimal_places = 2,default = 0.00) price =models.DecimalField( max_digits = 5, decimal_places =2,default = 0.00) class_name = models.ManyToManyField(SchClass, help_text='Select a class for this book') term = models.ManyToManyField(SchTerms, help_text='Select Terms') class TransBody(models.Model): trans_header = models.ForeignKey(TransHeader,on_delete=models.CASCADE,null=True) book = models.ForeignKey(TextBook,on_delete=models.CASCADE) quantity = models.IntegerField(default=0) price = models.FloatField(default=0) def get_absolute_url(self): """Returns the url to access a detail record for this book.""" return reverse('select_stock_report', args=[str(self.id)]) my view: def listSelectStkTrans(request,id): # (note:return(HttpResponse(id) gives correct book id) allstktrans =TransBody.objects.filter(id=TransBody.book.id) context = {'allstktrans': allstktrans} return render(request, 'wstore/list_stk_trans.html', context) my url: path('listselectstktrans/<int:id>/', views.listSelectStkTrans, name='select_stock_report'), my template has link: {{ book.code }} I am getting 'ForwardManyToOneDescriptor' object has no attribute 'id' - Error. -
Python: How to assign Python function to HTML button using Django
Python 3.8.5 Django 3.1.2 I created a Django Project. I have an HTML page created with a button. I need to assign the following urlpattern to that HTML button... path('', views.output, name='output'), That URLpattern is linked to a function called 'output' which runs successfully on it's own. I'm using the following HTML code to assign that function to my HTML button... <button onclick="Location.href='{% url 'output' %}'"> Enter </button> This does not work. I cannot get this button to run my function. Does anyone know how to assign this function successfully? Here is my code in my urls.py file... from django.contrib import admin from django.urls import path, include from myapp import views urlpatterns = [ path('app/', include('myapp.urls')), path('admin/', admin.site.urls), path('', views.output, name='output'), ] -
i want my balance keep updates when a purchase has been made
Hello i want create a virtual payment system.All the functions works properply but whenevr i purchase something my balance is not updating. Here is my views.py : def post(self, request, *args, **kwargs): ids = list(request.session.get('cart').keys()) cart_products = Product.get_products_id(ids) product_prices = list(map(self.map_func, cart_products)) total_due = sum(product_prices) balance = request.session['customer']['coin'] if balance >= total_due: balance = balance - total_due Customer.objects.filter(id = request.session['customer']['id']).update(coin=balance) request.session['customer']['coin'] = balance return HttpResponse(balance) return HttpResponse("Failed") Here is my index: {% extends 'Home/header.html' %} {% load cart %} {% block content %} {{user_orders.product.name}} {{user_orders.product.price}} {{total_due}} <h5>{{request.session.customer.coin}}</h5> <form action="" method="POST"> {% csrf_token %} <input type="submit" name="payment_coin"> </form> {% endblock %} What i actually i want is when a purchased has been made account balance will be automaticly update. -
Rest Framework serializer raises "NotImplementedError: `create()` must be implemented." error
So, I'm following a React and Django Tech with Tim tutorial, but it's raising an error saying NotImplementedError: 'create()' must be implemented. Models.py from django.db import models import string import random def generate_unique_code(): length = 6 while True: code = ''.join(random.choices(string.ascii_uppercase, k=length)) if Room.objects.filter(code=code).count() == 0: break return code class Room(models.Model): code = models.CharField(max_length=8, default="", unique=True) code = models.CharField(max_length=50, unique=True) guest_can_pause = models.BooleanField(null=False, default=False) votes_to_skip = models.IntegerField(null=False, default=1) created_at = models.DateTimeField(auto_now_add=True) Serializers.py from rest_framework import serializers from .models import Room class RoomSerializer(serializers.Serializer): class Meta: model = Room fields = ('id', 'code', 'host', 'guest_can_pause', 'votes_to_skip','created_at')``` Views.py from django.shortcuts import render from rest_framework import generics from .models import Room from .serializers import RoomSerializer class RoomView(generics.CreateAPIView): queryset = Room.objects.all() serializer_class = RoomSerializer How can I make this code work? I tried changing class RoomSerializer(serializers.Serializer): to class RoomSerializer(serializers.ModelSerializer): but that just raised another error: Field name 'host' is not valid for model 'Room'. Any help is appreciated :) -
Django Serializer for 3 models, with chained foreignKeys
Let's use these 3 simple models for example. A city can have multiple shops, and a shop can have multiple products models.py class City(models.Model): name=models.CharField(max_length=300) class Shop(models.Model): name = models.CharField(max_length=300) city = models.ForeignKey(City, related_name='related_city', on_delete=models.CASCADE) class Product(models.Model): name=models.CharField(max_length=300) shop=models.ForeignKey(Shop, related_name='related_shop', on_delete=models.CASCADE) serializers.py class CitySerializer(serializers.ModelSerializer): class Meta: model = City fields=['id','name'] class ShopSerializer(serializers.ModelSerializer): related_shop = CitySerializer(many=True, read_only=True) class Meta: model = Shop fields=['id','name','related_city'] class ProductSerializer(serializers.ModelSerializer): related_shop = ShopSerializer(many=True, read_only=True) class Meta: model = Product fields=['id','name','related_shop'] ProductSerializer will give me all products, and will fetch the foreignKey shops, and I will also get the names of the shops where this product is found. ShopSerializer, in a similar way, will give me all shops names, and all the cities where this shop can be found. But how can I make a serializer, that will retrieve from all 3 tables at once? The fields I want are: fields=['product_name','shop_name', 'city_name'] That list I will get will have repetitions, and can be considered 1NF or 2NF, opposed to the model design I have as database 3NF. I was actually thinking of denormalizing my database, so I can easily achieve this. My second question is, is it better to denormalize it to 1NF, and have repetitions, so … -
I actually doesn't understand why {%if%} {%else%} doesn't work there. I just need to render this if author and username are equal
Actually, I am new in Django so I don't understand why if else statement doesn't work here. Is there anything super wrong with this code? {%extends 'main/base.html'%} {%block title%} {{ title }} {%endblock%} {%block content%} <div class="container-fluid"> <h2>{{user.first_name}}</h2> <p>{{user.second_name}}</p> <div class="col"> {%for recel in receipts%} {%if recel.author is user.username%} <h2>Receipt: {{recel.title}}</h2> <h4>Doctor: {{recel.author}}</h4> {%else%} <span></span> {%endif%} {%endfor%} </div> </div> {%endblock%} -
My Django Password encryption is not working
I have a User table that has some attributes where the Password is being stored as a String. I am trying to store it as an encrypted string using bcrypt, but for some reason it is not changing and the password continues to be the one before encryption. I have this in my settings.py: enter image description here And the method to add my User to the table is in views.py as this: enter image description here What am I doing wrong and how can I fix it? -
Django consuming Printfull API
I'm working on a project of one shop that consuming a Printful API, and I'm struggling to create a logic to pass the "Product" class on my model with the products variations. Following the scripts to get clean: The secret key is about one test store on printful, feel free to use. Printful Docs printful.py import requests import base64 url = 'https://api.printful.com/sync/products' s_key = 'xk7ov0my-t9vm-70z6:y491-2uyygexkkq6r' key = base64.b64encode(bytes(s_key, 'utf-8')) keyDecoded = key.decode('ascii') header = {'Authorization': 'Basic ' + keyDecoded} r = requests.get(url, headers=header) pack_json = r.json() class ProductList: id = [n for i in pack_json["result"] for k, n in i.items() if k == "id"] external_id = ([n for i in pack_json["result"] for k, n in i.items() if k == "external_id"]) name = ([n for i in pack_json["result"] for k, n in i.items() if k == "name"]) thumbnail_url = ([n for i in pack_json["result"] for k, n in i.items() if k == "thumbnail_url"]) str_id = [str(i) for i in id] id_name = dict(zip(str_id, name)) id_name_list = list(id_name.items()) models.py from django.db import models from django.db.models.deletion import CASCADE from core import printful import requests class SyncProducts(models.Model): ID_NAME = printful.ProductList.id_name_list title = models.CharField(max_length=200) name_id = models.CharField(max_length=200, choices=ID_NAME) def product_url(self): return f'https://api.printful.com/store/products/{self.name_id}' def __str__(self): d … -
For loops in a view
I am currently working on a rna to protein translator. To do that, I've created a class that does two things. Firstly, you input a dna chain and it gets translated into rna (this part works perfectly) Secondly, you get the rna chain translated into a protein (this part doesn't work). Here's the code for the class: class TranslatorView(View): template_name = 'main/translated.html' rna_mapper = { "a": "u", "t": "a", "c": "g", "g": "c" } amino_mapper={ "aat": "Asparagine", "aac": "Asparagine", "aaa": "Lysine", "aag": "Lysine", "act": "Threonine", "acc": "Threonine", "aca": "Threonine", "acg": "Threonine", "agt": "Serine", "agc": "Serine", "aga": "Arginine", "agg": "Arginine", "att": "Isoleucine", "atc": "Isoleucine", "ata": "Isoleucine", "atg": "Methionine", "cat": "Histidine", "cac": "Histidine", "caa": "Glutamine", "cag": "Glutamine", "cct": "Proline", "ccc": "Proline", "cca": "Proline", "ccg": "Proline", "cgt": "Arginine", "cgc": "Arginine", "cga": "Arginine", "cgg": "Arginine", "ctt": "Leucine", "ctc": "Leucine", "cta": "Leucine", "ctg": "Leucine", "gat": "Aspartic", "gac": "Aspartic", "gaa": "Glutamic", "gag": "Glutamic", "gct": "Alanine", "gcc": "Alanine", "gca": "Alanine", "gcg": "Alanine", "ggt": "Glycine", "ggc": "Glycine", "gga": "Glycine", "ggg": "Glycine", "gtt": "Valine", "gtc": "Valine", "gta": "Valine", "gtg": "Valine", "tat": "Tyrosine", "tac": "Tyrosine", "taa": "Stop", "tag": "Stop", "tct": "Serine", "tcc": "Serine", "tca": "Serine", "tcg": "Serine", "tgt": "Cysteine", "tgc": "Cysteine", "tga": "Stop", "tgg": "Tryptophan", "ttt": "Phenylalanine", "ttc": "Phenylalanine", "tta": … -
Uuser to be logged out after certain time period of inactivity using simple_jwt in django rest framework
I am using django rest framework and trying to implement a security solution. The user has to login again after certain time period of inactivity. Right now I am trying to manipulate django rest framework's settings and I updated the REFRESH_TOKEN_LIFETIME settings.py SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(minutes=30), 'ROTATE_REFRESH_TOKENS': False, 'BLACKLIST_AFTER_ROTATION': True, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), } -
Django phone number field not showing on admin page
I have created below model. from django.db import models from phone_field import PhoneField #pip install django-phone-field # Create your models here. class Profile(models.Model): dateofbirth = models.DateTimeField(null=True, blank=True) website = models.TextField(blank=True) degree = models.TextField(blank=True) phone = PhoneField(blank=True, help_text='Contact phone number') email = models.TextField(blank=True) city = models.TextField(blank=True) freelance = models.BooleanField(default=False) heading = models.TextField(blank=True) caption = models.TextField(blank=True) summary = models.TextField(blank=True) profile_captions_csv = models.TextField(blank=True) name = models.TextField(blank=True) webtitle = models.TextField(blank=True) def __str__(self): return self.heading To support the phone number field, I installed this. pip install django-phone-field The model is migrated but when I try to access it on admin page, I am getting error as template not found. My admin.py from django.contrib import admin from .models import Profile # Register your models here. class ProfileAdmin(admin.ModelAdmin): pass admin.site.register(Profile) Error: Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: C:\Users\UdayKiranReddy\AppData\Local\Programs\Python\Python38\lib\site-packages\django\forms\templates\phone_field\phone_widget.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\UdayKiranReddy\AppData\Local\Programs\Python\Python38\lib\site-packages\django\contrib\admin\templates\phone_field\phone_widget.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\UdayKiranReddy\AppData\Local\Programs\Python\Python38\lib\site-packages\django\contrib\auth\templates\phone_field\phone_widget.html (Source does not exist) django.template.loaders.app_directories.Loader: D:\my resume\UdayResume\homepage\templates\phone_field\phone_widget.html (Source does not exist) -
How to use NASA API with satellite layer in python django?
Currently, I am using the NASA API python package. I am able to retrieve the images by providing longitude and latitude. But I want the map location image in a satellite filter. from django.shortcuts import render from django.shortcuts import render,get_object_or_404,redirect,HttpResponse from nasaapi import Client # Create your views here. def home(request): api = 'CONSIDER MY API KEY HERE' lat = 32.466259415511644 lon = 35.48680851545021 date = '2017-10-10' nasa = Client(api) obj = nasa.earth(lat,lon,date=None) print(obj) return render(request,'home.html',{'context':obj}) -
Django Admin model create new instance instead of update
I've multiple models in my Django project but only this given below model creating another instance on update instead of save. This is happening in Django's Admin panel, not on my custom UI. When I remove my save() method then it works fine but this way I won't be able to create slug. Does anybody know what I'm doing wrong in here class Course(models.Model): title = models.CharField(max_length=200) user = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name='category') slug = models.SlugField(max_length=200, unique=True, primary_key=True, auto_created=False) short_description = models.TextField(blank=False, max_length=60) description = models.TextField(blank=False) outcome = models.CharField(max_length=200) requirements = models.CharField(max_length=200) language = models.CharField(max_length=200) price = models.FloatField(validators=[MinValueValidator(9.99)]) level = models.CharField(max_length=20) application_link = models.URLField(max_length=1000, blank=True, null=True) brochure = models.FileField(upload_to='brochures/', blank=True, null=True) thumbnail = models.ImageField(upload_to='thumbnails/') video_url = models.CharField(max_length=100) is_session_available = models.BooleanField(default=False) session_url = models.CharField(max_length=250, default='') is_published = models.BooleanField(default=True) created_at = models.DateTimeField(default=now) updated_at = models.DateTimeField(default=now) def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Course, self).save(*args, **kwargs) -
My Python class feels very excessive. Is there a shorter way to do this?
I can't seem to find a way to research this. I have this Size class that buckets various size choices into common categories (small, medium, large, etc...). As a result, I ended up with this ridiculously long enumeration of sizes that I've defined. While it works, I was still wondering if there was a smarter way I could have executed this. Are TextChoices really the best way? class Size(models.TextChoices): xs = "xs" x_small = "x-small" xsmall = "xsmall" s00 = "00" s0 = "0" s1 = "1" s2 = "2" w23 = "w23" w24 = "w24" s = "s" sm = "sm" small = "small" s3 = "3" s4 = "4" s5 = "5" s6 = "6" w25 = "w25" w26 = "w26" m = "m" md = "md" med = "med" medium = "medium" s7 = "7" s8 = "8" s9 = "9" s10 = "10" w27 = "w27" w28 = "w28" l = "l" lg = "lg" large = "large" s11 = "11" s12 = "12" s13 = "13" s14 = "14" w29 = "w29" w30 = "w30" s1x = "1X" s1x = "1XL" xl = "xl" x_large = "x-large" xlarge = "xlarge" s15 = "15" s16 = … -
creating a list of known faces for the face recognition library
i'm trying to integrate face recognition library to work with a django project, as the code is shown here based on the documentation: i have to specify the image path and [known face_encodings] and [known_face_names] inside the function or the script # Get a reference to webcam #0 (the default one) video_capture = cv2.VideoCapture(0) # Load a sample picture and learn how to recognize it. image_of_yahya = face_recognition.load_image_file('../media/yahya_stihi.jpg') yahya_face_encoding = face_recognition.face_encodings(image_of_yahya)[0] # Load a second sample picture and learn how to recognize it. obama_image = face_recognition.load_image_file("./images/obama.jpeg") obama_face_encoding = face_recognition.face_encodings(obama_image)[0] image_of_steve = face_recognition.load_image_file('./images/Steve Jobs.jpg') steve_face_encoding = face_recognition.face_encodings(image_of_steve)[0] image_of_ahmed = face_recognition.load_image_file('../media/ahmed_bouchfirat.jpg') ahmed_face_encoding = face_recognition.face_encodings(image_of_ahmed)[0] # Create arrays of known face encodings and their names known_face_encodings = [ obama_face_encoding, steve_face_encoding, yahya_face_encoding, ahmed_face_encoding, ] known_face_names = [ "Barack Obama", "Steve Jobs", "yahya stihi", "ahmed bouchfirat" ] as i started to add more faces i noticed that my code is getting ugly and not efficient and slow now i'm trying to kinda put this section on separate file and load the known faces text only and maybe a for loop so i can create a queryset for every name in that list and that file can be modified while adding a new user so is … -
Sum data in serializer Django
I would like sum data from nested object. My model: class Diet(models.Model): day = models.IntegerField() meals = models.ManyToManyField(Meal) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f'{self.day} - {self.user}' My viewset: class DietViewSet(viewsets.ModelViewSet): queryset = Diet.objects.all() serializer_class = DietSerializer pagination_class = None def get_queryset(self): if self.action == 'list': self.queryset = Diet.objects.filter(user=self.request.user).order_by('day') else: self.queryset = Diet.objects.all().order_by('day') return super(DietViewSet, self).get_queryset() def get_permissions(self): if self.action in ['list', 'retrieve']: self.permission_classes = [permissions.AllowAny] else: self.permission_classes = [IsDietician] return super(DietViewSet, self).get_permissions() My serializers: class MealSerializer(serializers.ModelSerializer): class Meta: model = models.Meal fields = '__all__' class DietSerializer(serializers.ModelSerializer): def to_representation(self, instance): result = super(DietSerializer, self).to_representation(instance) result['meals'] = MealSerializer(instance.meals, many=True).data return result class Meta: model = models.Diet fields = '__all__' Now I would like add total_kcal which will be calculate by data from meals. I tried did it by kcal = serializers.MethodSerializerField() and def get_kcal(self, obj) but I don't know how can I get data from serialized objects in to_representation. Example response: [ { "id":1, "day":1, "user":1, "meals":[ { "id":4, "name":"Rise", "description":"", "kcal":150.0, "protein":3.0, "fat":0.0, "carbs":28.0 }, { "id":5, "name":"Chocoloate", "description":"", "kcal":200.0, "protein":0.0, "fat":0.0, "carbs":100.0 } ] } ] -
My Django model for video upload saying “ValueError”
I am trying to write a small blog where I can be uploading my videos for public download but am getting a server error message when I try click on any video for details. Below is the error that I'm getting when Debug is set to True ValueError at /video/lagos-anthem/ Sample larger than population or is negative Request Method: GET Request URL: https://www.majestylink.com/video/lagos-anthem/ Django Version: 3.1.2 Exception Type: ValueError Exception Value: Sample larger than population or is negative Exception Location: /home/majestyempire/.virtualenvs/majestyenv/lib/python3.7/random.py, line 321, in sample Python Executable: /usr/local/bin/uwsgi Python Version: 3.7.5 Python Path: ['/var/www', '.', '', '/var/www', '/home/majestyempire/.virtualenvs/majestyenv/lib/python37.zip', '/home/majestyempire/.virtualenvs/majestyenv/lib/python3.7', '/home/majestyempire/.virtualenvs/majestyenv/lib/python3.7/lib-dynload', '/usr/lib/python3.7', '/home/majestyempire/.virtualenvs/majestyenv/lib/python3.7/site-packages', '/home/majestyempire/musicblog/myblog'] Server time: Sat, 28 Nov 2020 13:49:35 +0100 Below is my models.py class Video(models.Model): CATEGORY_CHOICES = ( ('Music', 'Music'), ('Movies', 'Movies'), ) artist = models.CharField(max_length=200, unique=True) category = models.CharField(max_length=30, choices=CATEGORY_CHOICES, default='Music') title = models.CharField(max_length=200, unique=True) slug = models.SlugField(default='', blank=True, unique=True) thumbnail = models.ImageField(blank=False) video_file = models.FileField(default='') uploaded_date = models.DateTimeField(default=timezone.now) objects = PostManager() class Meta: ordering = ['-uploaded_date'] def save(self): self.uploaded_date = timezone.now() self.slug = slugify(self.title) super(Video, self).save() def __str__(self): return self.title def get_absolute_url(self): return reverse('video:detail', kwargs={'slug': self.slug}) This is the post_detail view def post_detail(request, slug): random_posts = random.sample(list(Video.objects.all()), 2) vid = get_object_or_404(Video, slug=slug) comments = Comment.objects.filter(post=vid) is_liked … -
filtering with django rest framework
I'm using django rest framework in my project and I want to have filtering on my products . i filter products with category name and popular . but i want to filter products that have discount too . this is my model: class Product(models.Model): category = models.ManyToManyField(Category, related_name='products') name = models.CharField(max_length=500) slug = models.SlugField(max_length=500, allow_unicode=True, unique=True) image = models.ImageField(upload_to='products_pic/%Y/%m/%d/', null=True, blank=True) description = models.TextField(null=True, blank=True) price = models.PositiveIntegerField() discount = models.PositiveIntegerField(null=True, blank=True) available = models.BooleanField(default=True) popular = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) comments = GenericRelation(Comment) class Meta: ordering = ('-created',) def __str__(self): return self.name there is a problem here. discount is a integer field and i want to filter products with boolean discount. i mean i want to filter products that have discount or not. it is not important how much discount they have. this is my view: class search(generics.ListAPIView): queryset = Product.objects.filter(available=True) serializer_class = ProductSerializer permission_classes = (permissions.AllowAny,) filter_backends = [DjangoFilterBackend, filters.SearchFilter] filter_fields = ['category__name', 'popular'] search_fields = ['name', 'category__name', 'description'] -
Django this page is not rendering?
the page is keep giving me this error page is not rendering. I am not getting any error in the terminal. here is my view: class Blog_list_View(View): model = Blog template_name = 'blog.html' paginated_by = 1 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) blog_list = Blog.objects.all() category_count = get_category_count() latest = Blog.objects.order_by('-timestamp')[0:3] paginator = Paginator(blog_list, self.paginated_by) page = self.request.GET.get('page') try: blog = paginator.page(page) except PageNotAnInteger: blog = paginator.page(1) except EmptyPage: blog = paginator.page(paginator.num_pages) context['latest'] = latest, context['form'] = form, context['category_count'] = category_count, return context here is urls.py: from Blog.views import Blog_View urlpatterns = [ path('admin/', admin.site.urls), path('blog/', Blog_View.as_view(), name="blog-view"),