Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I want to make a comilation cutter in the browser using only 1 ffmpeg feature
I want to make a website where people can put in compilations and get them automatically cut in to different scenes. This is already possible with PySceneDetect. But the process looks really "back-end-y" I want a process for the frontend where people can drop a file, the file gets processed with PySceneDetect then all the seperate clips get spit out and people can add titles tags and feedback to them so they get sorted and posted on my website. Can someone tell me if this is possible and how? I am not experienced. -
Django better way to avoid KeyError?
I was building a simple weather app with Django. This app allows the user to enter a city name and it will give the weather details of that city. I am using an API to fetch the data. I wanted to avoid KeyError when an user enters an empty string or misspelled a city. I kinda achieved my goal, but I wonder if there is a much easier way to do this. Here is my code: from django.shortcuts import render import requests from datetime import datetime import geonamescache # Used for match checking def home(request): # Checks for legitimate cities if 'search-city' in request.POST: gc = geonamescache.GeonamesCache() while request.POST['search-city'] != '': cities = str(gc.get_cities_by_name(request.POST['search-city'])) if request.POST['search-city'] in cities: city = request.POST['search-city'] break elif request.POST['search-city'] not in cities: city = 'Amsterdam' break while request.POST['search-city'] == '': city = 'Amsterdam' break # Call current weather URL = 'https://api.openweathermap.org/data/2.5/weather' API_KEY = 'c259be852acd2ef2ab8500d19f19890b' PAR = { 'q': city, 'appid': API_KEY, 'units': 'metric' } req = requests.get(url=URL, params=PAR) res = req.json() city = res['name'] description = res['weather'][0]['description'] temp = res['main']['temp'] icon = res['weather'][0]['icon'] country = res['sys']['country'] day = datetime.now().strftime("%d/%m/%Y %H:%M") weather_data = { 'description': description, 'temp': temp, 'icon': icon, 'day': day, 'country': country, 'city': city … -
Does Django 1.9.5 support PostgreSQL 11?
The end-of-life for Postgres 10 on Heroku is closer and closer, but I still have a legacy project on Django 1.9 using it there. Is it possible to migrate to Postgres 11 without troubles? -
How to convert this mysql query to django queryset
I dont know how to do ranking in queryset of ordered by different criterias. How can i convert this sql to queryset ? SELECT t.user_id, t.country_id, t.score, RANK() OVER (PARTITION BY t.country_id ORDER BY t.score DESC) AS countryRank, RANK() OVER (ORDER BY t.score DESC) AS globalRank FROM ( SELECT user_id, country_id, score FROM user_scores WHERE standard = 5 ) AS t LIMIT 50 OFFSET 50; -
classification failed path should be path-like or io.BytesIO, not <class 'django.db.models.fields.files.ImageFieldFile'>
i'm trying to build an image classifier using django and react, here i've build and a drop zone for images and i've got this a dropzone data trasfer in rest my code -
Unable to access the S3 bucket with django: ValueError: Invalid endpoint
I'm trying to integrate S3 Bucket with my django application. But always getting this error. raise ValueError("Invalid endpoint: %s" % endpoint_url) ValueError: Invalid endpoint: <bucket_name>.s3.amazonaws.com These are my settings.py configurations AWS_ACCESS_KEY_ID = config('STATIC_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('STATIC_SECRET_KEY') AWS_S3_REGION_NAME = config('AWS_REGION') AWS_STORAGE_BUCKET_NAME = config('STATIC_BUCKET_NAME') AWS_S3_ENDPOINT_URL = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' AWS_DEFAULT_ACL = 'public-read' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATIC_URL = 'https://%s/%s/' % (AWS_S3_ENDPOINT_URL, AWS_LOCATION) I have referred the answers here, ValueError: Invalid endpoint: https://s3..amazonaws.com Region is set correct. -
Sync data from api to wagtail
I was wondering if there is an example of how to create or update wagtail page? I would like to sync data from /api/ endpoint to wagtail page. I made an example how create, and it works, but with update I have to change some logic. I tried to add a different primary key and use it to save the id from api but i got an error: Attempted to add a tree node that is already in the database def get_some_data(): products = some_api_endpoint() product_page_content_type = ContentType.objects.get_for_model(Product) language_en = Language.objects.get(code="en") home_page_en = HomePage.objects.get(language=1) product_index_page_en = ProductsPage.objects.descendant_of( home_page_en ).first() for level_1 in products: for level_2 in level_1["general"]: # product_en, _ = Product.objects.update_or_create( # id=level_2["id"], # ) # product_en.language = level_2["id"] # product_en.title = level_2["name"] # product_en.draft_title = level_2["name"] # product_en.code = level_2["id"] # product_en.content_type=product_page_content_type, product_en = Product( # id=level_2["id"], # won't work, must be incremental language=language_en, title=level_2["name"], draft_title=level_2["name"], code=level_2["id"], content_type=product_page_content_type, ) product_index_page_en.add_child(instance=product_en) product_en.save() class Command(BaseCommand): def handle(self, *args, **options): get_some_data() -
How to get current user data in django
I'm trying to get logged user data but I get an only username I try these codes user= User.objects.get(id=user_id) user= User.objects.filter(id=emp_data.user_id).first() user =request.user this 3 query returns username how can i get user details -
How to use multiple SMTP in django_mail_admin (Gmail & Outlook)
We are using django_mail_admin in our project to send and receive emails. Our requirement is to send email on both accounts Gmail and Outlook. 1- Gmail Account will send E-mail to Gmail account using Gmail SMTP 2- Outlook Account will send E-mail to Outlook account using outlook SMTP. NOTE: Switch SMTP is a function to change SMTP according to Gmail and Outlook. Use of single Gmail account :- Gmail is sending Email to Gmail account, Sender and Receiver both from Gmail, working fine. Use of single Outlook account :- Outlook is sending Email to Outlook account, Sender and Receiver both from Outlook, working fine. Use of Gmail and outlook together When we use Gmail and outlook together and we Switch SMTP Gmail to Outlook, then we are facing issue (Sender not changing, Gmail Receive email from Gmail but Outlook Receive email from Gmail) -
Signals don't work when outside MQTT script inserts data to database
I have django project and I have signals in model.py file. I created demo just to show what problem is def func(sender, instance, created, **kwargs): try: if created: print("WORKED") except BaseException as e: import traceback print(traceback.format_exc()) post_save.connect(func, sender=MyTable, dispatch_uid="IDDD") When I insert data from admin panel, everything is OK, it prints,however, when I use simple script which inserts to MyTable, signal does not work, but data is saved to the table. -
Django ListView - getting the most recent related object and preventing Django from caching the view or database query
I have a Campaign model and a CampaignStatus model whose foreign key is the Campaign model. When a Campaign is edited or created it will pass through several statuses and will have a CampaignStatus object associated with each status change. Using Django's CBVs, I have a list view that shows a users Campaigns, and I want to pass the most recent status in the context to the template. Django seems to be caching the status and I don't know how to prevent it. (Possibly relevant: the Django admin campaign view also has the same caching problem - I've defined a method to get the most recent status. The Django admin CampaignStatus list view behaves as expected, always showing new statuses as soon as they're created.) I would like the cache to be 5 seconds, but it appears to be about 3 minutes. How can I change this? A code snippet from the generic ListView we're using: @method_decorator(cache_page(5), name="dispatch") # single arg is seconds class CampaignsListView(LoginRequiredMixin, ListView): model = Campaign paginate_by = 100 template_name = "writing/user_campaigns.html" context_object_name = "user_campaigns" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) for i, _ in enumerate(context.get("user_campaigns")): campaign = context["user_campaigns"][i] campaign_status = CampaignStatus.objects.filter(campaign=campaign).latest("-status") context["user_campaigns"][i].status = campaign_status.get_status_display() return context … -
ImportError: cannot import name 'ugettext_lazy' from 'django.utils.translation'
I imported from rest_auth.views import LoginView and I am trying to implement login api and I never import ugettext_lazy directly. from rest_auth.views import LoginView from django.contrib.auth import authenticate, login, logout from .serializers import LoginUserSerializer class Login(LoginView): def post(self, request, *args, **kwargs): serializer = LoginUserSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] login(request, user) return super().post(request, format=None) I recieved this problem File "C:\Users\v_kum\Documents\My Project\wshp\app_mypage\urls.py", line 4, in <module> from .login import Login File "C:\Users\v_kum\Documents\My Project\wshp\app_mypage\login.py", line 1, in <module> from rest_auth.views import LoginView File "C:\Users\v_kum\Documents\myenv\lib\site-packages\rest_auth\views.py", line 9, in <module> from django.utils.translation import ugettext_lazy as _ ImportError: cannot import name 'ugettext_lazy' from 'django.utils.translation' (C:\Users\v_kum\Documents\myenv\lib\site-packages\django\utils\translation\__init__.py) I read the other answers and most of answer suggested to downgrade from the django version 4 to 3. Is there any other ways to fix this problem or any other suggestion to implement login api? -
send video chunks from django to react
I've a video comming from rstp feed, I successfully processed it using openCV python. now it is generating image frames and I want to sent these image frames directly to frontend as they are generated. while True: success, img = cap.read() img = cv2.resize(img, (0, 0), None, 0.5, 0.5) ih, iw, channels = img.shape blob = cv2.dnn.blobFromImage( img, 1 / 255, (input_size, input_size), [0, 0, 0], 1, crop=False) net.setInput(blob) layersNames = net.getLayerNames() outputNames = [(layersNames[i - 1]) for i in net.getUnconnectedOutLayers()] outputs = net.forward(outputNames) postProcess(outputs, img) # I want to send these frames to my react frontend cv2.imshow('Output', img) if cv2.waitKey(1) == ord('q'): break I've already work with API's but never encountered such situation I'm confused how do I send these frames to my frontend. If streaming server is required, please share some references, any help will be appreciated. -
how to access the url after Django rest frame router
I am unable to access the url after path("", include(router.urls)), i would like to render a template after the load i am using django rest framework and i want to access the url after the rest fromework router and render a template from django.urls import path, include from rest_framework import routers from .views import NSE_DATA_VIEW_SET, AddCoi router = routers.DefaultRouter() router.register(r"", NSE_DATA_VIEW_SET) urlpatterns = [ path("", include(router.urls)), path("add", AddCoi) ] Image from django.urls import include, path urlpatterns = [ path("nsedata/", include("api.nsedata.urls")), path("coidata/", include("api.coidata.urls")) ] -
Upon email verification endpoint I'm getting an Invalid token error while trying to activate a user with tokens sent to the mail?
from django.db import models from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, PermissionsMixin) from rest_framework_simplejwt.tokens import RefreshToken class UserManager(BaseUserManager): def create_user(self,username,email, password=None ): if username is None: raise TypeError("Users should have a username") if email is None: raise TypeError("Users should have an Email") user =self.model(username=username, email=self.normalize_email(email)) user.set_password(password) user.save() return user def create_superuser(self, username, email, password=None): if password is None: raise TypeError("Password should not be none") user = self.create_user(username, email, password) user.is_superuser = True user.is_staff = True user.save() return user class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=100, unique=True, db_index=True) email = models.EmailField(max_length=100, unique=True, db_index=True) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["username"] objects = UserManager() def __str__(self): return self.email def tokens(self): refresh = RefreshToken.for_user(self) return { "refresh":str(refresh), "access": str(refresh.access_token) } Below is the serializers.py file from .models import User from rest_framework import serializers from django.contrib import auth from rest_framework.exceptions import AuthenticationFailed class RegisterSerializer(serializers.ModelSerializer): password = serializers.CharField(max_length=50, min_length=6, write_only =True) class Meta: model = User fields = ["email", "username", "password"] def validate(self, attrs): email = attrs.get("email", '') username = attrs.get("username", '') if not username.isalnum(): raise serializers.ValidationError("The username should contain only alphanumeric characters") return attrs def create(self, validated_data): return User.objects.create_user(**validated_data) class EmailVerificationSerializer(serializers.ModelSerializer): token … -
disable or enable checkboxes if belong to parent class
I have 2 tabs with a list of checkboxes. I'd like to create dependent checkboxes so if the user will select a checkbox in the first tab then it will disable all checkboxes in tab 2 that don't belong to the checkbox in tab 1. Both client_list and business_challange are the filters for my products and they are connected in relation ManyToMany with the Product model (models with view below). html file <div class="container"> <ul class="nav nav-tabs flex-row f-12 mb-3" id="myTab" role="tablist"> <li class="nav-item" role="presentation"> <button class="nav-link active" id="client-list-tab" data-bs-toggle="tab" data-bs-target="#client_list" type="button" role="tab" aria-controls="client_list" aria-selected="true">Client</button> </li> <li class="nav-item" role="presentation"> <button class="nav-link" id="business-challange-tab" data-bs-toggle="tab" data-bs-target="#business_challange" type="button" role="tab" aria-controls="business_challange" aria-selected="false">Challanges</button> </li> </ul> <div class="tab-content filters" id="myTabContent"> <div class="tab-pane fade show active" id="client_list" role="tabpanel" aria-labelledby="client-list-tab"> <div class="parent-checkbox"> {% for object in client_list %} <div class="form-check"> <input class="form-check-input" type="checkbox" value="{{object.title}}" id="{{object.title}}" data-filter="client_list" name="showCb" onclick="showMe('uncheck-all')"> <label class="form-check-label ps-2" for="{{object.title}}"> {{object.title}} </label> </div> {% endfor %} </div> </div> <div class="tab-pane fade" id="business_challange" role="tabpanel" aria-labelledby="business-challange-tab"> <div class="child-checkbox"> {% for object in business_challange %} <div class="form-check"> <input class="form-check-input" type="checkbox" value="{{object.title}}" id="{{object.title}}" data-filter="business_challange" name="showCb" onclick="showMe('uncheck-all')"> <label class="form-check-label ps-2" for="{{object.title}}"> {{object.title}} </label> </div> {% endfor %} </div> </div> </div> </div> js file $(document).on('click', '.parent-checkbox input[type=checkbox]', function (event) { // If … -
Django - Custom model field with default value
How can I set default value for timestp field ? Default value > 'NOW()' class Timestamp(models.Field): def db_type(self, connection): return 'timestamp' class MyModel(Model): # ... my_field = Timestamp() -
Access RelatedManager object in django
I have the following model : class Travel(models.Model): purpose = models.CharField(max_length=250, null=True) amount = models.IntegerField() class TravelSection(models.Model): travel = models.ForeignKey(Travel, related_name='sections', on_delete=models.CASCADE) isRoundTrip = models.BooleanField(default=True) distance = models.FloatField() transportation = models.CharField(max_length=250) I create object without using the database : mytravel = Travel( purpose='teaching', amount=1 ) mysection = TravelSection( travel=mytravel, isRoundTrip=True, distance=500, transportation='train' ) When I try to access mytravel.sections, I can't access to the field distance and other fields. How can I do this wihtout having to save in the database ? I don't want to create objects in the database, beaucause I'm trying to make some preprocessing. Thanks for your help -
Can I write RIGHT JOIN queryset in Django ORM?
How can I write RIGHT JOIN and ORDER BY queryset in Django ORM? For example I have two table : NEWS | id | title | | -------- | -------------- | | 1 | News 1 | | 2 | News 2 | | 3 | News 3 | | 4 | News 4 | COMMENTS | id | news_id | like_count | | -------- | -----|----- | | 1 | 1 | 100 | | 2 | 1 | 90 | | 4 | 3 | 245 | select n.title from NEWS n right join Comment c on n.id = c.news_id order by c.like_count DESC; wanted result: title like_count News 3 245 News 1 100 News 1 90 -
Django doesn't respect Prefetch filters in annotate
class Subject(models.Model): ... students = models.ManyToMany('Student') type = models.CharField(max_length=100) class Student(models.Model): class = models.IntergerField() dropped = models.BooleanField() ... subjects_with_dropouts = ( Subject.objects.filter(category=Subject.STEM). prefetch_related( Prefetch('students', queryset=Students.objects.filter(class=2020)) .annotate(dropped_out=Case( When( students__dropped=True, then=True, ), output_field=BooleanField(), default=False, )) .filter(dropped_out=True) ) I am trying to get all Subjects from category STEM, that have dropouts of class 2020, but for some reason I get Subjects that have dropouts from other classes as well. I know that I can achive with subjects_with_dropouts = Subject.objects.filter( category=Subject.STEM, students__dropped=True, students__class=2020, ) But why 1st approach doesn't work? I am using PostgreSQL. -
How to adjust the setting file to have the smallest (lightest) django source?
I want to build a lightest django source and how to set it in the settings.py As I notice, whenever I build and migrate a django source. There are tables which will be migrate by default such as: auth_group auth_group_permissions ... django_admin_log django_content_type ... In the situation, that I only need to build a source that server a couple of tables and CRUD (create, retrieve, update, delete) rows on that table. I dont need auth and django things. What should I do ? -
Django using the auth_user table in relationships
I'd like to use the auth_user table in one-to-many and many-to-many relationships. Is this a bad idea? Can I do it? How do I do it? Everything is happening through Admin. So, I just need the models. -
Django ManytoManyField query does not exist
I've created models for the logic of friend list and friend request. In the FriendRequest I've defined a method which adds User relation to FriendList if accept method is called. However I'm unable to do so because of the error shown below. I don't understand the error as I'm adding the User in the model. views.py friend_request = FriendRequest.objects.get(id=request_id) if request_option == 'accept': friend_request.accept() if request_option == 'decline': friend_request.decline() models.py class FriendList(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="user") friends = models.ManyToManyField(User, blank=True, related_name="friends") def add_friend(self, account): if not account in self.friends.all(): self.friends.add(account) self.save() class FriendRequest(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name="sender") receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name="receiver") is_active = models.BooleanField(blank=False, null=False, default=True) timestamp = models.DateTimeField(auto_now_add=True) def accept(self): receiver_friend_list = FriendList.objects.get(user=self.receiver) if receiver_friend_list: receiver_friend_list.add_friend(self.sender) sender_friend_list = FriendList.objects.get(user=self.sender) if sender_friend_list: sender_friend_list.add_friend(self.receiver) self.is_active = False self.save() def decline(self): self.is_active = False self.save() raise self.model.DoesNotExist( friends.models.FriendList.DoesNotExist: FriendList matching query does not exist. -
RabbitMQ : How to check queue content when processing a task using celery?
I have setup a basic message and task queue using RabbitMQ and Celery in my Django app. According to my understanding the when I use delay menthod, that pushes my tasks to the rabbitMQ queue and one of my workers from my celery app fetches the same from queue to execute the same. Is there any way in which when I push the task to the queue using delay I can view the same on my message queue RabbitMQ management portal? Since the tasks are almost instantly fetched and processed there is no chance of viewing them on the portal. This is what I tried which I think is wrong by adding a sleep timer in my task method. sudo nano tasks.py from __future__ import absolute_import, unicode_literals from celery import shared_task import time @shared_task def add(x, y): time.sleep(100) return x + y Started my celery app (myprojectenv) root@ubuntu-s-1vcpu-1gb-blr1-01:/etc/myproject# celery -A myproject worker -l info Pushed the tasks for processing (myprojectenv) root@ubuntu-s-1vcpu-1gb-blr1-01:/etc/myproject# python3 manage.py shell Python 3.8.10 (default, Mar 15 2022, 12:22:08) [GCC 9.4.0] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from app1.tasks import add >>> add.delay(1,2) On celery window [2022-06-10 06:16:15,182: INFO/MainProcess] celery@ubuntu-s-1vcpu-1gb-blr1-01 ready. … -
Validation Error {'__all__': ['Model with this field1, field2, field3 and field4 already exists.']} not getting handled by Django in admin
When I enter duplicate values for field1, field2, field3 and field4 in the django admin form, the debug screen with Validation Error appears Validation Error {'all': ['Model with this field1, field2, field3 and field4 already exists.']} instead of getting handled by the djnago admin form. The solution was I had excluded the field1 in my django admin.py file for the Model, I removed it from exclude and entered field1 in the fields of my Model Form. P.S. : readonly fields do not work in this scenario, you need to include the field in normal field, but you can add it as in custom form as widget readonly.