Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to do `jsonb_array_elements` in where condition in django models
I have a model: class Profile(models.Model): ... criteria = models.JSONField() The criteria could look like: { "product_uuids": [uuid1, uuid2, ...] } I need to run a query: SELECT * FROM profilemodel WHERE deleted_at IS NULL and (criteria -> 'product_uuids')::text !='null' AND NOT EXISTS( select product_uuid::varchar from jsonb_array_elements(criteria -> 'product_uuids') as product_uuid where product_uuid::varchar not in ( select my_product::varchar from jsonb_array_elements('["uuid1", "uuid2", ...]'::jsonb) as my_product) ) The query wants to get all profiles that don't have any product uuid that's not in the expected list ["uuid1", "uuid2", ...]. I tried to annotate the jsonb_array_elements(criteria -> 'product_uuids') on the profile model, but it's not using the outer layer's model, the query was not generated as expected. Would love to get some suggestions here. Thanks! -
How retuen all rows of a group item in DJANGO?
My data base is real estated related and I have history of transaction of properties. I have this code: ` def filter_model(estate, years=[], exact_match=False, distance_km=None): query_filter = Q(location__postal_code__isnull=False, sold_histories__isnull=False) if distance_km: query_filter &= Q(location__point__distance_lte=( estate.location.point, distance_km)) query_filter &= Q(type=estate.type) query_filter &= Q(square_feet__isnull=False) # >1500 query_filter &= Q(year_built__isnull=False) if estate.type == 2: address = str(estate.location.address).split('#')[0].strip() query_filter &= Q(location__address__icontains=address) estates = Estate.objects.prefetch_related( # ? This is for speed up loop. 'location__city', 'location__neighbourhood', Prefetch('sold_histories', queryset=SoldHistory.objects.order_by('-date')) ).filter(query_filter).distinct() else: if len(years) == 2: query_filter &= Q(sold_histories__date__year=years[0]) if exact_match: query_filter &= Q(location__city__province__id=estate.location.city.province.id) else: query_filter &= Q(location__city__id=estate.location.city.id) estates = Estate.objects.prefetch_related( # ? This is for speed up loop. 'location__city', 'location__neighbourhood', Prefetch('sold_histories', queryset=SoldHistory.objects.filter(date__year__in=years)) ).filter(query_filter).filter(sold_histories__date__year=years[1]).distinct() return [ [ e.id, e.bedrooms, e.type, e.year_built, e.square_feet, e.lot_size, e.location.id, e.location.address, e.location.postal_code, e.location.latitude, e.location.longitude, e.location.city.name if e.location.city else None, e.location.neighbourhood.name if e.location.neighbourhood else None, sh.date, sh.price ] for e in estates for sh in e.sold_histories.all() ]` I need to optimize this code, the reason I made the list is that I need to return all history of an address from the database. I am using this code to get data, km = 1 * 1000 estates_by_km.extend(filter_model(estate=estate, distance_km=km//2)) If I don't return the list it would only return the last history per each address. Is … -
Cannot insert PSOT data in SQLlite3 db in Django - NOT NULL constraint failed error
I have a page with 10 questions and a comment field. The questions' answers are selected via are radio buttons, the comment is a text field. When I tr to get the POST data entered into my SQL data base I get the error: NOT NULL constraint failed: ISO22301_answer.value The SQL table has 3 fields: Name - an identifier from LQ1 to LQ10 Answer - integer from 0 - 5 Question - a FK that has the text of the question being answered. Since the questions are in teh db when I g to admin they show up as a drop down in answer. The relevant file snippets are: models.py class Topic(models.Model): name = models.CharField(max_length=30) def __str__(self): return f"{self.name}" class Question(models.Model): question = models.CharField(max_length=200) name = models.CharField(max_length=20) # THis is probably useless topic = models.ForeignKey( Topic, on_delete=models.CASCADE ) # Django will store this as topic_id on database class Answer(models.Model): value = models.IntegerField() name = models.CharField(max_length=20) # q_id = models.CharField(max_length=10, default="XX") # USed foreignkey instead question = models.ForeignKey( Question, on_delete=models.CASCADE ) def __str__(self): return f"{self.question} value is {self.value}" leadership.html (one of the 10 rows): <td colspan="7">Risk Assessment and Planning</td> <tr> <td class="question">Conducts annual risk assesments and identifies key risks and mitigation … -
First full stack site what could be better
Developed a full stack site using react and django, got it running great would like input on what I've done and ideas for improvements. Book Review Site Git for project Readme.md is not fully up to date and will be getting rewritten soon -
Django ORM querying nested many to many table efficiently?
SO lets say I am designing a db for cooking session models as below from django.db import models class Recipe(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Step(models.Model): name = models.CharField(max_length=255) recipes = models.ManyToManyField(Recipe, related_name='steps') def __str__(self): return self.name class CookingSession(models.Model): name = models.CharField(max_length=255) steps = models.ManyToManyField(Step, related_name='cooking_sessions') def __str__(self): return self.name How can I use minimal number of queries (preferably one) to get all steps for a certain cooking session where each step should have the corresponding recipes if any. cooking_sessions = ( CookingSession.objects.annotate( step_list=ArrayAgg( models.F( "steps__name", ), distinct=True, ), recipe_list=ArrayAgg(models.F("steps__recipes__name")), ) ) This is how the data looks like [ { 'id': 1, 'name': 'Italian Night', 'step_list': ['Preparation', 'Cooking', 'Serving'], 'recipe_list': ['Tomato Sauce', 'Pasta Dough', 'Spaghetti', 'Tomato Sauce', 'Garlic Bread'] }, ... ] I would like the data to be like { 'id': 1, 'name': 'Italian Night', 'steps': [ { 'step_name': 'Preparation', 'recipes': ['Tomato Sauce', 'Pasta Dough'] }, { 'step_name': 'Cooking', 'recipes': ['Spaghetti', 'Tomato Sauce'] }, { 'step_name': 'Serving', 'recipes': ['Garlic Bread'] } ] } -
Redis command called from Lua script
Django = 5.0.7 Python = 3.12.4 Redis = 7.0.4 django-cacheops = 7.0.2 I am caching data with cacheops using these versions but the response gives the following error: redis.exceptions.ResponseError: Error running script (call to f_0605214935a9ffcd4b9e5779300302540ff08da4): @user_script:36: @user_script: 36: Unknown Redis command called from Lua script What could be the reason? Sample Code: What is causing this problem? -
Django based website having error with Pillow after deployment to Heroku Server while I want to migrate. (DB = Postgresql)
I have deployed my website based on django to Heroku, and changed my database from sqlite3 to postgresql, and when i want to migrate having an error with Pillow. Asking to install Pillow for working With Images. However, I have already installed to my project and added to requirements.txt (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow". While I have checked with heroku run pip list there is no pillow installed, Thus i have several time tried to reinstall and git push. Moreover used heroku bash to install and even restarted it. But no sense, having same issues -
Django-tailwind in production mode?
How to work with django-tailwind in production mode (DEBUG = False). When I turn production mode, all my tailwindcss styles not works. How can I fix this?? I tried python manage.py collectstatic but is doesn't work for me -
Django Tenants does not switch between tenants
I'm using django-tenants lab for developing my project. For each registered user, a tenant is created. Access to the tenant has to be via sub-folder project-url.ru/user/<username>/... instead of sub-domain <username>.project-url.ru/... However, when entering a tenant app, Django does not change the tenant/scheme to the user one, and remains in public. Please help me figure out why Django does not switch between tenants/schemes. setting.py SHARED_APPS = [ 'django_tenants', 'users', ..., ] TENANT_APPS = [ 'products', ... ] INSTALLED_APPS = SHARED_APPS + [app for app in TENANT_APPS if app not in SHARED_APPS] TENANT_MODEL = 'users.Tenant' TENANT_DOMAIN_MODEL = 'users.Domain' PUBLIC_SCHEMA_URLCONF = 'users.users-urls' TENANT_SUBFOLDER_PREFIX = '/user' DATABASE_ROUTERS = ( 'django_tenants.routers.TenantSyncRouter', ) MIDDLEWARE = [ 'django_tenants.middleware.TenantSubfolderMiddleware', ... ] Creating new tenant def create_user_tenant(request): user = UserClass.objects.get(username=request.POST['username']) schema_name = f'{user.username}_schema' try: with transaction.atomic(): tenant = Tenant(schema_name=schema_name, user=user) tenant.save() logger.debug(f'Tenant {tenant} created') except IntegrityError as e: logger.error(f'Error creating tenant or domain for user {user.username}: {e}') except Exception as e: logger.error(f'Unexpected error creating tenant or domain for user {user.username}: {e}') New schema created in DB. I checked. Here is urls settings: users-url.py urlpatterns = [ path('<str:username>/products/', include('products.products-urls', namespace='products')), path('<str:username>/storage/', include('storage.storage-urls', namespace='storage')), ... ] products-urls.py urlpatterns = [ ... path('items-list/', items_list, name='items-list'), ... ] Authorization: def login(request): error_msg = … -
adjust height of the container in html
enter image description hereim trying to adjust the height of the dash container ( white ) but icant seems to figure how to do it , this code and i would appreciate any help : analytics.html : {% extends 'frontend/base.html' %} {% load plotly_dash %} {% block content %} <h2>Reports and Analytics</h2> <div id="dash-container" style="width: 100%; height: 1200px; overflow: hidden;"> <!-- Adjust container height here --> {% plotly_app name="Analytics" %} </div> {% endblock %} analytics_dash.py : import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output import plotly.graph_objects as go from django_plotly_dash import DjangoDash from .models import UserAction from django.db.models import Count # Create a Django Dash application app = DjangoDash('Analytics') def load_data(): actions = UserAction.objects.values('action_type').annotate(count=Count('id')) return [action['action_type'] for action in actions], [action['count'] for action in actions] # Define the layout of the Dash app app.layout = html.Div([ dcc.Graph( id='user-action-graph', style={'width': '100%', 'height': '100%'} # Use 100% to fill container ) ], style={'width': '100%', 'height': '1200px'}) # Adjust to match container size @app.callback( Output('user-action-graph', 'figure'), [Input('user-action-graph', 'id')] ) def update_graph(_): action_types, counts = load_data() fig = go.Figure() if not action_types or not counts: fig.add_annotation(text="No Activity Data Available Yet", showarrow=False) else: fig.add_trace(go.Bar( x=action_types, y=counts, marker=dict(color='royalblue', line=dict(color='black', width=1)) )) … -
it is about django related manager
Django 5.1 What is the meaning of q.choice_set.all() in the polls app? https://docs.djangoproject.com/en/5.1/intro/tutorial04/ from django.db.models import F from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import get_object_or_404, render from django.urls import reverse from .models import Choice, Question def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST["choice"]) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render( request, "polls/detail.html", { "question": question, "error_message": "You didn't select a choice.", }, ) else: selected_choice.votes = F("votes") + 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse("polls:results", args=(question.id,))) -
How do I override django.db.backends logging to work when DEBUG=False?
In django's LOGGING configuration for the builtin django.db.backends it states that: "For performance reasons, SQL logging is only enabled when settings.DEBUG is set to True, regardless of the logging level or handlers that are installed." As a result the following LOGGING configuration, which is correctly set up to issue debug level logs showing DB queries, will NOT output the messages I need: DEBUG = False LOGGING = { "version": 1, "disable_existing_loggers": True, "root": {"handlers": [ "gcp_structured_logging"]}, "handlers": { "gcp_structured_logging": { "level": "DEBUG", "class": "django_gcp.logging.GoogleStructuredLogsHandler", } }, "loggers": { 'django.db.backends': { 'handlers': ["gcp_structured_logging"], 'level': 'DEBUG', 'propagate': True, }, }, } This is preventing me from activating this logging in production, where of course I'm not going to durn on DEBUG=True in my settings but where I need to log exactly this information. Ironically, I need this in order to debug a performance issue (I plan to run this for a short time in production and cat my logs so I can set up a realistic scenario for a load test and some benchmarking on the database). How can I override django's override so that sql queries get logged as I intend? -
Got attribute error when trying creating model
I got this error message Got AttributeError when attempting to get a value for field id on serializer IngredientSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Ingredient instance. Original exception text was: 'Ingredient' object has no attribute 'ingredient'. when trying to save model in DRF. My serializers: from django.db import transaction from rest_framework import serializers from .models import Recipe, Ingredient, RecipeIngredient, Tag class IngredientSerializer(serializers.ModelSerializer): id = serializers.PrimaryKeyRelatedField( queryset=Ingredient.objects.all(), source="ingredient" ) amount = serializers.IntegerField() class Meta: model = RecipeIngredient fields = ["id", "amount"] class CreateRecipeSerializer(serializers.ModelSerializer): ingredients = IngredientSerializer(many=True) tags = serializers.PrimaryKeyRelatedField(queryset=Tag.objects.all(), many=True) image = serializers.ImageField(required=False) name = serializers.CharField(source="recipe_name") class Meta: model = Recipe fields = ["name", "image", "text", "cooking_time", "ingredients", "tags"] def create(self, validated_data): ingredients_data = validated_data.pop("ingredients") tags_data = validated_data.pop("tags") with transaction.atomic(): recipe = Recipe.objects.create(**validated_data) recipe.tags.set(tags_data) recipe_ingredients = [ RecipeIngredient( recipe=recipe, ingredient=ingredient_data["ingredient"], amount=ingredient_data["amount"], ) for ingredient_data in ingredients_data ] RecipeIngredient.objects.bulk_create(recipe_ingredients) return recipe And my models here class Ingredient(models.Model): """Модель ингредиентов.""" ingredient_name = models.CharField( max_length=MAX_LENGTH_200 ) measurement_unit = models.CharField( max_length=MAX_LENGTH_200 ) class Recipe(models.Model): ingredients = models.ManyToManyField( Ingredient, through="RecipeIngredient", related_name="recipes", ) tags = models.ManyToManyField(Tag, related_name="recipes") author = models.ForeignKey( User, on_delete=models.CASCADE, related_name="recipes" ) recipe_name = models.CharField( max_length=MAX_LENGTH_200 ) image = models.ImageField( upload_to="recipes/images/" ) text = … -
Send an http request from django server inside docker container to another server that is located on localhost not inside docker
I have a django project inside docker container. I have several containers for backend, frontend, redis, celery and db thar are served by docker compose. I need to send an http request made by python lib requests to a server that is outside of docker but is started on the same computer (on localhost). This code worked perfectly when django server wasn't inside docker container. There is 500 status code from this function at the moment. How can i do this? Function that should send request: class ConnectLocalHost(APIView): response = requests.post('http://127.0.0.1:9001') return Httpresponse('Message sent', status=status.HTTP_200_OK) docker-compose.yml file: # docker-compose.yml version: "3" volumes: db-data: storage: services: backend: working_dir: /backend build: context: ./backend dockerfile: Dockerfile ports: - "8000:8000" command: bash -c " ./wait-for-postgres.sh database user user123 postgres && python manage.py makemigrations --settings=test_project.prod_settings && python manage.py makemigrations task_manager_app --settings=test_project.prod_settings && python manage.py migrate --settings=test_project.prod_settings && python manage.py migrate task_manager_app --settings=test_project.prod_settings && python manage.py collectstatic --noinput --settings=test_project.prod_settings && python manage.py auto_superuser --settings=test_project.prod_settings && gunicorn test_project.wsgi:application --bind 0.0.0.0:8000" volumes: - storage:/backend/storage/ depends_on: - database - redis environment: REDIS_HOST: redis POSTGRES_USER: user POSTGRES_PASSWORD: user123 POSTGRES_DB: postgres POSTGRES_PORT: 5432 restart: always frontend: working_dir: /frontend build: context: ./frontend dockerfile: Dockerfile command: yarn start ports: - "9000:9000" depends_on: - … -
Django Tastypie API Slow Response Time with Annotate Count and Pagination
I'm working with a Django Tastypie API that processes a large QuerySet. I need to perform an annotate with a Count on a related table, which is also very large. Afterward, I return the response using paginator to handle the pagination. However, the API is taking a significant amount of time to return the results. Here is a simplified version of the annotate that seems to be causing the most delay: .annotate( dynm_calc=Count('devices', filter=Q(devices__groups__id__in=ids_list), distinct=True) ) My main concerns are: QuerySet Evaluation: Is the entire QuerySet being evaluated despite using pagination? If so, could this be the reason for the slow response times? Performance Optimization: How can I optimize this query or improve the performance of the API response? Splitting the QuerySet: Would splitting the QuerySet into smaller parts before applying the annotate be beneficial? If yes, how can this be effectively implemented? Any insights or suggestions on how to tackle this issue would be greatly appreciated. Thank you! -
How to recover Django users password after migrating project to a different server
I migrated my Django project to a different server, so I figured that the database is the most important thing on the server since my code is on GitHub and my media files on S3 bucket. So I made a backup of the database as an SQL dump. I setup my project, restored the database, configure my domain etc. and everything seems like nothing changed (works well). Then I tried to login but it says incorrect password. I'm thinking the way Django hash the password has changed which makes it not match the hash on the database. Every data on the database is up to date. How can I recover the password of the users and what are best practice methods to midrate successfully? I don't have access to the old server anymore. -
Django Allauth: Keycloak Authentication Fails with "Connection Refused" Error
Django Allauth: Keycloak Authentication Fails with "Connection Refused" Error `I'm integrating Keycloak with my Django application using django-allauth for OpenID Connect authentication. I've set up the configuration, but when I click on the "Login with Keycloak" link, I encounter the following error: HTTPConnectionPool(host='localhost', port=8081): Max retries exceeded with url: /realms/customercloud/.well-known/openid-configuration (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f8d322fb100>: Failed to establish a new connection: [Errno 111] Connection refused')) /**login.html **/ <a href="{% provider_login_url 'openid_connect' %}">Login with Keycloak</a> `SOCIALACCOUNT_PROVIDERS = { "openid_connect": { "APP": { "provider_id": "keycloak", "name": "Keycloak", "client_id": "myclient", "secret": "********************", "settings": { 'server_url': 'http://localhost:/realms/customercloud/.well-known/openid-configuration', 'client_id': 'myclient', 'redirect_uri': 'http://localhost:***/', }, } } } ` ' -
Django Rest giving error Exception value: .accepted_renderer not defined in response
I am participating in a course and in it an activity was just to copy and paste the code provided and to use postman, but when I did this I got this error that is in the title, follow the code Minha views.py from django.views.decorators.csrf import csrf_exempt from rest_framework.response import Response from rest_framework import status from .models import Livro from .serializers import LivroSerializer @csrf_exempt def livro_list_create(request): if request.method == 'GET': livros = Livro.objects.all() serializer = LivroSerializer(livros, many=True) return Response(serializer.data) if request.method == 'POST': serializer = LivroSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @csrf_exempt def livro_detail(request, pk): livro = Livro.objects.get(pk=pk) if request.method == 'GET': serializer = LivroSerializer(livro) return Response(serializer.data) if request.method == 'PUT': serializer = LivroSerializer(livro, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) if request.method == 'DELETE': livro.delete() return Response(status=status.HTTP_204_NO_CONTENT) urls.py from django.urls import path from .views import livro_list_create, livro_detail urlpatterns = [ path('livros/', livro_list_create, name='livros-list-create'), path('livros/<int:pk>/', livro_detail, name='livro-detail'), ] serializer.py from rest_framework import serializers from .models import Categoria, Autor, Livro class CategoriaSerializer(serializers.ModelSerializer): class Meta: model = Categoria fields = ['id', 'nome'] class AutorSerializer(serializers.ModelSerializer): class Meta: model = Autor fields = ['id', 'nome'] class LivroSerializer(serializers.ModelSerializer): class Meta: model = Livro fields = ['id', 'titulo', 'autor', 'categoria', … -
downloading large file from S3 is failed with django
I uploaded a large zip file (6.7GB) to S3 via Django code: @retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=3), reraise=True) @aws_exception_handler def upload_file(self, file_path, key, tags=None, extra_args={}): absolute_key = generate_key(key) transfer_config = TransferConfig( multipart_threshold=1024 * 1024 * 4, multipart_chunksize=1024 * 1024 * 16, max_io_queue=1000, max_concurrency=max_workers, use_threads=True ) with open(file_path, 'rb') as data: self.s3_client.upload_fileobj(data, self.bucket_name, absolute_key, Config=transfer_config, ExtraArgs=extra_args) if tags: try: put_object_tagging_kwargs = { 'Key': self._get_absolute_key(key), 'Bucket': self.bucket_name, 'Tagging': { 'TagSet': [ {'Key': tag_key, 'Value': tag_value} for tag_key, tag_value in tags.items() ] } } self.s3_client.put_object_tagging(**put_object_tagging_kwargs) except Exception as ex: raise ex Then I tried to download it through the UI with this code in the server (I tried each of those methods, and the result is the same as I describe below): def check_file_exists_retry_predicate(exception): return False if isinstance(exception, CloudStorageObjectDoesNotExists) else True @retry( retry=retry_if_exception(check_file_exists_retry_predicate), stop=stop_after_attempt(3), wait=wait_exponential(multiplier=3), reraise=True ) @aws_exception_handler def download(self, key, stream=False): obj = self.s3_client.get_object(Bucket=self.bucket_name, Key=self.generate_key(key)) if stream: return obj['Body'] return obj['Body'].read().decode(self._decode_format) @retry( retry=retry_if_exception(check_file_exists_retry_predicate), stop=stop_after_attempt(3), wait=wait_exponential(multiplier=3), reraise=True ) @aws_exception_handler def download_file(self, file_path, key): file_folder_path = os.path.dirname(file_path) if file_folder_path: mkdir_by_path(file_folder_path) with open(file_path, 'wb') as fh: transfer_config = TransferConfig( multipart_threshold=1024 * 1024 * 4, multipart_chunksize=1024 * 1024 * 16, max_io_queue=1000, max_concurrency=max_workers, use_threads=True ) absolute_key = self.generate_key(key) self.s3_client.download_fileobj(self.bucket_name, absolute_key, fh, Config=transfer_config) The download starts but stops suddenly after a … -
Django custom lookup, rhs receives %s only
I want to create a custom icontainsall lookup such that when a user searches for a phrase with a space in it, I want to convert it into a like on all words with AND (so that order of word does not matter). i.e. If user searches for 'egg milk', the predicate becomes name LIKE %egg% AND name LIKE %milk%. This is how my lookup looks: from django.db.models import CharField, Lookup, TextField class CaseInsensitiveContainsAllLookup(Lookup): lookup_name = 'icontainsall' def as_sql(self, compiler, connection): lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection) print(rhs) # shows %s and not 'egg milk' predicate, params = [], [] # escape \ and % rhs_list = rhs.replace('\\', '\\\\').replace('%', '\\%').split(' ') for rhs in rhs_list: params += lhs_params + rhs_params predicate.append(f"LOWER({lhs}) LIKE LOWER({rhs})") return ' AND '.join(predicate), params CharField.register_lookup(CaseInsensitiveContainsAllLookup) TextField.register_lookup(CaseInsensitiveContainsAllLookup) However, rhs receives only %s and not egg milk. How can I go about achieving what I want using a lookup? -
How do I check if a user is not in any group in Django?
I have created some groups in the Django Admin Panel, and users without a group are considered default users. If a user sends a request, how do I check to see if they don't have any groups assigned, similar to request.user.groups.filter(name="Group Name") but reversed? -
I would like to express that query through Django orm
My project have 4 models stock/models.py class StockIndex(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name class Stock(models.Model): code = models.CharField(max_length=24) name = models.CharField(max_length=128) price = models.DecimalField(max_digits=10, decimal_places=2) dividend_rate = models.DecimalField(decimal_places=2, max_digits=4) index = models.ForeignKey(StockIndex, related_name='stocks', on_delete=models.SET_NULL, null=True) def __str__(self): return self.name class StockSet(models.Model): code = models.ForeignKey(Stock, related_name='stock_set', on_delete=models.CASCADE) quantity = models.IntegerField() owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='stock_set', to_field='wallet') def __str__(self): return f'{self.owner} - {self.code}' users/models.py class User(AbstractBaseUser, PermissionsMixin): objects = UserManager() username = models.CharField( max_length=150, unique=True, ) email = models.EmailField(blank=True) is_staff = models.BooleanField( default=False, ) is_active = models.BooleanField( default=True, ) wallet = models.UUIDField(unique=True, default=uuid.uuid4, editable=False) EMAIL_FIELD = "email" USERNAME_FIELD = "username" REQUIRED_FIELDS = ["email"] def __str__(self): return self.username All I want is to get each user's assets. The way to evaluate users' assets is to multiply the StockSet object by the Stock Price and the quantity field and add it all. The database use is mariadb and I know how to get the value from the query. SELECT u.username, u.email, SUM(st.quantity * s.price) AS user_asset FROM stock_stockset st JOIN users_user u ON (st.owner_id = u.wallet) JOIN stock_stock s ON (st.code_id = s.id) GROUP BY u.username; But I don't know how to express the above query in Django ORM. class UserView(ListAPIView): queryset … -
Render Deployment could not install GUNICORN
When render deploys my Django App, it installs everything from the requirements.txt except for gunicorn. I've tried changing the version and also tried other wsgi servers but they are all not working. Can someone help me with this? -
I can't run manage.py server, anyone my fellow programmers? [closed]
It is giving me this error in both vs code and pycharm C:\Program Files\Python312\python.exe: can't open file 'C:\\Users\\HP\\Desktop\\Django\\manage.py': [Errno 2] No such file or directory I ran this command> python manage.py runserver but it issued an error -
'uv' is not recognized as an internal or external command in Windows when trying to create a virtual environment
I'm trying to create a virtual environment in Windows using the uv command, but I keep encountering the following error: 'uv' is not recognized as an internal or external command, operable program or batch file. 1] Installation: I installed uv using pip install uv within my Python environment. I verified the installation by running pip list, and uv appears in the list of installed packages. 2] Path Configuration: I checked my PATH environment variable and confirmed that the Python Scripts directory (where uv.exe should reside) is included. I tried using the full path to the uv executable, but the error persists. 3] Environment Setup: I ensured that my virtual environment was properly created and activated using: python -m venv myenv myenv\Scripts\activate 4] Other Commands: Other Python-related commands like pip, python, etc., work fine without issues. I also tried uninstalling and reinstalling uv but still face the same problem. Why is the uv command not being recognized despite being installed and listed by pip? How can I resolve this issue and successfully create a virtual environment using uv?