Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Display an Image in a Django Form Instead of Showing Its URL
I have a Django application where I want to display the current image in a form when editing an existing product. Currently, It's showing the image URL in the form, but I would like to display the actual image itself instead of URL. If that is not possible then remove that currently URL. I tried by my self but didn't worked -
In Django rest-framework , is it possible to bundle original callback like def copy?
I have a Django framework bundle it works for model. For example, class DrawingViewSet(viewsets.ModelViewSet) def list(self, request): def destroy(self, request, *args, **kwargs): def update(self,request,*args,**kwargs): And each function is called by POST DELETE PATCH GET For example: /api/drawing/13 Then now I want to make the function named copy, such as by calling: /api/drawing/copy/13 Then, with this query: class DrawingViewSet(viewsets.ModelViewSet) def copy(self, request, *args, **kwargs): // do some action. Is it possible to set the original call back on viewsets.ModelViewSet? -
Problem with Django and Python (the current path api/ did not match of these)
I am trying to setup a school journal based on Django and Python, but I can't do it because of a 404 page with problem in title. Python part is backend and Node + Yarn + HTML is consumer (client) part. my views.py from itertools import chain from rest_framework import viewsets, mixins from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import IsAuthenticated from core.models import ( StudyYear, Subject, Mark, StudentClass, Student, School, ) from journal import serializers class BaseJournalAttrViewSet(viewsets.GenericViewSet, mixins.ListModelMixin, mixins.RetrieveModelMixin,): """Base viewset for journal attributes""" authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) class StudyYearViewSet(BaseJournalAttrViewSet): """Manage study year in the database""" queryset = StudyYear.objects.all() serializer_class = serializers.StudyYearSerializer class SubjectViewSet(BaseJournalAttrViewSet): """Manage subjects in the database""" queryset = Subject.objects.all() serializer_class = serializers.SubjectSerializer class MarkViewSet(BaseJournalAttrViewSet, mixins.CreateModelMixin, mixins.UpdateModelMixin): """Manage marks in the database""" queryset = Mark.objects.all() serializer_class = serializers.MarkSerializer def get_queryset(self): """Retrieve all marks by student and subject""" queryset = self.queryset student = self.request.query_params.get('student') subject = self.request.query_params.get('subject') if student: queryset = queryset.filter(student__id=student) if subject: queryset = queryset.filter(subject__id=subject) return queryset class StudentClassViewSet(BaseJournalAttrViewSet): """Manage classes in the database""" queryset = StudentClass.objects.all() serializer_class = serializers.StudentClassSerializer class StudentViewSet(BaseJournalAttrViewSet): """Manage students in the database""" queryset = Student.objects.all() serializer_class = serializers.StudentSerializer def get_queryset(self): """Retrieve students for authenticated user by class""" student_class = self.request.query_params.get('student_class', … -
Tailwind-Django not working in Docker Container
I'm trying to deploy a django application on https://render.com/ using Docker. Unfortunately, the Tailwind classes don't work. In development, they work perfectly. Dockerfile: FROM python:3.12 # Set environment variables ENV PYTHONUNBUFFERED=1 \ PYTHONDONTWRITEBYTECODE=1 # Set the working directory WORKDIR /app # Install Node.js and npm RUN curl -fsSL https://deb.nodesource.com/setup_20.x | bash - && \ apt-get install -y nodejs # Install Poetry RUN pip install poetry # Copy pyproject.toml and poetry.lock COPY pyproject.toml poetry.lock /app/ # Configure Poetry to not use virtualenvs RUN poetry config virtualenvs.create false # Install Python dependencies RUN poetry install --no-dev # Copy the entire project COPY . /app/ # Install Tailwind CSS (requires Node.js and npm) RUN python manage.py tailwind install --no-input # Build Tailwind CSS RUN python manage.py tailwind build --no-input # Collect static files RUN python manage.py collectstatic --no-input # Expose port 8000 EXPOSE 8000 # Start the application with Gunicorn CMD ["gunicorn", "--bind", "0.0.0.0:8000", "config.wsgi:application"] I tried changing the order of the manage.py commands and clearing the cache. But that didn't help. -
How to count model objects in pytest-django?
While I'm perfectly able to get the objects count in python manage.py shell, somehow the test returns always 0. What am I missing? #myapp/test_.py import pytest from .models import Organization @pytest.mark.django_db def test_organization(): assert Organization.objects.count() == 10 $ pytest: E assert 0 == 10 E + where 0 = count() E + where count = <django.db.models.manager.Manager object at 0x734e379b0790>.count E + where <django.db.models.manager.Manager object at 0x734e379b0790> = Organization.objects -
Why is my youtube transcripts API only working in non-prod, but not in prod?
In my non-production environment, I am able to use the transcript youtube API to obtain transcript. In my production environment, after much debugging and logging, I am unable to do this. Here are the logs: 2024-08-20T07:41:29.989747260Z [ANONYMIZED_IP] - - [20/Aug/2024:07:41:29 +0000] "GET /generate/youtubeSummary/ HTTP/1.1" 200 30723 "https://[ANONYMIZED_DOMAIN]/dashboard/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:129.0) Gecko/20100101 Firefox/129.0" 2024-08-20T07:41:45.777775814Z Custom form options: {} 2024-08-20T07:41:45.778110014Z Form data debug: {'grade_level': '', 'video_url': 'https://www.youtube.com/watch?v=[ANONYMIZED_VIDEO_ID]', 'summary_length': None} 2024-08-20T07:41:45.778131714Z INFO 2024-08-20 07:41:45,777 views Generating summary for video URL: https://www.youtube.com/watch?v=[ANONYMIZED_VIDEO_ID] 2024-08-20T07:41:45.781101714Z INFO 2024-08-20 07:41:45,780 views YouTube IP address: [ANONYMIZED_IP] 2024-08-20T07:41:45.979793308Z INFO 2024-08-20 07:41:45,979 views YouTube connection status: 200 2024-08-20T07:41:45.980433708Z INFO 2024-08-20 07:41:45,980 views Attempting to connect to: www.youtube.com 2024-08-20T07:41:45.980820208Z INFO 2024-08-20 07:41:45,980 views Extracted video ID: [ANONYMIZED_VIDEO_ID] 2024-08-20T07:41:46.463787194Z INFO 2024-08-20 07:41:46,463 _universal Request URL: 'https://[ANONYMIZED_DOMAIN]/v2.1/track' 2024-08-20T07:41:46.463807494Z Request method: 'POST' 2024-08-20T07:41:46.463815194Z Request headers: 2024-08-20T07:41:46.463822194Z 'Content-Type': 'application/json' 2024-08-20T07:41:46.463830194Z 'Content-Length': '2373' 2024-08-20T07:41:46.463840094Z 'Accept': 'application/json' 2024-08-20T07:41:46.463847194Z 'x-ms-client-request-id': '[ANONYMIZED_REQUEST_ID]' 2024-08-20T07:41:46.463853694Z 'User-Agent': 'azsdk-python-azuremonitorclient/unknown Python/3.9.19 (Linux-5.15.158.2-1.cm2-x86_64-with-glibc2.28)' 2024-08-20T07:41:46.463863894Z A body is sent with the request 2024-08-20T07:41:46.485539393Z INFO 2024-08-20 07:41:46,485 _universal Response status: 200 2024-08-20T07:41:46.485558093Z Response headers: 2024-08-20T07:41:46.485565793Z 'Transfer-Encoding': 'chunked' 2024-08-20T07:41:46.485600593Z 'Content-Type': 'application/json; charset=utf-8' 2024-08-20T07:41:46.485609693Z 'Server': 'Microsoft-HTTPAPI/2.0' 2024-08-20T07:41:46.485616293Z 'Strict-Transport-Security': 'REDACTED' 2024-08-20T07:41:46.485622793Z 'X-Content-Type-Options': 'REDACTED' 2024-08-20T07:41:46.485629293Z 'Date': 'Tue, 20 Aug 2024 07:41:45 GMT' 2024-08-20T07:41:46.486316593Z INFO 2024-08-20 07:41:46,485 _base Transmission … -
Is it necessary to specify the device type (Android or iOS) when sending push notifications from a Django server through Firebase in a Flutter app?
I am trying to send notifications and I am receiving on Android but on iOS I also uploaded the APNS key also on firebase, when send notifications there is success message on server and no error. I was expecting to find information on whether specifying the device type is necessary for proper notification delivery and if it impacts the notification payload. Specifically, I want to know if failing to specify the device type could result in notifications not being delivered correctly or if Firebase handles this automatically. -
Method GET not allowed [closed]
I am trying to use the second url with the get method and it gives me the error Method "GET" not allowed in Django app. urlpatterns = [ path('book/', include([ path("<str:user_uuid>/<str:image_uuid>", BookView.as_view({"post": "post"}, http_method_names=["post"]), name=ApiName.BOOK_POST.value), path("<str:user_uuid>/<str:book_uuid>", BookView.as_view({"get": "get"}, http_method_names=["get"]), name=ApiName.BOOK_GET.value), path("edit/<str:user_uuid>/<str:book_uuid>", BookView.as_view({"post": "edit"}, http_method_names=["post"]), name=ApiName.BOOK_EDIT.value), path("export/<str:user_uuid>/<str:book_uuid>", BookView.as_view({"post": "export"}, http_method_names=["post"]), name=ApiName.BOOK_EXPORT.value), path("/images/<str:user_uuid>/<str:folder_uuid>", BookView.as_view({"post": "post_images"}, http_method_names=["post"]), name=ApiName.BOOK_IMAGES_POST.value), path("<str:user_uuid>/<str:template_uuid>", BookView.as_view({"get": "get_template"}, http_method_names=["get"]), name=ApiName.BOOK_GET.value), ])), ] Below is my view class BookView(CustomViewSet): parser_classes = [JSONParser, DrfNestedParser] authentication_classes = [BaseApiAuthentication] # permission_classes = [IsAuthenticated, FilePermission] permission_classes = [IsAuthenticated] @method_decorator(logging()) def post(self, request, user_uuid:str, image_uuid:str): return api_response_success() @method_decorator(logging()) def get(self, request, user_uuid:str, book_uuid:str): return api_response_success() -
One to Many relationships in DJANGO - how to generate a row of uniqueness based on 2 compound keys
I am trying to create a relationship based on a compound key based on 2 fields for uniqueness. From my understanding Django uses foreign keys to define one to many relationships? This is my scenario: I have 2 tables Table1 Table2 I want to write code to generate rows for Table3 records which iterate through Table 2 and generate the list below and generate the compound key combination: I want to create this relationship using models.py, however, every time I save a record the ID in table 2 increments see example of Table 2 How can I force this behaviour? This is the code I have used Table1 is Parish i derive the value for parish.id Table2 is CheckList.object.all() Table3 is All_Inpection def form_valid(self, form): form.instance.author = self.request.user parish = form.save(commit=False) parish.user_id = self.request.user.id parish.save() entry = Company.objects.get(pk=parish.id) Checklists = Checklist.objects.all() for rec in Checklists: new_rec=All_Inspection(str_status=rec.str_status, str_comment='',company_id=entry) new_rec.save() return super().form_valid(form) -
Cannot Install Django-Q on Django 5
We have problem install Django-Q on DJango 5 when run python manage.py migrate it was error as message below pip install django-q INSTALLED_APPS = [ ... 'django_q', ] python manage.py migrate Q_CLUSTER = { 'name': 'Django Q', 'workers': 16, 'recycle': 500, 'timeout': 1200, 'compress': True, 'save_limit': 250, 'queue_limit': 1000, 'cpu_affinity': 1, 'label': 'Django Q', } Error message: File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed File "/Users/imac/Desktop/Project/Test/myenv/lib/python3.12/site-packages/django_q/apps.py", line 3, in <module> from django_q.conf import Conf File "/Users/imac/Desktop/Project/Test/myenv/lib/python3.12/site-packages/django_q/conf.py", line 8, in <module> import pkg_resources ModuleNotFoundError: No module named 'pkg_resources' How to Fix the issue ? -
Django Q (scheduler) is not properly working in python 3
Django Q (scheduler) is not properly working in python 3. it is alway stop one time a week but it is working fine on python 2. no error log found in python 3. How to fix that issue ? https://django-q.readthedocs.io/en/latest/ Q_CLUSTER = { 'name': 'Django Q', 'workers': 16, 'recycle': 500, 'timeout': 1200, 'compress': True, 'save_limit': 250, 'queue_limit': 1000, 'cpu_affinity': 1, 'label': 'Django Q', } getting the solution and track error log -
Input fields not displaying- Django inlineformsets
I am using an inline formset so the user can upload multiple images and also I can receive related information together e.g. the ingredient, quantity and unit. This was previously working but my input fields have disappeared- the titles still appear but I can't actually input the textfields so then the form won't save properly. Here is my forms.py class ImageForm(forms.ModelForm): class Meta: model = Image fields = '__all__' class VariantIngredientForm(forms.ModelForm): class Meta: model = VariantIngredient fields = '__all__' widgets = { 'ingredient': forms.TextInput( attrs={ 'class': 'form-control' } ), 'quantity': forms.NumberInput( attrs={ 'class': 'form-control' } ), 'unit': forms.MultipleChoiceField( choices = UNIT_CHOICES ), } This is my models.py class Image(models.Model): recipe = models.ForeignKey( Recipe, on_delete=models.CASCADE, null=True ) image = models.ImageField(blank=True, upload_to='images') def __str__(self): return self.recipe.title if self.recipe else "No Recipe" class VariantIngredient(models.Model): recipe = models.ForeignKey( Recipe, on_delete=models.CASCADE ) ingredient = models.CharField(max_length=100) quantity = models.PositiveIntegerField(default=1) unit = models.CharField(max_length=10, choices=unit_choice, default='g') def __str__(self): return self.recipe.title if self.recipe else "No Recipe" This is the relevant section of my template: <!-- inline form for Images Start--> {% with named_formsets.images as formset %} {{ formset.management_form|crispy }} <script type="text/html" id="images-template"> // id="inlineformsetname-template" <tr id="images-__prefix__" class= hide_all> // id="inlineformsetname-__prefix__" {% for fields in formset.empty_form.hidden_fields %} {{ fields }} … -
CSRF Token doesn't work in production environment
My environment: Django backend deployed on Elastic Beanstalk behind a application load balancer that terminates ssl. The flow is: my website is served on S3 and cloudfront on domain: https://www.test.app.mydomain.com/. This sends request to backend which has domain: https://api.test.mydomain.com/. The request grabs the csrftoken in browser cookies and includes it in the headers. CSRF tokens work locally, but it doesn't work in my production environment. Most importantly, there is no csrftoken in the browser cookies in the production environment. These are my settings that are relevant: MIDDLEWARE = [ # keep on top 'corsheaders.middleware.CorsMiddleware', # rest of the middleware "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] SESSION_ENGINE = "django.contrib.sessions.backends.signed_cookies" SESSION_COOKIE_AGE = 7200 # 2 hours SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True CSRF_TRUSTED_ORIGINS = ['http://localhost:3000', 'https://www.test.app.mydomain.com', 'https://test.app.mydomain.com'] SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') USE_X_FORWARDED_HOST = True CORS_ALLOWED_ORIGINS = ['http://localhost:3000', 'https://www.test.app.mydomain.com', 'https://test.app.mydomain.com'] CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_HEADERS = list(default_headers) + [ 'Tab-ID', ] -
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?