Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Javascript code is not working completely
I am trying to add items to my cart thus using javascript to indicates the product and fetch api to obtain data of item. But my javascript file is somehow get stuck and not running completely . I wrote a code in my js file and if i open server inspect tab to get src code , the code is not the same . -
filter queryset with filterset for anonymous. How install exception 401 UNAuthorized
I am a beginner developer django. I do site foodgram. Here you can publish recipes, subscribe to authors, add recipes to your shopping list. I try install filtering requests for users using bu shopping_cart and favorite as filterset. But I cant to install exception for anonymous.For request /api/recipes/?is_in_shopping_cart appear all recipes. But must be error 401 Unautorized My code filter class CustomFilters(filters.FilterSet): tags = filters.ModelMultipleChoiceFilter(field_name='tags__slug', to_field_name='slug', queryset=Tag.objects.all()) author = filters.NumberFilter(field_name='author') is_favorited = filters.BooleanFilter(field_name='is_favorited', method='get_is_favorited') is_in_shopping_cart = filters.BooleanFilter( field_name='is_in_shopping_cart', method='get_is_in_shopping_cart' ) def get_is_favorited(self, queryset, name, value): user = self.request.user if (user.is_authenticated and value is True and name == 'is_favorited'): return queryset.filter(recipes_favorite_recipes__user=user) return Response(status=status.HTTP_401_UNAUTHORIZED) def get_is_in_shopping_cart(self, queryset, name, value): user = self.request.user if ( user.is_authenticated and value is True and name == 'is_in_shopping_cart' ): return queryset.filter(recipes_shopping_cart_recipes__user=user) return Response(status=status.HTTP_401_UNAUTHORIZED) class Meta: model = Recipes fields = ['tags', 'author', "is_in_shopping_cart", "is_favorited"] if I I remove the method condition in the filter and leave only Response(status=status.HTTP_401_Unauthorized) with an anonymous request, recipes still appear and an error appears on the site. I will glad any advice -
Wrong display on pythonanywhere
I am running a django app on pythonanywhere. I tested it in local and everything was working just fine without any error. However, on pythonanywhere, there is a problem on one of my pages. On it I have a button that changes the style of a part of the page (basically changing a rectangle from portrait to landscape). Everything else on that page works well, but when I click that button, nothing changes. I dig and looked at the template I'm rendering before and after clicking, the template is correctly changed, but nothing changes on the screen. I tried to reload the site from pythonanywhere and then refresh the page, the pages changes well. I'have looked at the access log, the Error log and the Server log, none shows anything indicating any error. I don't understand where the problem is. -
Django database connection with postgis automatically shutdown after serval time
My database automatically shuts down after a few hours. I'm using PostgreSQL 14 with Django 4.2.4,In django i am getting connection refused error ,When i amdcheckfor postgress status it and here's my database configuration in settings.py and PostgreSQL logs, I see the following logs: DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'fight-db', 'USER': 'postgres', 'PASSWORD': 'gsdgfwtdtfw', 'HOST': '192.**********', 'PORT': '5432', } } In the PostgreSQL logs, I see the following logs: 2023-09-21 21:48:11.208 UTC [15283] LOG: received fast shutdown request 2023-09-21 21:48:11.222 UTC [15283] LOG: aborting any active transactions 2023-09-21 21:48:11.264 UTC [15283] LOG: background worker "logical replication launcher" (PID 15290) exited -
Mostly Basic Django Site on Google Cloud
I have a basic "mostly informational-only" corporate website in WordPress 6.3 and I plan on migrating it to Django 4.2 since the only one who would be editing the content would be the developer himself. Looking at these options - https://cloud.google.com/python/django - what's the best way to go about with this ? May or may not have a database - if so, it would be of low consumption like max 1GB storage for MySQL. -
Initial Value in modelForm through init
It could be that I'm trying to solve this issue the wrong way. But if someone has a good idea of how to solve this I'm all ears for it. What I want to achieve. I have a model with a Charfield, that I populate with data from a field in another model. For different reasons a ForeignField is not an option for me. So instead I define the data so select from the Init process of my model form. It works well to establish a list to pick from. I have tried to simplify the code below. class myModel(model.Models) troop = models.CharField(......) stuff = models.CharField(......) camp = models.SlugField(......) def __str__(self): return self.troop class mySecondModel(model.Models) name = models.CharField(......) other_stuff = models.CharField(......) slug = models.SlugField(......) camp = models.SlugField(......) def __str__(self): return self.slug class View_Troop(UpdateView): template_name = 'troop.html' model = myModel form_class = myModel_form def get_form_kwargs(self): id_ = self.kwargs.get('id') #//'id' = troop # obj= myModel.objects.filter(troop=id_) kwargs = super(View_Troop, self).get_form_kwargs() kwargs.update({'troop': obj.troop}) kwargs.update({'camp': obj.camp}) return kwargs class myModel_form(forms.ModelForm) stuff = ModelChoiceField(queryset= mySecondModel.objects.all()) class Meta: model = myModel fields = '__all__' def __init__(self, *args, **kwargs): troop = kwargs.pop('troop') camp = kwargs.pop('camp') variable_1= .... function based on troop value super(myModel_form, self).__init__(*args, **kwargs) self.fields['stuff'].queryset=mySecondModel.objects.filter(other_stuff__contains= variable_1, camp=camp) … -
Gateway timeout Django
Have a Django website running on a virtual machine. When I run the site locally on a virtual machine via runserver, everything works as it should. But if I run with the condition runserver 0.0.0.0:8000 (to connect from another machine in the local corporate network), then when I run heavy queries on the site (with a runtime of more than a minute with access to the Postgres database), I get a Gateway Timeout error. But the request itself is not interrupted and continues its execution. I don't understand the reason. I tried to adjust the SETTINGS by adding a TIMEOUT, and I started it from under IIS with an indication of a long TIMEOUT - the result is the same. -
Docker/Django reflects changes only once
Whenever I make a change in a template, it will be reflected on the page. Every subsequent change is ignored. When I refresh page, it "shuffles" between original and first change. I am not a pro, but it looks like something with cacheing? I am not aware of caching anything though. version: '3.7' services: web: container_name: web build: . restart: always command: ["/wait-for-it.sh", "db:5432", "--", "gunicorn", "--bind", "0.0.0.0:8000", "--workers", "3", "mysite.wsgi:application"] volumes: - .:/app - static_files:/app/staticfiles - media_files:/app/media expose: - 8000 env_file: .env depends_on: - db nginx: container_name: nginx restart: always image: nginx:stable-perl volumes: - static_files:/app/staticfiles - media_files:/app/media - ./nginx/user_conf.d/:/etc/nginx/conf.d/ ports: - "80:80" depends_on: - web - db db: container_name: db image: postgres:13 restart: always volumes: - postgres_data:/var/lib/postgresql/data/ - ./db_backup:/app/db_backup/ env_file: .env pgadmin: container_name: pgadmin4_container image: dpage/pgadmin4 restart: always environment: PGADMIN_DEFAULT_EMAIL: mail PGADMIN_DEFAULT_PASSWORD: pw ports: - "5050:80" depends_on: - db volumes: - pgadmin:/var/lib/pgadmin volumes: postgres_data: static_files: media_files: pgadmin: db_backup: -
How to give a result to a html page in python
I have a Django project setup and an HTML page in this project that is asking for a password, and a Python code that is checking that password to validate it, the two are connected, and the password is sent with the GET method and my question is how to respond to the password, after it was checked with valid or invalid depending on the case and how to integrate that response in my page -
ValueError: Field 'id'
When I POST new email i send this request, sender and receiver should represent registered users... i get this error ValueError: Field 'id' expected a number but got '<django.db.models.query_utils.DeferredAttribute object at 0x10291f410>'. I try to delete the migrations and the db.sqlite3 file several times, and run makemigrations & migrate commend but it didn't work. I'm new to Django...So so sorry if i'm not in the right direction at all. I would appreciate any help, thanks { "sender": "test1@gmail.com", "receiver": "test2@gmail.com", "subject": "Hello", "message": "bbaa aaafff jjjj fslskjf adjfjfj dkdklfwl lfewjro fjklsfjl dddkkc "unread": true } models.py class CustomUserManager(BaseUserManager): def create_user(self, email, password, **extra_fields): email = self.normalize_email(email) user = self.model( email=email, **extra_fields ) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault("is_staff", True) extra_fields.setdefault("is_superuser", True) # is_staff -> controls whether the user is allowed to log in to the admin interface. if extra_fields.get("is_staff") is not True: raise ValueError("Superuser has to have is_staff attribute set to True.") # is_superuser -> have access to create, edit, and delete any object (models). if extra_fields.get("is_superuser") is not True: raise ValueError("Superuser has to have is_superuser attribute set to True.") return self.create_user(email=email, password=password, **extra_fields) class User(AbstractUser): email = models.EmailField(max_length=80, unique=True) username = models.CharField(max_length=50) objects = CustomUserManager() … -
Django framework - makemigrations - no changes detect
In my Django project, when I am running the makemigrations command, it shows no changes detected. I have also updated my settings.py file. It is still facing the same issue, and I tried writing , but it still isn't working. I'm attaching some screenshots here.enter image description here I'm attaching an another ss i want that output. -
Django how to update price of an item if that item existed or save that item to database if not
My models: class Product(models.Model): name = models.CharField(max_length=200) current_price = models.CharField(max_length=50) place = models.CharField(max_length=50) url = models.CharField(max_length=50) img = models.CharField(max_length=50) date_add = models.DateTimeField(default=timezone.now) def __str__(self): return self.name My codes: def cellphones(query): lists = [] search = query.replace(' ', '%20') url = f"https://cellphones.com.vn/catalogsearch/result?q={search}" driver.get(url) content = driver.find_element( By.CSS_SELECTOR, "div[id*='search-catalog-page']") items = content.find_elements( By.CSS_SELECTOR, "div[class*='product-info']") for _ in items: item = Item( url=_.find_element(By.CSS_SELECTOR, "a").get_attribute('href'), name=_.find_element(By.CSS_SELECTOR, "h3").text, current_price=_.find_element(By.CSS_SELECTOR, "p[class*='product__price--show']").text, place="Cellphones", img=_.find_element(By.CSS_SELECTOR, "img").get_attribute('src'), date_add=datetime.datetime.now() ) if Product.objects.filter(name=item.name, place=item.place).first(): t = Product.objects.get(name=item.name, place=item.place) t.current_price = item.current_price t.img = item.img t.date_add = item.date_add t.save() else: save_to_db(item) lists.append(item) return lists save_to_db: def save_to_db(item): conn = sqlite3.connect('../db.sqlite3') c = conn.cursor() c.execute("CREATE TABLE IF NOT EXISTS products (url TEXT, name TEXT, current_price TEXT, place TEXT, img TEXT, date_add TEXT)") c.execute("INSERT INTO products VALUES (?, ?, ?, ?, ?, ?)", (item.url, item.name, item.current_price, item.place, item.img, item.date_add)) conn.commit() conn.close() I want to update the price, date add of an item if that item already exists in the database. If that item not existed, i want to add it to the database. But the item will always save to the database. I think it the same problem i have here Django objects.all() return empty queryset where Product object return empty queryset. How do … -
How to Sort a Nested List in Django Rest Framework Serializer by a Field?
This is the data I am receiving in the frontend. { id: 1, tenant_id: 73, product_channel: 2, revision_status: "Effective", cou_charges_detail_row: [ { biller_category_ref_id: 23, rate_flag: false, rate_percentage: "0.75", min_value: 1, max_value: 5000, }, { biller_category_ref_id: 18, rate_flag: false, rate_percentage: "0.30", min_value: 1, max_value: 10000, }, { .... 31 rows more }, ], } I want to send the cou_charges_detail_row sorted by biller_category_ref_id in ascending order from the backend. { id: 1, tenant_id: 73, product_channel: 2, revision_status: "Effective", cou_charges_detail_row: [ { biller_category_ref_id: 18, rate_flag: false, rate_percentage: "0.30", min_value: 1, max_value: 10000, }, { biller_category_ref_id: 23, rate_flag: false, rate_percentage: "0.75", min_value: 1, max_value: 5000, }, { .... 31 rows more }, ], } Here are relevant code snippets from my models, serializers, and views for reference. I'm seeking guidance to correctly sort the cou_charges_detail_row list. views.py class COUChargesViewSet(viewsets.ModelViewSet): queryset = CustomerOUCharges.objects.filter(is_deleted=False, is_active=True).order_by('-id') serializer_class = COUChargesSerializer def list(self, request): tenant_id = LoginSerializer.get(request.user).values_list("tenant_id", flat=True) if 'id' in self.request.GET: charges_obj = CustomerOUCharges.objects.filter(is_deleted=False,id = request.GET["id"]).exclude(revision_status='History').order_by('-id') serializer = self.get_serializer(charges_obj, many=True) return Response(serializer.data) else: charges_obj = CustomerOUCharges.objects.filter(tenant_id__in =tenant_id, is_deleted=False, is_active=True).exclude(revision_status='History').order_by('-id') serializer = COUChargesSerializer(charges_obj, many=True) return Response(serializer.data) serializers.py class COUChargesSerializer(serializers.ModelSerializer): tenant_name = serializers.CharField(source=varible_class.tenant_id_tenant_name, read_only=True) cou_charges_detail_row = COUChargesDetailsSerializer(many=True) class Meta: model = CustomerOUCharges fields = ('__all__') class COUChargesDetailsSerializer(serializers.ModelSerializer): id = … -
Delete Duplicate Rows in a huge Django DB with condition
There are several questions similar to mine but none are satisfactory. I would like to be able to remove duplicates from a DB having more than 26 million lines, therefore in the most efficient way with the condition that I want to keep the row which has the most recent update date (update_date is a field). Is it possible to use the Django ORM or do we have to use SQL in that case? Thank you in avance for your help. -
Images not showing on production after i deployed my django mvt app to heroku
My django mvt app seems to be working fine on development but not on production, everything works fine except that the images are not displaying, that is they are not been served on production environment. i have check my static and media settings and they are all good my findings point to ngnix configuration because i changed to gunicorn on production and according to a post heroku website, i created a config folder and add a file name ngnix.conf.erb and add the configuration below server { listen 80; server_name www.asashop-2f86477073eb.herokuapp.com asashop-2f86477073eb.herokuapp.com/; location /favicon.ico { access_log off; log_not_found off; } location /static/ { root /app/static/; } location /media/ { root /app/media; } location / { include proxy_params; proxy_pass http://localhost:8000; } } but no changes, heroku supports says the issue is from my app configuration, i've been stuck with this for about 2 days, i dont know what i'm doing wrong, pls help. thanks in advance -
Using HTML Template with django project
The problem I have is that I cant load pictures and CSS from template to django. Here is the structure of the files. -
object attribute is missing after manager.py is restarted when using django redis cache
Here is the sample code: class CrossSection(LoggerMixin): pass class CrossSectionFactory(LoggerMixin): cross_section_sequence = {} def add(self, date): cross_section = CrossSection() self.cross_section_sequence[date] = cross_section class Analyzer(LoggerMixin): cross_section_factory = None def __init__(self, logger=None, **kwargs): self.cross_section_factory = CrossSectionFactory(logger=logger, **kwargs) def init(self): pass # ---- from django.core.cache import cache class MyDetail(APIView): def post(self, request, analyzer_id, date, format=None): analyzer = cache.get("analyzer:1") if analyzer is None: analyzer = Analyzer(**{}) analyzer.init() cache.set("analyzer:1", analyzer) settings.py: CACHES = { "default": { "BACKEND": "django.core.cache.backends.redis.RedisCache", "LOCATION": "redis://xxx:xxxxx@xxx.com:6379", "TIMEOUT": None, } } If the manger.py is not restarted, it can get analyzer with all attributes, but if manger.py restarts, the other attributes are all good except analyzer.cross_section_factory.cross_section_sequence, it become {} again. I tried set/get the analyzer.cross_section_factory directly, it seems that works fine. Do you know why this happens? How do I fix it? -
Calling notification.notify() raises "No Usable Implementation Found
This is properly executing when i run into my local system. But when i deployed into GCP, after that it generates this error. "No Usable Implementation Found! Not found any solution. please help to find out something. It is quite urgent -
Django FileNotFoundError at /admin/ [Errno 2] No such file or directory: '/media'
Website works fine locally but when I try to change or add to the model Trick (which has a FilePathField attribute) in localhost:8000/admin, I get FileNotFoundError [Errno 2] No such file or directory: '/media' (https://i.stack.imgur.com/DLql1.png) (https://i.stack.imgur.com/slzpl.jpg) (https://i.stack.imgur.com/KoBt7.jpg) I’m guessing there’s a problem with my media folder implementation, but I don’t know what it is. -
Django signal doesn't execute a function from my consumer
I have a problem regarding my consumer. or Django signal? I wasn't able to send a message from my group in the web socket by using my Django signal to execute the function from my consumer. I have here a Django signal code, which executes/tracks my model if being updated and it executes correctly: @receiver(post_save, sender=Person) def check_got_data_update_to_true(sender, instance, **kwargs): if instance.got_data: print(f"from django signals: {instance.id}") print(f"from django signals: {instance.company_website}") message = f"from django signals: {instance.id}" send_data_to_consumers(message) def send_data_to_consumers(message): channel_layer = get_channel_layer() try: async_to_sync(channel_layer.group_send)( "test", { "type": "handle_signal_message", "message": message, }, ) print("Group message sent successfully.") except Exception as e: print(f"Error sending group message: {str(e)}") now when there is an update from my model, my Django signals execute properly and output the message of Group message sent successfully in logs. Now here, I have a consumer that my Django signals calling the function of handle_signal_message and I don't know why this doesn't execute. Since when i put a print inside the function, it doesn't print. Here is the full code of my consumer: from channels.generic.websocket import ( AsyncJsonWebsocketConsumer, AsyncWebsocketConsumer, JsonWebsocketConsumer, ) import json class TestConsumer(AsyncJsonWebsocketConsumer): async def connect(self): await self.channel_layer.group_add("test", self.channel_name) await self.accept() print("Connected!") async def disconnect(self, close_code): print("Disconnected!") await … -
Celery is not updating django model field
So I have written a celery task to update a field on my django model which is here class PizzaOrder(models.Model): customer = models.ForeignKey(User, null=True, on_delete=models.CASCADE) total_price = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True) order_status = models.CharField(max_length=20) created_at = models.DateTimeField(auto_now_add=True) I want to update the order_status as following Once the order is placed, in the first minute, the status should change from ‘Placed’ to ‘Accepted’ After 1 minute, the status should change from ‘Accepted’ to ‘Preparing’ After 3 minutes it should change from ‘Preparing’ to ‘Dispatched’ After 5 minutes it should read ‘Delivered’ for which I have written below celery task from celery import shared_task from datetime import timedelta from django.utils import timezone from .models import PizzaOrder @shared_task def update_order_status(order_id): try: order = PizzaOrder.objects.get(pk=order_id) current_time = timezone.now() if order.order_status == 'Placed' and current_time - order.created_at <= timedelta(minutes=1): order.order_status = 'Accepted' elif order.order_status == 'Accepted' and current_time - order.created_at > timedelta(minutes=1) and current_time - order.created_at <= timedelta(minutes=2): order.order_status = 'Preparing' elif order.order_status == 'Preparing' and current_time - order.created_at > timedelta(minutes=3) and current_time - order.created_at <= timedelta(minutes=5): order.order_status = 'Dispatched' elif order.order_status == 'Dispatched' and current_time - order.created_at > timedelta(minutes=5): order.order_status = 'Delivered' order.save() except PizzaOrder.DoesNotExist: pass And I am calling that method in serializer … -
How to update total amount in a row set in inlineformset_factory in Django?
enter image description here <script> jQuery($ => { $('quantity').on('input', function() { let $row = $(this).closest('tr'); let price = $row.find("price").val(); $row.find('.total').text('$' + (this.value * price).toFixed(2)); }); }); </script> <form method="POST"> {% csrf_token %} <div class="col-lg-6 col-12 col-md-12 col-sm-12"> <h3>{{ header }}</h3> <div class="input-group mb-3"> <span class="input-group-text" id="inputGroup-sizing-default" style="width:120px">PO No.</span> {{ form.importno }} </div> <div class="input-group mb-3"> <span class="input-group-text" id="inputGroup-sizing-default" style="width:120px">Invoice No.</span> {{ form.doc_number }} </div> <div class="input-group mb-3 flex-nowrap"> <span class="input-group-text" id="inputGroup-sizing-default" style="width: 120px;">ETA</span> {{ form.eta }} </div> <div class="input-group mb-3"> <span class="input-group-text" id="inputGroup-sizing-default" style="width: 120px;">Supplier</span> {{ form.supplier }} </div> <div class="input-group mb-3"> <span class="input-group-text" id="inputGroup-sizing-default" style="width: 120px;">Deliver to Site</span> {{ form.deliverto_site }} </div> <div class="input-group mb-3"> <span class="input-group-text" id="inputGroup-sizing-default" style="width: 120px;">{{ form.created_by.label }}</span> {{ form.created_by }} </div> <div class="input-group mb-3"> <span class="input-group-text" id="inputGroup-sizing-default" style="width: 120px;">Total Quantity</span> {{ form.totalqty }} </div> <div class="input-group mb-3"> <span class="input-group-text" id="inputGroup-sizing-default" style="width: 120px;">Total Amount</span> {{ form.totalamount }} </div> </div> {{ formset.management_form }} {% for error in formset.non_form_errors %} <span style="color: red">{{ error }}</span> {% endfor %} <!-- Product Details --> <div class="display_table overflow-auto"> <table id="mytable" class="table table-striped table-hover " style="font-size: 14px; white-space: nowrap; width: 100%"> <thead> <tr class="table-dark" style="color: white;"> <th style="text-align: center; width: 45%;">Product</th> <th scope="col" style="text-align: center; width: 10%;">Quantity</th> <th scope="col" style="text-align: center; … -
Django CheckboxSelectMultiple() duplicates options
I have a form in which there is a field called 'value' for which I want the user to be able to select one or more options: class MyForm(): class Meta: model = X fields = ['type'] widgets = {'type': forms.widgets.CheckboxSelectMultiple()} The problem is that, when this outputs, the options are duplicated two-fold: I see one copy of the options with square check-boxes and another copy of the options with circular radio select boxes. Why does this happen and how do I fix it? See https://github.com/django-crispy-forms/django-crispy-forms/issues/357 for previous posts on this issue, for which there is no clear solution. -
Why Django did not migrate using this project [closed]
I am a beginner in programing, i have tried few youtube projects on HTML, CSS VBA and have successfully compiled a VBA project recently. but most of the debuging method i use are from youtube videos. Infect I started here after I have interest on further my learning to PYTHON DJANGO were I found this open source code video ( https://t.ly/FfN7E ) including three of its full project. As a beginner i just follow step by step through but now i got stuck when running this migration command; "python manage.py makemigrations I expect it to connect to a database i guess so it can launched onto a browser but it wasn't. -
Django Project Error: "Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding"
I'm encountering a critical error in my Django project that I can't seem to resolve. When I try to run my Django application, I receive the following error message: Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' ``` I've been searching for a solution but haven't found anything that works. It's worth mentioning that this issue is preventing me from running any Django commands (e.g., manage.py runserver, manage.py migrate, etc.). Here are some details about my environment: (1) Django version: 4.2.5 (2) Python version: 3.9.16 (3) Server: Cpanel Shared Hosting(Namecheap) I've tried the following steps to resolve the issue without success: (1) Reinstalling Python and Django. (2) Checking my system's PYTHONPATH. (3) Ensuring that the virtual environment is activated. Has anyone encountered this issue before, or does anyone have suggestions on how to resolve it? Any help would be greatly appreciated.