Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Dictionary Issue With API
I have a DJANGO dictionary that I am trying to send via API to another service, however when specifying the keys, I get an error in DJANGO. TypeError: list indices must be integers or slices, not str. Here is the output of my dictionary. "receipt_details": [ { "product__name": [ { "product__name": "Pokemon 25th Anniversary", "quanity": 1, "product__point_price": 100.0, "order_id": 32 }, { "product__name": "Minecraft - Nintendo Switch", "quanity": 1, "product__point_price": 100.0, "order_id": 32 } ], Here is my code on my view, dictionary creation, and API. @login_required def checkoutcomplete(request): customer = request.user order = Order.objects.get(customer= customer , complete = False, ) favorites = Favorite.objects.filter(customer = customer.id) today_date = datetime.datetime.today() today_date_strf = datetime.datetime.strftime(today_date,"%m/%d/%Y" ) items = order.orderitem_set.all() data = items.values("product__name","quanity","product__point_price", "order_id") data_list = list(data) receipt_details = { } for count, data in enumerate (data_list): receipt_details = data_list print(receipt_details) <-- This is at this point a dictionary after the for loop. try: student = Student.objects.get(email = customer.email) counselor = User.objects.get(id = student.counselor_id) points = K8RunningPoints.objects.filter(student_ps = student.studentpsid).aggregate(Sum("running_total"))['running_total__sum'] #POST MARK API url = "https://api.postmarkapp.com/email/withTemplate" payload = json.dumps({ "From": "", "To": "", "TemplateId": 28132290, "TemplateModel": { "counselor_name": "Fellow Counselor", "student_name": student.student_name, "receipt_id": str(order.transaction_id), "date": today_date_strf, "points": order.get_cart_total, "receipt_details": [ { "product__name": receipt_details['product__name'], <-- This … -
Django's DateTimeField is None in serializer
I use DRF and i have Bid model, i have DateTimeField which has auto_now_add and when i send data from Postman accordingly i do not send time. and then i want to validate this time in serializer's validate function but when i call that time, it's None. what i can that receive time in serializer? i send data like this { "user": 12, "product": 5 } this is my code -> class Bid(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name=_('მომხმარებელი')) product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True, blank=True, verbose_name=_('პროდუქტი')) price = models.IntegerField(default=0) time = models.DateTimeField(auto_now_add=True, verbose_name=_('დრო')) def __str__(self): return self.product.name def save(self, *args, **kwargs): if self.price == 0: self.product.current_price += 1 self.product.save() self.price = self.product.current_price else: self.product.current_price += self.price self.product.save() super(Bid, self).save(*args, **kwargs) view class BidView(generics.ListCreateAPIView): serializer_class = BidSerializer queryset = Bid.objects.all() def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) serializer class BidSerializer(serializers.ModelSerializer): class Meta: model = Bid fields = '__all__' def validate(self, data): all_bids = Bid.objects.filter(product=data.get('product').id).last() print(data.get('price')) <--- this is None if data.get('price'): if data.get('product').current_price > data.get('price'): raise ValidationError({"price_error": "შენი შეთავაზება მიმდინარე ფასზე ნაკლებია"}) return data -
cannot adapt type when using custom field in django admin panel
I'm trying to add custom field to the actor admin panel to show the movie counts each contributed in admin panel.. from django.contrib import admin from actors.models import Actor @admin.register(Actor) class ActorAdmin(admin.ModelAdmin): search_fields = ('actor_name',) list_filter = ('gender',) list_display = ['actor_name', 'age', 'gender', 'movies_count'] readonly_fields = ['movies_count'] def movies_count(self, obj): count = 0 for mv in Actor.objects.raw('select * from movies_movie_actors ' 'where actor_id=' '(select id from actors_actor where actor_name="%s")', [obj]): count += 1 return str(count) movies_count.short_description = 'movie count' but I get error Exception Type: ProgrammingError Exception Value: can't adapt type 'Actor' what does the error mean, why is it show and how to solve it (different approach with the same goal is acceptable) maybe relevant actor model : from django.db import models GENDER_LIST = [('male', 'male'), ('female', 'female')] class Actor(models.Model): actor_name = models.fields.CharField(verbose_name='Name', max_length=25, unique=True) gender = models.CharField(verbose_name='Gender', choices=GENDER_LIST, max_length=6, default='male') age = models.IntegerField(default=0) create_time = models.TimeField(verbose_name='Created at', auto_now=True) update_time = models.TimeField(verbose_name='Updated at', auto_now=True) def __str__(self): return f'{self.actor_name}' movies model : from django.db import models from django.db.models import CASCADE from director.models import Director class Movie(models.Model): movie_name = models.fields.CharField(verbose_name='movie name', max_length=25, unique=True) production_year = models.IntegerField(verbose_name='production year') actors = models.ManyToManyField('actors.actor') director = models.ForeignKey(Director, on_delete=CASCADE, related_name='movies') create_time = models.TimeField(verbose_name='Created at', auto_now=True) update_time … -
DJANGO Dictionary/ JSON
I have a DJANGO dictionary that I am trying to send via API to another service, however when specifying the keys, I get an error in DJANGO. TypeError: list indices must be integers or slices, not str. Here is the output of my dictionary. "receipt_details": [ { "product__name": [ { "product__name": "Pokemon 25th Anniversary", "quanity": 1, "product__point_price": 100.0, "order_id": 32 }, { "product__name": "Minecraft - Nintendo Switch", "quanity": 1, "product__point_price": 100.0, "order_id": 32 } ], Here is my code on how I am creating the dictionary. @login_required def checkoutcomplete(request): customer = request.user order = Order.objects.get(customer= customer , complete = False, ) favorites = Favorite.objects.filter(customer = customer.id) today_date = datetime.datetime.today() today_date_strf = datetime.datetime.strftime(today_date,"%m/%d/%Y" ) items = order.orderitem_set.all() data = items.values("product__name","quanity","product__point_price", "order_id") data_list = list(data) receipt_details = { } I know it's looking for me to specify an index however, I have multiple items I want to send. So what do I do to over come this? Thanks Here is the API info I'm sending. #POST MARK API url = "https://api.postmarkapp.com/email/withTemplate" payload = json.dumps({ "From": "", "To": "", "TemplateId": 28132290, "TemplateModel": { "counselor_name": "Fellow Counselor", "student_name": student.student_name, "receipt_id": str(order.transaction_id), "date": today_date_strf, "points": order.get_cart_total, "receipt_details": [ { "product__name": receipt_details['product__name']['product__name'], <-- Wants me to … -
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 ?