Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
My postgresql database doesn't persist between docker runs
I am learning docker and postgresql and I have problem with persisting data between the re-runs of the app. My docker-compose.yml: version: '3.7' services: web: build: . command: python3 /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db db: image: postgres:15 volumes: - postgres_data:/var/lib/postgresql/data environment: POSTGRES_PASSWORD: postgres ports: - "5432:5432" volumes: postgres_data: external: true I run my project with docker-compose up -d go with docker-compose exec web python3 manage.py migrate but after I go docker-compose down and I run the containers I have to migrate again. It's really bothersome. Can someone help, please? -
Cannot connect django and redis running inside the same container
I have exposed the port 6379 , this is my docker file from python:3.11.8-bookworm as builder RUN curl -sSL https://install.python-poetry.org | python3 - ENV PATH "/root/.local/bin:$PATH" ENV POETRY_NO_INTERACTION=1 \ POETRY_VIRTUALENVS_IN_PROJECT=1 \ POETRY_VIRTUALENVS_CREATE=1 \ POETRY_CACHE_DIR=/tmp/poetry_cache \ PYTHONUNBUFFERED=1 \ PYTHONDONTWRITEBYTECODE=1 WORKDIR /app COPY poetry.lock pyproject.toml ./ RUN poetry install --no-dev && rm -rf $POETRY_CACHE_DIR from python:3.11.8-slim-bookworm as runtime RUN apt-get update && apt-get install -y sudo RUN sudo apt install lsb-release curl gpg -y && curl -fsSL https://packages.redis.io/gpg | sudo gpg --dearmor -o /usr/share/keyrings/redis-archive-keyring.gpg && echo "deb [signed-by=/usr/share/keyrings/redis-archive-keyring.gpg] https://packages.redis.io/deb $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/redis.list && sudo apt-get update && sudo apt-get install redis -y && redis-server --daemonize yes EXPOSE 6379 ENV VIRTUAL_ENV=/app/.venv \ PATH="/app/.venv/bin:$PATH" COPY --from=builder ${VIRTUAL_ENV} ${VIRTUAL_ENV} COPY text_snippets /app/text_snippets COPY url_shortner /app/url_shortner COPY manage.py /app/ WORKDIR /app RUN python3 manage.py makemigrations RUN python3 manage.py migrate RUN python3 manage.py crontab add ENTRYPOINT ["python3", "manage.py", "runserver", "0.0.0.0:8000", "--noreload"] This is the caches setting in the settings.py CACHES = { "default": { "BACKEND": "django.core.cache.backends.redis.RedisCache", "LOCATION": "redis://127.0.0.1:6379", } } I start the service with docker run -p 8000:8000 name One of the views in django application connects to redis cache to get data/ save data but when I try to visit the … -
Django modal Update with preview
Hi Im trying to change some parts from a existung project. The existing project is is from Github here: https://github.com/AliBigdeli/Django-Smart-RFID-Access-Control/ I added in Card management one new field in models.py class UIDCard(models.Model): ... ammount = models.DecimalField(max_digits=8, decimal_places=2, default=0) ... Also added in the folder dashboard/api/serializers.py the price in class CardReaderSerializer Now I changed some parts in templates/card-management.html Added the field "ammount" in the genral overview, is showing me the Database value Added a Pay button, open a new Modal window, the plan is to add some money on it. The enterred value is saving on the Database, but with two issues. first, I cant see the existing values from the Database in the formfields prefilled. Like in the edit part second, the Update button is saving the value but the modal window is not closing I cant find the problems in the code, can somewhre helping me please The complete changed .html file: {% extends 'dashboard/base.html'%} {% block content %} <div class="d-flex"> <div> <h1 class="mt-4">Cards</h1> </div> <div class="ms-auto mt-4"> <button type="button " class="btn btn-warning" data-bs-toggle="modal" data-bs-target="#CreateFormModal" id="CreateDevice"> Add Card ID </button> </div> </div> <hr> <div class="table-responsive" style="height: 100%;"> <table class="table"> <thead class="table-dark"> <tr> <th scope="col">#</th> <th scope="col">Name</th> <th scope="col">Card ID</th> … -
django app deploy on vercel , serverless function has crashed
Hi guys i am trying to deploy my django app to vercel, but i have a problem when i try to deploy the backend i get an error, even though when i tried it on the local server there was no error at all can you help me to fix this ? Here is the error This Serverless Function has crashed. Your connection is working correctly. Vercel is working correctly. 500: INTERNAL_SERVER_ERROR Code: FUNCTION_INVOCATION_FAILED ID: fra1::8b4lf-1709362569275-006c244d7831 If you are a visitor, contact the website owner or try again later. If you are the owner, learn how to fix the error and check the logs. how to fix the issue -
Handling Duplicate Emails for Clients and Establishments Registration
I would like to register a client and an establishment with the same email. The problem is that if I create a client and then try to create an establishment, it tells me that the email already exists. How can I solve this issue? #models.py from django.dispatch import receiver from django.db.models.signals import post_save from django.conf import settings from rest_framework_simplejwt.tokens import RefreshToken from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): email = models.EmailField(max_length=255, unique=True) is_etablishment=models.BooleanField(default=False) is_client=models.BooleanField(default=False) is_verified=models.BooleanField(default=False) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["first_name", "last_name"] def tokens(self): refresh = RefreshToken.for_user(self) return { "refresh":str(refresh), "access":str(refresh.access_token) } def __str__(self) : return self.username @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_jwt_token(sender, instance=None, created=False, **kwargs): if created: refresh = RefreshToken.for_user(instance) instance.jwt_token = str(refresh.access_token) instance.save() class Client(models.Model): user=models.OneToOneField(User, related_name="client", on_delete=models.CASCADE) username = models.CharField(max_length=200, null=True, blank=True,default="") email = models.EmailField(max_length=255,default='') phone=models.CharField(max_length=200, null=True, blank=True) def __str__(self): return self.user.first_name class Etablishment(models.Model): user=models.OneToOneField(User, related_name="etablishment", on_delete=models.CASCADE) email = models.EmailField(max_length=255,default='') nom=models.CharField(max_length=200,default="") adresse = models.CharField(max_length=255) photo = models.ImageField(upload_to='etablissements/photos/') phone=models.CharField(max_length=200, null=True, blank=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["nom"] def __str__(self): return self.nom class OneTimePassword(models.Model): client = models.OneToOneField(Client, on_delete=models.CASCADE, null=True, blank=True) etablishment = models.OneToOneField(Etablishment, on_delete=models.CASCADE, null=True, blank=True) otp = models.CharField(max_length=6) def __str__(self): if self.client: return f"{self.client.user.first_name} - otp code" elif self.etablishment: return f"{self.etablishment.user.first_name} - otp code" else: return "OTP … -
Troubleshooting Dynamic Image Updating and Color-Based Filtering in Django Product Page
I have created a hyperlink in html So, In product_detail_page.html: <div class="product-color"> <span>Color</span> {% for c in colors %} <div class="color-choose"> <a href="?colorID={{c.id}}" style="display: inline-block; width: 40px; height: 40px; background-color: {{c.code}}; border-radius: 50%; border: 2px solid #FFFFFF; cursor: pointer; float: left; margin-right: 10px; box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.33);"> </a> </div> {% endfor %} </div> Now it is taking colors id (suppose if I click on red color it is taking {?colorID=1} in url) Now I created a view for this That if I Click in a color it will change the product Image So, In views.py def product_detail_view(request,pid): product=Product.objects.get(pid=pid) colors = Color.objects.all() sizes= Size.objects.all() p_image=product.p_images.all() products=Product.objects.filter(cagtegory=product.cagtegory) ColorID=request.GET.get('colorID') if ColorID: product=Product.objects.filter(color=ColorID) else: product=Product.objects.all() context={ "p":product, "p_image":p_image, 'colors': colors, 'sizes': sizes, 'products': products, } return render(request,"core/product_detail.html",context) and I created this models in models.py class Product(models.Model): pid=ShortUUIDField(length=10,max_length=100,prefix="prd",alphabet="abcdef") user=models.ForeignKey(CustomUser, on_delete=models.SET_NULL ,null=True) cagtegory=models.ForeignKey(Category, on_delete=models.SET_NULL ,null=True,related_name="category") vendor=models.ForeignKey(Vendor, on_delete=models.SET_NULL,null=True,related_name="product") color=models.ManyToManyField(Color,blank=True) size=models.ManyToManyField(Size,blank=True) title=models.CharField(max_length=100,default="Apple") image=models.ImageField(upload_to=user_directory_path,default="product.jpg") description=models.TextField(null=True, blank=True,default="This is a product") price = models.DecimalField(max_digits=10, decimal_places=2, default=1.99) old_price = models.DecimalField(max_digits=10, decimal_places=2, default=2.99) specifications=models.TextField(null=True, blank=True) product_status=models.CharField(choices=STATUS, max_length=10,default="In_review") status=models.BooleanField(default=True) in_stock=models.BooleanField(default=True) featured=models.BooleanField(default=False) digital=models.BooleanField(default=False) sku=ShortUUIDField(length=10,max_length=100,prefix="sku",alphabet="abcdef") date=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(null=True,blank=True) class Meta: verbose_name_plural="Products" def product_image(self): return mark_safe('<img src="%s" width="50" height="50"/>'%(self.image.url)) def __str__(self): return self.title def get_percentage(self): new_price=((self.old_price-self.price)/self.old_price)*100 return new_price class ProductImages(models.Model): images=models.ImageField(upload_to="product-image",default="product.jpg") product=models.ForeignKey(Product,related_name="p_images" ,on_delete=models.SET_NULL … -
Django ViewSet perform_create not recognizing my data
I have a Django (python) project. The problem lies in trying to use the create function for my viewset not recognising the data being past to it. (It claims a NullConstraint is not being satisfied.) My views.py includes (notice the print() statements): class MyModelInstModelViewSet(ABC, MyModelrModelViewSet): dfn_class = None def _create(self, request, *args, **kwargs): print(request.data) # Check if 'dfn_id' is provided in request.data dfn_id = request.data.get('dfn_id') if dfn_id is None: return Response({'error': 'dfn_id is required'}, status=status.HTTP_400_BAD_REQUEST) # Retrieve the Def instance try: dfn = self.dfn_class.objects.get(id=dfn_id) except self.dfn_class.DoesNotExist: return Response({'error': 'Invalid dfn_id'}, status=status.HTTP_400_BAD_REQUEST) # Get default values from Def instance data = {} # Dynamically copy each/all fields from the Def instance for field in dfn._meta.fields: data[field.name] = getattr(dfn, field.name) # Update default values with request data for key, value in request.data.items(): # If the value is a dict/JSONField, perform a deep copy if isinstance(value, dict): data[key] = copy.deepcopy(value) else: data[key] = value del data['id'] del data['updated_at'] data['created_at'] = timezone.now() if data['dfn_id'] is None: raise 'DFN ID IS NONE!' print(data) # Create a serializer instance with the updated data serializer = self.serializer_class(data=data) print('about to validate') serializer.is_valid(raise_exception=True) print('after validate') # Perform creation self.perform_create(serializer) print('after perform_create') return serializer def create(self, request, *args, **kwargs): res … -
Django's AttributeError for PointField()
I have a problem with my Django database. When I enter: python manage.py makemigrations. I got this exception: AttributeError: module 'django.db.models' has no attribute 'PointField'. Here is my very simple code that cause the issue: from django.db import models import uuid # Create your models here. class Image(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4,editable=False) location = models.PointField() # The culprit date = models.DateTimeField() image = models.ImageField() Thank you in advance. It supposed to make changes to my PostgreSQL database. Well the database hasn't been made yet, I already initialize it with SQLite WITHOUT THE CODE ABOVE. IT WAS INITIALIZED BEFORE THERE IS ANYTHING IN THE MODELS FILES, trying to switch to PostgreSQL. -
How to create a Postgresql database query in Django with BitXor bitwise comparison and filtering by Hamming distance value?
My task is to develop a function for searching images in a database using perseptual hash and Hamming distance comparison. The code below works, but due to the fact that filtering occurs in the Django environment and Python, the code runs extremely slowly, on average the execution time is more than 7 seconds with 1,500,000 records in the database, but the number of records on the production server will be much larger and the request processing speed will drop even more. models.py # models.py from django.db import models class Fids(models.Model): """ The model stores records with computed image hashes (>6000000 records) picture = 'https://ae01.alicdn.com/kf/Sc835208f704548b7b230fd12f72850bfU.jpg' hs8 = '9aca3edfc0c23538' bin8 = '1001101011001010001111101101111111000000110000100011010100111000' """ picture = models.URLField() hs8 = models.CharField(max_length=50) bin8 = models.CharField(max_length=64) service.py # service.py import requests import json import imagehash from PIL import Image from main.models import Fids def hamming_distance(binary_str1, binary_str2): """ The function calculates the Hamming distance example input: binary_str1 = '1001101011001010001111101101111111000000110000100011010100111000' binary_str2 = '1001101011001010001111101101111111000000110000100011010100111000' """ if len(binary_str1) != len(binary_str2): return -1 xor_result = int(binary_str1, 2) ^ int(binary_str2, 2) hamming_distance = bin(xor_result).count('1') return hamming_distance def search(url=None, hamming=None): """ Search query processing function example input: url = 'https://ae01.alicdn.com/kf/Sc835208f704548b7b230fd12f72850bfU.jpg' hamming = 8 output: delay: 8-15 sec """ if url is None: return … -
Invalid number of arguments in "auth_request_set" directive in /etc/nginx/sites-enabled/projectconf
I have been trying to configure my Nginx proxy server with Oauth2Proxy but I am getting the following error while trying to restart my server. 2024/03/03 08:07:41 [emerg] 370#370: invalid number of arguments in "auth_request_set" directive in /etc/nginx/sites-enabled/someapplication:64 2024/03/03 08:52:44 [warn] 968#968: server name "/var/log/nginx/someapplication_access.log" has suspicious symbols in /etc/nginx/sites-enabled/someapplication:5 2024/03/03 08:52:44 [warn] 968#968: server name "/var/log/nginx/someapplication_access.log" has suspicious symbols in /etc/nginx/sites-enabled/someapplication:39 2024/03/03 08:52:44 [warn] 969#969: server name "/var/log/nginx/someapplication_access.log" has suspicious symbols in /etc/nginx/sites-enabled/someapplication:5 2024/03/03 08:52:44 [warn] 969#969: server name "/var/log/nginx/someapplication_access.log" has suspicious symbols in /etc/nginx/sites-enabled/someapplication:39 2024/03/03 09:28:19 [emerg] 2000#2000: unknown "user" variable This is the release I am using for the library https://github.com/pusher/oauth2_proxy/releases/download/v5.0.0/oauth2_proxy-v5.0.0.linux-amd64.go1.13.6.tar.gz Following is the nginx configuration on my server server { listen 80; listen [::]:80; server_name someapplication.com; location /oauth2/ { proxy_pass http://127.0.0.1:4180; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Scheme $scheme; proxy_set_header X-Auth-Request-Redirect $request_uri; } location / { auth_request /oauth2/auth; error_page 401 = /oauth2/sign_in; # pass information via X-User and X-Email headers to backend # requires running with --set-xauthrequest flag auth_request_set $user $upstream_http_x_auth_request_user; auth_request_set $email $upstream_http_x_auth_request_email; proxy_set_header X-User $user; proxy_set_header X-Email $email; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass_header Server; proxy_connect_timeout 3s; proxy_read_timeout 10s; # if you enabled --cookie-refresh, this is needed for it … -
How to deploy a django app on render.com?
I'm totally confused how to deploy a django blog on render.com , in their docs completely explained but its so much work to do , any easy way to deploy a simple blog django app? Have no idea about data bases and other platforms , im still brand nee to this -
Do Docker volumes also update the Source application?
I am going insane for the following. I have been following youtube tutorials by two different makers and in both cases, they start with a fresh directory where there is nothing but a virtual environment. Then they add the 3 expected files Dockerfile, docker-compose.yml and the requirements. txt. Like them I get to create the container and launch it to see the django app successfully created. BUT, here is where the problem comes. Once they either stop or delete the container and they get back to the terminal prompt, that is, once they are at the OS source application and not the container, both of them can do python manage.py runserver and launch the development server, or they can migrate, but when I click on the requirements.txt on the project tree, I get a notice that Django has not been installed. I can understand that because we actually installed Django in the container but not in the source application. I know that volumes are suppose to update the container if you make changes in the application source in your IDE, but not the other way around. That is why django is not installed. Here are the files: Dockerfile: FROM python:3.8 … -
Render video from js into html
I'm new here and have a question. How can I render the webcam video from JavaScript into HTML? I want to scan QR-Codes in my browser and while scanning there should be the video from the camera for better user experience (easier to find the qr-code). For scanning the QR-Codes, I use Instascan. My code looks something like this: HTML: <div class="video-container"> <div class="overlay-box"> <video id="preview"></video> </div> </div> JavaScript: let scanner = new Instascan.Scanner({ video: document.getElementById('preview') }); // When starting scanning, activate via css document.getElementById("preview").style.display = "block"; // When stopping scanning, deactivate via css document.getElementById("preview").style.display = "none"; I tried without the css stuff, but that was not a problem. It should be a problem with the scanner ig... Expecting: that it render it into the html file that I can see the camera output while scanning Thanks for every help! PS: If it's an important information (idk); its inside a Django project -
Getting a script to run after files have been uploaded by users
I have a django project and I would like to trigger a script for every 30 items that get uploaded by users. Basically, after 30 items have been uploaded by users, the script checks the latest (i.e. last) item which has been uploaded by a user, and if there is a problem with the item it then gives a warning to the user. After 30 more items get uploaded by users the process repeats. The problem is I'm not sure how to do this since I'm new to django and I can't find any documentation for it, so if anyone has any ideas I would greatly appreciate it. Thank you! -
ListSerializer with Child 's PrimaryRelatedKeyField
When is_valid methods of ListSerializer, the queryset of the PrimaryRelatedKeyField of the Serializer specified as child is executed for the number of elements in the List. The queryset is evaluated as many times as the number of elements in the List. Is there any way to avoid this? I want to keep the number of SQL executions as low as possible. class BookSerializer(serializers.ModelSerializer): title = serializers.CharField() publisher = serializers.PrimaryKeyRelatedField(queryset=Publisher.objects.all(), source="publisher") class BookListSerializer(serializers.ListSerializer): child = BookSerializer() def create(self, validated_data): return Book.objects.bulk_create([Book(**book) for book in validated_data]) books = [ {'title': 'Django Basic', 'publisher': 1}, {'title': 'Django Advance', 'publisher': 2}, {'title': 'DRF Basic', 'publisher': 1}, {'title': 'DRF Advance', 'publisher': 2}, {'title': 'Django Professional', 'publisher': 2}, ] bookListSerializer = BookListSerializer(data=books) # In validation, queryset ( Publisher.objects.all() ) is evaluated every times. # In this example, it will be executed five times. bookListSerializer.is_valid(raise_exception=True) bookListSerializer.save() If we define it as an IntegerField in the Serializer specified as child, it will not execute many querysets, but we have to validate in another part whether the correct id is specified or not. class BookSerializer(serializers.ModelSerializer): title = serializers.CharField() publisher = serializers.IntegerField() class BookListSerializer(serializers.ListSerializer): child = BookSerializer() def create(self, validated_data): return Book.objects.bulk_create([Book(**book) for book in validated_data]) books = [ {'title': … -
ValueError: invalid literal for int() with base 10: getting that error on delete functionality when clicking delete button
i am building an ecommerce site and in cart functionality when i tried to delete the product from cart it throws an error while i used the same logic when adding product to cart where i use the same line of code to get product id through ajax integration for cart_add() view product_id = int(request.POST.get('product_id')) but in cart_delete() view it throws an error on this line invalid literal for int() with base 10: delete button from template: <button type="button" data-index=""="{{product.id}}" class="btn btn-danger btn-sm delete-button"> Delete </button>enter code here this is ajax integration <script> $(document).on('click','.delete-button',function(e){ e.preventDefault(); $.ajax({ type:'POST', url:'{% url "cart-delete" %}', data:{ product_id: $(this).data('index'), csrfmiddlewaretoken:"{{csrf_token}}", action:'post' }, success: function(json){ //console.log(json) document.getElementById('cart-qty').textContent = json.qty document.getElementById('total').textContent = json.total }, error:function(xhr,errmsh,err){ } }); }) </script> ths is my views.py def cart_delete() def cart_delete(request): cart = Cart(request) if request.POST.get('action') == 'post': product_id = int(request.POST.get('product_id')) cart.delete(product=product_id) cart_quantity = cart.__len__() cart_total = cart.get_total() response = JsonResponse({'qty':cart_quantity,'total':cart_total}) return response And this is cart.py (for session handling) delete function def delete(self,product): product_id = str(product) if product_id in self.cart: del self.cart[product_id] self.session.modified = True And urls.py path('delete/',views.cart_delete,name='cart-delete'), -
I got bugs after I install the newest version of mysqlclient for my Django project
I am doing a django project, and I am supposed be able to get the correct content with http://127.0.0.1:8000/statis/css/main.css and http://127.0.0.1:8000/media/imgs/p1.jpg. However, after I run the manage.py I can't get in with the website address because there's a mistake. And here's the bug django.core.exceptions.ImproperlyConfigured: mysqlclient 1.4.3 or newer is required; you have 1.0.2. I tried to install the newest version of mysqlclient like pip install mysqlclient pip install mysqlclient==1.3.4 but the bug still shows up. What should I do? I am not familiar with sql at all. I hope to solve the mysqlclient problem -
i want to show the default admin permission in another way
i want to remove the app name and model name show only the last one while selecting in the group making page. When showing those permission those app name and content type does not gets remove. Make the adjustment in front side only to show the code name only -
Undefined timestamp Issue in frontend with javascript
I have created django consumers.py and a frontend in html and css to disply messages sent by a user, the profile picture of the sender and the username of the sender but anytime i open the browser, the message displays well and the username appears well but the time since always appear as undefined even though i printed the time stamp from the websocket and it shows the actual timp. ususally when i send a message, i see the received timestamp on the developer console but immediately i refresh the page it changes to undefine, i simply want to be able to display the time elapsed since a essage was sent, example X seconds ago, X minutes ago, X hours ago my timestamp field is using timezone.now, Please i want a user to see the timesince a message was sent, the tmplate filere timesince isnt working though this is my consumers.py import os import json from channels.generic.websocket import AsyncWebsocketConsumer from django.contrib.auth import get_user_model from django.conf import settings from channels.db import database_sync_to_async from virtualrooms.models import VirtualRoom from .models import Interaction from django.templatetags.static import static from datetime import datetime User = get_user_model() class DiscussionRoomConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = … -
Create a queryset that automatically queries onetoone objects
I'm building a django application that has a model with multiple OneToOne relationships: class MyApp(BaseModel): site_1 = models.OneToOneField( Site, on_delete=models.CASCADE, related_name="site1", null=True ) site_2 = models.OneToOneField( Site, on_delete=models.CASCADE, related_name="site2", null=True ) site_3 = models.OneToOneField( Site, on_delete=models.CASCADE, related_name="site3", null=True ) def __str__(self): return self.title class Meta: verbose_name = "Main Application" verbose_name_plural = "Main Application" When I create a queryset using MyApp.objects.all() it returns an object with just the primary keys: { "model": "mesoamerica.mesoamericaapp", "pk": 1, "fields": { "site_1": 1, "site_2": 2, "site_3": 3 } However, I'd like to create a queryset that grabs each of the Site models by pk and attaches them to the query, rather than having to do that myself. Is there a queryset that will do this? -
django view that combines model data with all fields from its parent
I'm creating a django app where I have a model with a parent class: class BaseModel(models.Model): modified_date = models.DateTimeField(auto_now=True) class Meta: abstract = True class Site(BaseModel): name = models.CharField( max_length=25, verbose_name="Site Name (Internal) (25 char)", null=True ) and I've created a view to return the object as JSON. However, when I query and get the objects with Site.objects.all(), it doesn't contain the data from its parent class -- just the data from its own model. Now, I can go ahead and grab the primary keys and manually query the two datasets and consolidate them, but I bet there has to be a django / pythonic way to do this in a single query. prefetch_related() and select_related() dont seem to do what I want, or at least I havent figured out how to make them work for me. Does anyone have suggestions? -
CommandError: Could not load shell runner: 'IPython Notebook'
I'm having an issues starting using jupyter on my system (Mac OSX 14.2.1) even on new django projects. django-admin startproject mysite cd mysite/ pip install virtualenv virtualenv --python=$(pyenv root)/versions/3.9.18/bin/python3 env pip install jupyter ipython django-extensions # add django_extensions to INSTALLED_APPS vim mysite/settings python manage.py shell_plus --notebook Running the above has the following error: $ python manage.py shell_plus --notebook Traceback (most recent call last): File "/path/to/project/mysite/env/lib/python3.9/site-packages/django_extensions/management/commands/shell_plus.py", line 281, in get_notebook from notebook.notebookapp import NotebookApp ModuleNotFoundError: No module named 'notebook.notebookapp' CommandError: Could not load shell runner: 'IPython Notebook'. I have a feeling the answer is something really straightforward, but I've been stuck on this for weeks now and haven't gotten to the bottom of it. -
image don't render in react (django + react with vite project )
Hello I'm trying to develop a blog using django as a backend and react on the frontend. i've written a map function on the frontend to loop through the blog articles, all other field elements appears but the images don't render. the following are some files that i think might be relevenat for this case models.py from django.db import models from django.contrib.auth import get_user_model # Create your models here. class Category (models.Model): name = models.CharField(max_length=150) class Meta: verbose_name_plural = 'Categories' def __str__(self): return self.name class Post (models.Model): title = models.CharField(max_length=200) description = models.CharField(max_length=500) body = models.TextField(null=True) published = models.DateTimeField('Date published', auto_now_add=True) modified = models.DateTimeField('Date published', auto_now_add=True) category = models.ForeignKey(Category, default="", verbose_name='Categories', on_delete=models.SET_DEFAULT ) author = models.ForeignKey(get_user_model(), default=1, on_delete=models.SET_DEFAULT) image = models.ImageField(default='default/no_image.png', upload_to='blog/%Y/%m/%d', max_length=255) def __str__(self): return self.title serializer.py from rest_framework import serializers from django.contrib.auth.models import User from .models import * class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = '__all__' class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' class UserRegSerializer(serializers.ModelSerializer): username = serializers.CharField(max_length=150) username = serializers.CharField(max_length=100, write_only=True) def create(self, validated_data): user = User.objects.create( username = validated_data['username'], password = validated_data['password'] ) return user urls.py from django.urls import path from … -
whisperx diarization no module named 'julius'
I am trying to get this python file to run which takes an mp3 file and converts it to text with unique speaker ID's: import whisperx import gc device ="cuda" batch_size = 32 compute_type = "float16" audio_file = "MEGA64 PODCAST 483.mp3" audio = whisperx.load_audio(audio_file) model = whisperx.load_model("large-v2", device, compute_type=compute_type) result = model.transcribe(audio, batch_size=batch_size) print(result["segments"]) model_a, metadata = whisperx.load_align_model(language_code=result["language"], device=device) result = whisperx.align(result["segments"], model_a, metadata, audio, device, return_char_alignments=False) # https://huggingface.co/settings/tokens # new read token HUGGING_FACE_TOKEN="xxxx" diarize_model = whisperx.DiarizationPipeline(use_auth_token=HUGGING_FACE_TOKEN, device=device) diarize_segments = diarize_model(audio, min_speakers=2, max_speakers=2) print(diarize_segments) print(diarize_segments.speaker.unique()) result = whisperx.assign_word_speakers(diarize_segments, result) print(diarize_segments) print(result["segments"]) # segments area now assigned speaker IDs I am using a python3 virtual env, so when I activate it, and try to run my above script with python ex.py I get this error output: (venv_name) C:\Users\martin\Documents\projects\diarisation\Test2>python ex.py C:\Users\martin\Documents\projects\diarisation\venv_name\Lib\site-packages\pyannote\audio\core\io.py:43: UserWarning: torchaudio._backend.set_audio_backend has been deprecated. With dispatcher enabled, this function is no-op. You can remove the function call. torchaudio.set_audio_backend("soundfile") Traceback (most recent call last): File "C:\Users\martin\Documents\projects\diarisation\Test2\ex.py", line 1, in <module> import whisperx File "C:\Users\martin\Documents\projects\diarisation\venv_name\Lib\site-packages\whisperx\__init__.py", line 1, in <module> from .transcribe import load_model File "C:\Users\martin\Documents\projects\diarisation\venv_name\Lib\site-packages\whisperx\transcribe.py", line 10, in <module> from .asr import load_model File "C:\Users\martin\Documents\projects\diarisation\venv_name\Lib\site-packages\whisperx\asr.py", line 13, in <module> from .vad import load_vad_model, merge_chunks File "C:\Users\martin\Documents\projects\diarisation\venv_name\Lib\site-packages\whisperx\vad.py", line 9, in <module> from pyannote.audio … -
Django save post via celery
I have a particular use case where i write text for a blog post in admin dashboard. Then i want to generate the embeddings of post. I am doing this in admin.py @admin.register(Post) class PostAdmin(admin.ModelAdmin): list_display = ('title', 'author', 'created_at') readonly_fields = ('embeddings_calculated','emebddings_updated_at') def save_model(self, request, obj, form, change): if not obj.meta_title: obj.meta_title = obj.title obj.meta_description = obj.content[:160] super().save_model(request, obj, form, change) print("django post id",obj.id) post = get_object_or_404(Post, id=obj.id) print("django post title",post) if not change: # if new post not an edit post task_id = perform_task.delay(obj.id) result = AsyncResult(str(task_id), app=app) print("AsyncResultx", result) print("AsyncResultx_state", result.state) here is my celery task @shared_task() def perform_task(post_id): print("celery post id",post_id) post = get_object_or_404(Post, id=post_id) print("celery post title",post) I am getting this error django.http.response.Http404: No Post matches the given query. Though the print statement such as django post id and django post title show me correct result. But the issue lies in celery. I cant see celery post title in console. I aslo tried task_id = transaction.on_commit(lambda: perform_task.delay(obj.id)) But it did not work as well. Without celery every thing work well, but i want to use celery.