Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Raise message from a class in models.py in django
I have models class for Inventory Transfers or Issues Details. In the save method, i am accessing current stock level in a different model class for WarehouseStockStatus. I wish to message to the user from models.py if transferred or issued quantity exceeds current inventory levels. I am using django admin screens only. Print method will not work. Raise Validation error doesn't work. Also Messages will not work as it works only in views and templates where you have Request object. Any suggestions on how to proceed ? I expect to print the message to the user. -
Why are my ECS tasks pausing for six hours on startup?
I have a Fargate ECS task that runs a Django app via gunicorn. That task successfully started a few weeks ago and had no issues. It was then replaced by routine AWS maintenance/updates. The replacement task started successfully, but it paused during the execution of the entry point script for longer than the load balancer healthcheck grace period. The task of course failed the health check and that caused ECS to again stop and replace the task. This then happened endlessly, with each replacement task having the same issue. There have been no code changes involved in the Docker image used for the task. I obviously expected no change to the ECS task and that it would run as it did before. After implementing the ECS task deployment circuit breaker to stop the endless task replacement cycle, I left the paused (but running) ECS task alone for a while. I realized from the Cloudwatch logs that the task pauses for exactly six hours each time while in the middle of running the entry point script. Here's the entry point script: set -euo pipefail cd /home/viewer/projects/server || exit export DJANGO_SETTINGS_MODULE=viewer_server.settings export PYTHONPATH="/home/viewer/projects/server/" echo "DJANGO_SETTINGS_MODULE and PYTHONPATH set." python manage.py makemigrations python … -
Create CSV file from converting Json Output into CSV either using Pandas or CSV/Json Library in Django
I am struggling to figure out how to get my already made Json output and also create a csv file from that output. For more clarification, I have created a json file by using write, but I am unsure on how to also create a CSV file during the same process. Maybe I am just not inputting the CSV code in the correct area, or if Django needs some other form of method to process that request. utils.py import json import os import pandas as pd from django.utils import timezone from django.http import HttpResponse from django.db.models import Q from api.models import BlockedList def get_ip_list_json() -> dict: json_response = { "version": "", "description": "", "objects": [ { "name": "", "id": "", "description": "", "ranges": ["2.2.2.2"], }, ], } group_map = {} for ip in BlockedList.objects.filter( Q(end_date__isnull=True) | Q(end_date__gte=timezone.now()) ).select_related("group"): group_id = str(ip.group.id) if group_id not in group_map: group_map[group_id] = { "name": ip.group.name, "id": ip.group.group_id, "description": ip.group.description, "ranges": [], } group_map[group_id]["ranges"].append(ip.address) json_response["objects"] = list(group_map.values()) return json_response def create_ip_file(): try: base_dir = "C://Users/Steven/Desktop" filename = "blocklist.json" full_path = os.path.join(base_dir, filename) with open(full_path, "w") as f: f.write(json.dumps(get_ip_list_json(), indent=4)) except Exception as e: print(e) That is my above code where I create my Json output … -
redis and celery tasks works fine without docker, but using docker the tasks status is always in pending state in my django app
I am trying to write a background task to count the total number of posts. It works fine when I start redis server and celery without using docker but using docker, the tasks state is always pending. To confirm if the task is working, I tried to do it without using docker and it worked fine but as soon I can run it using docker the task stops working. Below is the code I tried: Dockerfile FROM python:3.8-slim-buster ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt requirements.txt RUN pip3 install -r requirements.txt RUN pip3 install ipdb COPY . /code/ docker-compose.yml version: '3' services: db: image: postgres:13 volumes: - postgres_data:/var/lib/postgresql/data environment: POSTGRES_DB: myproject POSTGRES_USER: myprojectuser POSTGRES_PASSWORD: password networks: - mynetwork web: build: . command: bash -c " python manage.py migrate && python manage.py runserver 0.0.0.0:8000 " volumes: - .:/code ports: - "8000:8000" depends_on: - db - es - redis - celery environment: - DATABASE_URL=postgres://myprojectuser:password@db:5432/myproject stdin_open: true # Keep stdin open tty: true # Enable TTY networks: - mynetwork es: image: docker.elastic.co/elasticsearch/elasticsearch:8.13.0 volumes: - esdata01:/usr/share/elasticsearch/data ports: - 9200:9200 environment: - discovery.type=single-node - xpack.security.enabled=false networks: - mynetwork redis: image: redis:latest container_name: rd01 command: redis-server ports: - '6379:6379' networks: - mynetwork celery: build: . command: celery … -
What I can do to get the approximated price for the cloud service
I have an application to run in a server in a specific domain and I want to know how much I'm gonna pay each month in Heroku. It's a website running in python/django to solve the schedulling problem. My user will log-in and fill the form and run the solution. After running the solution they will get the results via a specific page. Is this enough information so I can get an approx. price to pay? If not, what other information I need to reveal in order to get this estimate? I tried to get the estimate using the Heroku calculator, but I got an estimate of $250 dollars per month. I included in the calculator the advanced plan with performance M. I'm not sure if that is all or not. -
Django cannot be recognized
I am doing a coding course where I'll be learning all about Django. From this, it is correct to assume that I am new to everything Django. In the course, I am at the point where I must install Django. The instructor said to use my computer's terminal to install Django. He also said to install Django 2.0.2, as that is the version he would be using. The command he had me use was pip3 install django==2.0.2. Everything installed normally, but when I tried to open Django with Django-admin, I was met with this error: django: The term 'django' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. I tried uninstalling Django, then installing the latest version using: pip install Django, but even though everything installed perfectly, I am still met with the same error when I try to start a new project with Django. I was also given alternate commands that the Bing AI Copilot gave me, such as: python -m Django startproject first_project, but that produced the same type of error. … -
uWSGI: trying to figure out why my application goes frequently timeout
I'm using uWSGI into a Docker container to serve a Django application which is encountering serious timeouts problems almost once per day. For this reason, I am debugging my uWSGI settings, expecially the cheaper settings. Today I had timeouts errors at about 06:30 UTC time, and these are the uWSGI logs in the meantime: 2024-06-12 06:03:02 - [busyness] 1s average busyness is at 100% but we already started maximum number of workers available with current limits (8) 2024-06-12 06:03:03 - [busyness] 1s average busyness is at 100% but we already started maximum number of workers available with current limits (8) 2024-06-12 06:03:04 - [busyness] 1s average busyness is at 100% but we already started maximum number of workers available with current limits (8) 2024-06-12 06:03:05 - [busyness] backlog was non-zero for 60 second(s), spawning new worker(s) 2024-06-12 06:03:05 - [busyness] 18 requests in listen queue but we are already started maximum number of workers (8) 2024-06-12 06:03:06 - [busyness] 1s average busyness is at 100% but we already started maximum number of workers available with current limits (8) 2024-06-12 06:03:07 - [busyness] 1s average busyness is at 100% but we already started maximum number of workers available with current limits … -
How to retireve details by related onetoonefield in Djang Rest Framework?
Hello consider the following simple scenario: class User(models.Model): email = ... fname = ... lname = ... class UserPreferences(models.Model): user = models.OneToOneField(User, to_field="email", ...) preferences = ... Now the UserPreferences table in the db contains id, preferences, user_id. I want to get the preferences of a user by email. I want to use RetrieveAPIView. How to do this? What is the role of to_field if it stores the id of user anyway? I tried the following: class UserPreferencesRetrieveView(generics.RetrieveAPIView): serializer_class = UserPreferencesSerializer queryset = UserPreferences.objects.all() lookup_field = "email" I got the error: Cannot resolve keyword 'email' into field. Choices are: id, preferences, user, user_id -
Storing clients card Django
I need to store customer loyalty cards. It should be flexible. I have several variants of cards with different discount systems. For example, the card by amount of purchases - > $100 - 5%, > $1000 - 10%, etc. Or by amount of visits - > 10 - 3%, 100 - 10%, etc. Furthermore, it should store the different image for different types of cards and sales amount, for example 5% - silver colour, 10% - gold, etc. I came up with the idea of storing in in database as JSON. Visits for example: schema = {1: {'discount': 5%, image: '....', 'style': {'background': ..., 'foreground': ...}, 2: {'discount': 10%, image: '....', 'style': {'background': ..., 'foreground': ...}, 3: {'discount': 15%, image: '....', 'style': {'background': ..., 'foreground': ...}, } class ABSCard(models.Model): title = field work_place = field .... class Discount(models.Model): type = .... schema = JSONField abscard_id = ABSCard But I'm not sure that storing JSON in PostgreSQL is the best way. -
Prevent async task from being executed before the rest of the code on Django
Please help me here. This is my django admin class: My problem is, the check_sync_available validation is not working properly because the async task sync_development (redis/celery) is being executed BEFORE the requests.get according to the logs, how can I prevent that? I've tried to use transactions.oncommit and lots of other things and nothing works. class CourseAdmin(nested_admin.NestedModelAdmin): class Meta: model = Course fields = '__all__' actions = ["sync_course_development"] def sync_course_development(self, modeladmin, request, queryset): api_url = f'https://lalala.lalala.la/check_sync_available/' response = requests.get(api_url, headers={'Content-Type': 'application/json'}) if response.status_code != 200: modeladmin.message_user(request, f'A sync is already in progress, try again later.', messages.ERROR) return None else: print(f"Sync available: {response.status_code}") for course in queryset: sync_development.apply_async([course.id]) modeladmin.message_user(request, f'Courses syncing in background. Please reload the page in a while.', messages.SUCCESS) This is the log so you can see what I'm talking about. Jun 12 18:31:59 ip-xxx-xx-xx-xx celery_worker: [2024-06-12 18:31:59,694: WARNING/ForkPoolWorker-7] Point 765/3802 - Percentage: 19.89245930284848 Jun 12 18:31:59 ip-xxx-xx-xx-xx celery_worker: [2024-06-12 18:31:59,696: WARNING/ForkPoolWorker-7] Point 766/3802 - Percentage: 19.91905538924079 Jun 12 18:31:59 ip-xxx-xx-xx-xx celery_worker: [2024-06-12 18:31:59,698: WARNING/ForkPoolWorker-7] Point 767/3802 - Percentage: 19.945522992123962 Jun 12 18:31:59 ip-xxx-xx-xx-xx web: [2024-06-12 18:31:59 +0000] [5952] [INFO] Booting worker with pid: 5952 Jun 12 18:32:01 ip-xxx-xx-xx-xx web: [2024-06-12 18:32:01 +0000] [5906] [INFO] Autorestarting worker after current request. … -
Centrifugo Django. disconnect after handling command reason="bad request"
I am trying to follow this tutorial: But after following all of the steps I do not see any messages and have this in my centrifugo logs: 2024-06-12 20:42:18 [INF] disconnect after handling command client=5bf22df5-8051-463b-9c41-4a6e9d92865a command=id:6 reason="bad request" user= It seems that it occurs when centrifuge.connect() is executed (in chat.templates.chat.rooms.html file). Here are logs from NGINX container: 192.168.65.1 - - [12/Jun/2024:17:44:26 +0000] "GET /connection/websocket HTTP/1.1" 101 15 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36" 192.168.65.1 - - [12/Jun/2024:17:44:30 +0000] "GET /connection/websocket HTTP/1.1" 101 15 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36" 192.168.65.1 - - [12/Jun/2024:17:44:42 +0000] "GET /connection/websocket HTTP/1.1" 101 15 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36" 192.168.65.1 - - [12/Jun/2024:17:44:44 +0000] "GET /connection/websocket HTTP/1.1" 101 15 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36" 192.168.65.1 - - [12/Jun/2024:17:44:58 +0000] "GET /connection/websocket HTTP/1.1" 101 15 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36" 192.168.65.1 - - [12/Jun/2024:17:45:01 +0000] "GET /connection/websocket HTTP/1.1" 101 15 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 … -
window.addEventListener('scroll', function() {
I'm working on the front end through Django WebFramework and PyCham, but infinite scrolls are not properly applied It is a page that fetches and displays public data APIs. Even if the scroll is stuck to the floor, more content does not come out. my html templates {% extends 'base.html' %} {% load static %} {% block content %} <section> <div class="mainpage_content_container"> <div class="section_wrap"> <div class="slick_container"> <div><img src="{% static 'img/gucciSeoul.jpeg' %}" alt=""></div> <div><img src="{% static 'img/korean_mood1.jpeg' %}" alt=""></div> <div><img src="{% static 'img/white_cow.jpeg' %}" alt=""></div> <div><img src="{% static 'img/colorful.jpeg' %}" alt=""></div> <div><img src="{% static 'img/6.25.jpeg' %}" alt=""></div> <div><img src="{% static 'img/seoulcity.jpeg' %}" alt=""></div> </div> </div> <div class="content_container"> <div class="content_wrap"> <ul> {% for image_info in image_info_list %} <li> <div class="img_wrap"> <img src="{{ image_info.file_url }}" alt="{{ image_info.art_name }}" style="max-width: 300px; min-height: 350px"> <div class="img_info"> <p><strong>작품명 :</strong>{{ image_info.art_name }}</p> <p><strong>일련번호 :</strong>{{ image_info.artCd }}</p> <p><strong>작품가격 :</strong>{{ image_info.price }}</p> </div> </div> </li> {% endfor %} </ul> {% if art_list %} <h2>검색 결과</h2> <ul> {% for art in art_list %} <li> <p>작품 번호: {{ image_info.artCd }}</p> <p>작품명: {{ image_info.art_name }}</p> <p>이미지: {% if art.image_url %} <img src="{{ art.image_url }}" alt="작품 이미지"> {% else %} 이미지 없음 {% endif %} </p> </li> {% endfor %} </ul> {% else … -
Django docker error with Postgres django.core.exceptions.ImproperlyConfigured
Good day. I'm having problems comunicating django app (local) and postgres db (docker ) The db work fine with adminer. But when I try the credentials that I use in adminer... Boom! ...env\Lib\site-packages\django\db\backends\postgresql\base.py", line 29, in raise ImproperlyConfigured("Error loading psycopg2 or psycopg module") django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 or psycopg module SETTINGS DATABASES = { 'default': { 'ENGINE': os.getenv("DB_ENGINE"), 'NAME': os.getenv("DB_NAME"), 'USER': os.getenv("DB_USER"), 'PASSWORD': os.getenv("DB_PASSWORD"), 'HOST': os.getenv("DB_HOST"), 'PORT': os.getenv("DB_PORT") }, 'kettle': { 'ENGINE': os.getenv("DB_ENGINE"), 'NAME': os.getenv("DB_NAME_KETTLE"), 'USER': os.getenv("DB_USER"), 'PASSWORD': os.getenv("DB_PASSWORD"), 'HOST': os.getenv("DB_HOST"), 'PORT': os.getenv("DB_PORT") } } ENV DB_ENGINE='django.db.backends.postgresql' DB_NAME='database' DB_USER='postgres' DB_PASSWORD='1234' DB_HOST='db' DB_PORT='5432' DB_NAME_KETTLE='kettle' ADMINER_PORT=8080 VIRTUAL ENV asgiref==3.8.1 certifi==2024.6.2 cffi==1.16.0 charset-normalizer==3.3.2 cryptography==42.0.8 Django==4.2.3 django-cors-headers==4.2.0 djangorestframework==3.14.0 idna==3.7 psycopg==3.1.19 psycopg2==2.9.6 psycopg2-binary==2.9.6 pycparser==2.22 PyJWT==2.3.0 python-dateutil==2.9.0.post0 python-dotenv==1.0.0 pytz==2024.1 requests==2.31.0 six==1.16.0 sqlparse==0.5.0 typing_extensions==4.12.2 tzdata==2024.1 urllib3==2.2.1 and in my docker , postgres is in the port 5432:5432 -
Objects are displayed below the form field drowdown
I have created a form which is creating a new object of a model in which there is one field which is dropdown as it is a foreign key in model but the objects are also displayed below the field along with the dropdown. Model: class Vehicle(models.Model): type = models.ForeignKey(VehicleType, on_delete=models.CASCADE) number = models.CharField(max_length=10) View: def request_cabbie_upgrade(request): if request.method == 'POST': vehicle_form = VehicleForm(request.POST) if vehicle_form.is_valid(): vehicle = vehicle_form.save(commit=False) vehicle.save() cabbie_request = CabbieRequest(user=request.user, vehicle=vehicle) cabbie_request.save() return redirect('PassengerDashboard') else: vehicle_form = VehicleForm() return render(request, 'users/cabbie_request.html', {'vehicle_form': vehicle_form, 'user': request.user}) Form: class VehicleForm(forms.ModelForm): type = forms.ModelChoiceField(queryset=VehicleType.objects.all(), empty_label="Vehicle Type") class Meta: model = Vehicle fields = ['type', 'number'] Template: {% extends "base.html" %} {% block title %} <title>Cabbie Dashboard</title> {% endblock title %} {% block body %} <div class="container mt-5 pt-5 cabbie-dashboard-container"> <div class="row"> <div class="col-md-12"> <h2>Cabbie Information</h2> <div class="card"> <div class="card-body"> <p><strong>Username:</strong> {{ cabbie.username }}</p> <p><strong>First Name:</strong> {{ cabbie.first_name }}</p> <p><strong>Last Name:</strong> {{ cabbie.last_name }}</p> <p><strong>Email:</strong> {{ cabbie.email }}</p> <p><strong>Phone:</strong> {{ cabbie.phone }}</p> </div> </div> </div> <div class="col-md-12 mt-4"> <h2>Request Cabbie Upgrade</h2> <form method="post"> {% csrf_token %} <div class="form-group"> <label for="id_type">Vehicle Type:</label> {{ vehicle_form.type }} </div> <div class="form-group"> <label for="id_number">Vehicle Number:</label> {{ vehicle_form.number }} </div> <button type="submit" class="btn btn-primary">Submit Request</button> </form> </div> … -
How to Make Django Model Choice Field Accept Multiple Criteria
With a model defined as such class Product(models.Model): code = models.CharField(max_length=20, unique=True) name = models.CharField(max_length=100) # intended to be left as NOT unique I would like to pick a product by either its code or its name. For example, if Product 1's code is SUS304 and name Stainless Steel 304, type SUS304 or Stainless Steel 304 in the form should both select this product. I try to use a union queryset as source queryset, but Django complains that .filter after .union is not supported. class OrderForm(forms.ModelForm): codes = Product.objects.annotate(full=F('code')) names = Product.objects.annotate(full=F('name')) product = forms.ModelChoiceField(codes.union(names), to_field_name='full') class Meta: # Order is another model that have a ForeignKey to Product model = Order fields = ['product'] How can I achieve this (especially in Django's way)? PS1. It is possible that multiple products share the same name, or one product's name is another's code. In such case, I would expect a ValidationError. PS2. Despite the length limit, there is no effective way to determine if a given string is a code or a name. SUS304 could also be a product's name. -
Does wagtail support dynamical definition of Search and Social Previews or Slug?
Is there any system in wagtail where you can dynamically define Search and Social Previews or Slug. so for example that it goes details/1/ where one would represent certain ID. so it would be details/{id} I wonder is this possible. If this is not possible is it possible somehow to define query in route? Thanks in advance guys. Currently I am solving this problem with keeping in session my id and using it later in my blocks.py but I would like for the Id to be vissible in the route. Example: https://www.my-website.com/orders/2/ Where 2 would be dynamically forwarded. -
Should I subclass my django model or not?
I'm creating a simple forum app in order to learn django. The idea is to create as much a full featured forum as I can over time, but for now this is what I have: class Post(models.Model): post_body = models.TextField(max_length=2000) publish_date = models.DateTimeField("date posted") author = models.TextField(max_length=200) # link to User model later class Meta: abstract = True # Post that starts a thread class ThreadPost(Post): post_title = models.Charfield(200) is_solved = models.BooleanField("is_issue_solved", default=False) class ReplyPost(Post): is_solution = models.BooleanField("is_this_the_solution", default=False) thread_post = models.ForeignKey(ThreadPost, on_delete=models.CASCADE) I'm unsure if this this is overdoing it a bit. ThreadPost and ReplyPost are so similar. Should I instead just create two separate classes which are unrelated through inheritance? Should I just have one Post class and just make the post_title optional when it's a reply? I guess the singular Post class would have to have a recursive relation too in that case (0 to N). Also, in future I want to add other features like reactions (e.g. thumbs up/down, laugh etc.), ability to report a post etc. Which I think could be a seperate model that links Post and User and would have its own fields. I wonder what approach would be best to keep the … -
Invalid model reference ‘my.guru.Comment_ref_comments’. String model references must be of the form ‘app_label.ModelName’
Ive got this problem here. I will paste in my code too. After looking through the internet, I found this error, but only for custom User models. In my example I have a simple Comment model: class Comment(models.Model): author = models.ForeignKey(User, default=1, on_delete=models.SET_DEFAULT) published = models.DateField(auto_now_add=True) hidden = models.BooleanField(default=False) content = models.TextField() ref_comments = models.ManyToManyField('self', blank=True, related_name="comment_relation", default=None) parent = models.ForeignKey('self', default=None, null=True, on_delete=models.SET_DEFAULT) level = models.SmallIntegerField(default=1) no_of_reactions = models.IntegerField(default=0) def delete_tread(self): self.delete() orphans = Comment.objects.filter(parent=None) for com in orphans: if not com.get_blog() and not com.get_vlog() and not com.get_popPost() and not com.get_article(): com.delete() def get_article(self): if self.article_relation.all(): return self.article_relation.all()[0] else: return None def get_blog(self): if self.blog_relation.all(): return self.blog_relation.all()[0] else: return None def get_vlog(self): if self.vlog_relation.all(): return self.vlog_relation.all()[0] else: return None def get_popPost(self): if self.pop_relation.all(): return self.pop_relation.all()[0] else: return None def __str__(self): return self.content Error message: File “/workspaces/coachGu-live/guru/models.py”, line 100, in class Comment(models.Model): File “/usr/local/python/3.10.13/lib/python3.10/site-packages/django/db/models/base.py”, line 160, in new new_class.add_to_class(obj_name, obj) File “/usr/local/python/3.10.13/lib/python3.10/site-packages/django/db/models/base.py”, line 325, in add_to_class value.contribute_to_class(cls, name) File “/usr/local/python/3.10.13/lib/python3.10/site-packages/django/db/models/fields/related.py”, line 1585, in contribute_to_class self.remote_field.through = create_many_to_many_intermediary_model(self, cls) File “/usr/local/python/3.10.13/lib/python3.10/site-packages/django/db/models/fields/related.py”, line 1052, in create_many_to_many_intermediary_model lazy_related_operation(set_managed, klass, to_model, name) File “/usr/local/python/3.10.13/lib/python3.10/site-packages/django/db/models/fields/related.py”, line 80, in lazy_related_operation return apps.lazy_model_operation(partial(function, **kwargs), *model_keys) File “/usr/local/python/3.10.13/lib/python3.10/site-packages/django/db/models/fields/related.py”, line 78, in model_keys = (make_model_tuple(m) for m in models) … -
Django many to many nested serializer
Hi i have a class widgets which can have multiple cameras and multiple analysis related to it. i want to return the cameras and widgets related as an object because if we delete the cameras the i want to get [{camera: null}] class CameraWidgetSerializer(serializers.ModelSerializer): class Meta: model = CameraWidget fields = ('camera',) class AnalysisWidgetSerializer(serializers.ModelSerializer): class Meta: model = AnalysisWidget fields = ('analysis',) class WidgetSerializer(ModelSerializerWithValidation): cameras = CameraWidgetSerializer(many=True) analyses = AnalysisWidgetSerializer(many=True) these are the simplified modals class CameraWidget(models.Model): """ Association class used to link between cameras and widget """ camera = models.ForeignKey( Camera, models.SET_NULL, help_text='The camera related to the widget', related_name='cameras_widgets', blank=False, null=True ) widget = models.ForeignKey( Widget, models.CASCADE, help_text='The widget containing the camera', related_name='cameras_widgets', blank=True, null=True ) class Widget(models.Model): analyses = models.ManyToManyField(Analysis, through='AnalysisWidget') cameras = models.ManyToManyField(Camera, through="CameraWidget") i managed to do this by seperating input and output this way cameras_ids = serializers.PrimaryKeyRelatedField(queryset=Camera.objects.all(), many=True, write_only=True) cameras = serializers.PrimaryKeyRelatedField(queryset=Camera.objects.all(), many=True, write_only=True) but i want the get and post to have the same structure, meaning "cameras" in both requests body while keeping DRF validation for these fields -
Django cache requests and only allow refresh daily
So I have this Admin dashboard for an e-commerce website where there are all kinds of statistics about sales and customers. Now this data is hosted in AWS RDS and the dashboard is made with django templates. So logically whenever the admin goes to this page it gets refreshed and it queries the AWS RDS. Now this data does not change in real-time the dashboard data gets updated daily in the database (this is done with dbt so this has nothing to do with django) so it doesnt make sense to run these queries multiple times a day because the data will not change on the dashboard. So what I need is something to cache the data once the admin goes to this dashboard and then invalidate the cache at say midnight. Anyone has done something like this or has any advice on how to create something like this? Thanks in advance for all replies! -
vscode run django test with database running in docker container on host
My settings.json { "python.linting.pylintEnabled": true, "python.linting.enabled": true, "python.testing.unittestArgs": [ "-v", "-s", ".", "-p", "test_*.py" ], "python.testing.pytestEnabled": false, "python.testing.unittestEnabled": true, "[python]": { "editor.defaultFormatter": "ms-python.autopep8", "editor.formatOnSave": true, "editor.codeActionsOnSave": { "source.organizeImports": "explicit", "source.fixAll": "explicit" }, "editor.rulers": [ 80, ] }, "black-formatter.args": [ "--line-length", "80" ], "python.analysis.autoImportCompletions": true, "python.analysis.typeCheckingMode": "off", "python.envFile": "${workspaceFolder}/.vscode/.env", // "isort.args":["--profile", "black"] } I see all tests in Test explorer. I have test postgres database running in a docker container outside of vscode in network host mode on ubuntu. I have .vscode/.env file with all env variables needed to run a test case. When I run a test from test_explorer I get error django.db.utils.IntegrityError: duplicate key value violates unique constraint "user_category_name_key" DETAIL: Key (name)=(Admin) already exists. If I try running the same test case through Run and debug using following launch.json file - it works successfully { "version": "0.2.0", "configurations": [ { "name": "Django test", "type": "debugpy", "request": "launch", "program": "${workspaceFolder}/manage.py", "args": [ "test", "app1.tests.test1.test_abc", "--keepdb" ], "django": true, "envFile": "${workspaceFolder}/.vscode/.env", "console": "integratedTerminal" } ] -
Django - NoReverseMatch at /carro/
I'm learning how to make a basic e-commerce site, but I have this problem that appears when I add a product in the cart. I tried everything (I think) but still can't make this cart to work. It seems that the argument for "id_producto" is not reaching to nowhere. URLS.PY from django.conf import settings from django.urls import path from .import views app_name = "carro" urlpatterns = [ path('', views.detalle_carro, name='detalle_carro'), path('add/<str:id_producto>/', views.carro_mas, name='carro_mas'), path('remove/<str:id_producto>/', views.carro_menos, name='remover_carro'), ] VIEWS.PY from django.shortcuts import render, redirect, get_object_or_404 from django.contrib import messages from django.views.decorators.http import require_POST from gestionPedidos.models import Producto from .carro import Carro from .forms import anadirProductoForm #aqui va el form cupon @require_POST def carro_mas(request, id_producto): carro = Carro(request) producto = get_object_or_404(Producto, id_producto=id_producto) form = anadirProductoForm(request.POST) if form.is_valid(): cd = form.cleaned_data carro.anadir(producto = producto, cantidad=cd['cantidad'], update_cantidad=cd['update']) messages.success(request, "vamooo") return redirect('carro:detalle_carro') def carro_menos(request, id_producto): carro = Carro(request) producto = get_object_or_404(Producto, id=id_producto) carro.remover(producto) return redirect('carro:detalle_carro') def detalle_carro(request): carro = Carro(request) for item in carro: item['update_cantidad_form'] = anadirProductoForm(initial = { 'cantidad' : item['cantidad'], 'update' : True }) return render(request, 'detalle_carro.html', {'carro' : carro}) my template {% extends 'base.html' %} {% load static %} {% block title %}Mi carrito de compras!{% endblock %} {% block first_content %} … -
How to know user is online/offline with django channels?
With Django Channels, can you track which users are online or offline throughout your website? Should every page have a websocket connection? And when a user is online/offline, how can I show the user online/offline in real time. I have no idea. I only do group chats online users but cant do user online/offline in full website -
systemctl and uwsgi issue for remote django app
when I run uwsgi manually with uwsgi --ini uwsgi.ini command, it runs properly, but when I run sudo systemctl start uwsgi it will run properly (i.e., journalctl -b -u uwsgi or sudo systemctl status uwsgi won't show any errors) but I will get 500 error for all API calls. The errors do not happen when I run the server manually. And the uwsgi.service file worked fine until this morning so I don't know what is happening all of a sudden. help me please? The remote server is an ubuntu machine. I tried relaxing the permissions of related files/directories etc, doesn't work. When I check the uwsgi log it says that django app was not found, but I'm pretty sure the env files/variables are correctly configured. It works fine when I run uwsgi manually too. Set PythonHome to /home/ubuntu/venv3.9 *** Python threads support is disabled. You can enable it with --enable-threads *** Python main interpreter initialized at 0x557b93f7ebf0 your server socket listen backlog is limited to 100 connections your mercy for graceful operations on workers is 60 seconds mapped 145840 bytes (142 KB) for 1 cores *** Operational MODE: single process *** Traceback (most recent call last): File "/home/ubuntu/[app]/wsgi.py", line 14, … -
Google Assistant being extremely intrusive in my Django website
I have a homepage where the text - when clicked triggers Google Assistant to translate it, and this is very bad experience for the user. I have tried to set the website language so GoogleAssistant don't just translate/define english words. and have tried the following snippets but in vain. no-translate <html lang="en"> What else possibly I can do this avoid this sh*t. [ sorry I'm really tired of this so called 'Assistant' ]Website homepage with Django I expected to work "normally" but anytime a word or text is clicked Google Assistant gets into play.