Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to filter ManyToMany field in Django queryset?
I have models: class VideoParameter(models.Model): member = models.ForeignKey(Tag, on_delete=models.DO_NOTHING, related_name="parameter_tag") value = models.PositiveIntegerField() class Video(TimeStampedModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) parameters = models.ManyToManyField(VideoParameter, related_name="video_parameter") url = models.URLField(verbose_name=_('Url')) (I mean that a video have some parameters like Key-Value (ex. {"rabbit": 1, "panda": 1, "lion": 0})) Then I am trying to get the video, specified by query parameter. (like this /video/?rabbit=1&panda=1&lion=0) The SQL code that I want to do is belows: SELECT app_video.id, count(*) AS match_count FROM app_video INNER JOIN app_video_parameters on app_video.id = app_video_parameters.video_id INNER JOIN app_videoparameter ON app_video_parameters.videoparameter_id = app_videoparameter.id WHERE (app_videoparameter.member_id = 1 AND app_videoparameter.value = 0) OR (app_videoparameter.member_id = 9 AND app_videoparameter.value = 1) OR (app_videoparameter.member_id = 11 AND app_videoparameter.value = 1) ... GROUP BY (app_video.id) ORDER BY match_count DESC; How can I realize this process in Django queryset? -
Categorial Tabs Not Displaying in Nav-Bar Despite Using For Loop - Need Assistance
I'm trying to add multiple category tabs to the nav-bar using a for loop, but the result doesn't seem to show anything. I'm not sure where I went wrong. <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="{% url 'category:category_list' %}" role="button" data-bs-toggle="dropdown" aria-expanded="true"> Danh mục sản phẩm </a> <ul class="dropdown-menu"> {% for category in category_list %} <li><a class="dropdown-item" href="{% url 'category:category_detail' category.id %}">{{ category.category_name }}</a></li> {% endfor %} <li><a class="dropdown-item" href="#">Action</a></li> <li><a class="dropdown-item" href="#">Another action</a></li> </ul> </li> This is result -
How to implement caching for tokens in Django Rest Framework and Firebase Auth
I'm building an API using Django Rest Framework and I was thinking about using Firebase for authentication. I have some questions about how to implement the caching layer. **This is how the application works: ** A user logs in using the frontend (React.js), then when I make an API call to DRF and I pass the auth token sent back by Firebase. Using that token, DRF calls Firebase again to retrieve the user, and finally I retrieve the UserProfile for that user in DRF by querying a Postgres db. I want all this operations to result in the least amount of calls to Firebase, hence I was thinking about caching the (user token, user id) pair. However, I have never implemented caching in Django before and would appreciate any guidance. Also, what caching strategy and tool can you recommend me? Thank you -
Cannot delete "Forgot Password?" on Sign in page. Seems completely unresponsive to code
I'm expecting code to delete "Forgot your Password"?. Screenshot of deployed site (marked problem area in red) I cannot delete "Forgot your Password?" link, the issue seems to be to do with django resorting to default code that I cannot locate. Screenshot here of templates structure In templates/allauth/account/password_change.html I have commented out code {% extends "account/base_manage_password.html" %} {% load allauth i18n %} {% block head_title %} {% trans "Change Password" %} {% endblock head_title %} {% block content %} {% element h1 %} {% trans "Change Password" %} {% endelement %} {% url 'account_change_password' as action_url %} {% element form form=form method="post" action=action_url %} {% slot body %} {% csrf_token %} {% element fields form=form %} {% endelement %} {% endslot %} {% slot actions %} {% element button type="submit" %} {% trans "Change Password" %} {% endelement %} <!-- <a href="{% url 'account_reset_password' %}">{% trans "Forgot Password? TESTHERE" %}</a> --> {% endslot %} {% endelement %} {% endblock content %} Repo links See my full repo here: github.com/lmcrean/Project-4 See deployed site here: http://lmcrean-ittib-b97fbbd27fb0.herokuapp.com/accounts/login/ So far I've tried ... lead to no change in deployed site. I've tried updating file structure to contain account within allauth I've updated settings to … -
Representing NFT wallet addresses in Django model fields
I'm building a Django app that involves working with NFTs, and I want to know the best way to represent NFT wallet addresses using a Django model field. NFT wallet addresses are typically hexadecimal strings, but I'm not sure how to design the model field to accommodate them efficiently. I think the best option is a customization of the CharField with a length constraint to store the hexadecimal address. But is there a recommended maximum length for NFT wallet addresses? I'd exclude UUIDField and TextField. I'd appreciate any examples and recommendations. Thank you! -
Django-Tailwind not rebuilding after updating the template files
I did everything the instructions on the package website told me to; when I launch python manage.py tailwind start, it does indeed rebuild the stylesheets and add any new classes, but the issue is, after that, it just doesn't do anything when I add new classes in my templates. I'm not exactly sure what could be the issue with it, as I set everything up like the instruction said. All configs should be the same, and, I think, in the content config in tailwind.config.js, this is the line that's supposed to detect all of my templates: '../../**/templates/**/*.html' (this file is in [project_name]/theme/static_src/tailwind.config.js, my templates are in [project_name]/[app_name]/templates/[app_name]/[template_name].html, so I think it should check out) Actually, from what I've found out, it doesn't seem to detect changes pretty much anywhere, even in its own template files. While testing this out before actually asking in here, I also found out that changing the tailwind.config.js file itself and saving (even just saving without changes) actually does trigger the rebuild process. Although afterwards I found out that this was probably just because it was a config file, so it didn't really help me at all, the most I can get from this is to … -
Djoser override UserCreateSerializer not creating model instance
I've made modifications to the UserCreateSerializer provided by Djoser. Within the perform_create method, I'm attempting to create instances of the UserProfile and AddressDetails models. While the server appears to be functioning correctly, it seems that the data is not persisting as expected. I'm seeking guidance on identifying and rectifying any errors in this process. How would you suggest addressing this issue? accounts.serializers.py from djoser.serializers import UserCreateSerializer from django.contrib.auth import get_user_model from rest_framework import serializers from django.db import transaction from django.db.utils import IntegrityError from django.contrib.auth.password_validation import validate_password from .models import AddressDetails, UserProfile User = get_user_model() class UserCreateSerializer(UserCreateSerializer): address_line_one = serializers.CharField(write_only=True) address_line_two = serializers.CharField(write_only=True) address_line_three = serializers.CharField(write_only=True) province = serializers.CharField(write_only=True, required=True) barangay = serializers.CharField(write_only=True, required=True) city = serializers.CharField(write_only=True, required=True) zip_code = serializers.CharField(write_only=True, required=True) first_name = serializers.CharField(write_only=True, required=True) middle_name = serializers.CharField(write_only=True, required=True) last_name = serializers.CharField(write_only=True, required=True) date_of_birth = serializers.DateField() gender = serializers.CharField(write_only=True, required=True) relationship_status = serializers.CharField(write_only=True, required=True) phone_number = serializers.CharField(write_only=True, required=True) class Meta(UserCreateSerializer.Meta): model = User fields = ( "id", "email", "user_role", "password", "address_line_one", "address_line_two", "address_line_three", "province", "barangay", "city", "zip_code", "first_name", "middle_name", "last_name", "date_of_birth", "gender", "relationship_status", "phone_number" ) @transaction.atomic def perform_create(self, validated_data): address_line_one = validated_data.pop("address_line_one") address_line_two = validated_data.pop("address_line_two") address_line_three = validated_data.pop("address_line_three") province = validated_data.pop("province") barangay = validated_data.pop("barangay") city = validated_data.pop("city") zip_code = validated_data.pop("zip_code") … -
Add watchlist to product page
By clicking the Add button, the user should be able to add the product to the watch list. After this, the button should be changed to Remo, and by pressing it, the product will be removed from the list. There should be a link title at the top of the page and click on those products that are in the watch list to be displayed. However, these codes do nothing. Why?? forms & models.py: #forms.py class AddWatchlist(forms.Form): product_id = forms.IntegerField(widget=forms.HiddenInput()) #models.py(Related parts) class Product(models.Model): title = models.CharField(max_length=64) views.py: def product_detail(request, product_id): product = get_object_or_404(Product, pk=product_id) comments = Comment.objects.filter(product=product) offers = PriceOffer.objects.filter(product=product).order_by('-offer_price') off_list = [float(product.first_bid)] maximum = float(product.first_bid) if request.method == 'POST': # comment # offer off = maximum context = { 'product': product, 'comments': comments, 'offers': offers, 'off' : off } return render(request, 'auctions/product_detail.html', context) def watchlist(request): products = request.user.watchlist.all() return render(request, 'auctions/watchlist.html', {'products': products}) def add(request): if request.method == 'POST': form = AddWatchlist(request.POST) if form.is_valid(): product_id = form.cleaned_data['product_id'] product = Product.objects.get(id=product_id) request.user.watchlist.add(product) return redirect('product_detail') else: form = AddWatchlist() return render(request, 'auctions/add.html', {'form': form}) def remove(request, product_id): product = Product.objects.get(id=product_id) request.user.watchlist.remove(product) return redirect('watchlist') urls.py: path("product_detail/<int:product_id>/", views.product_detail, name="product_detail"), path('add', views.add, name='add'), path('remove/<int:product_id>/', views.remove, name='remove'), path('watchlist', views.watchlist, name='watchlist'), product_detail.html(Related parts): {% for … -
You cannot call this from an async context - use a thread or sync_to_async Django
I'm making a telegram bot. That's why I use asynchronous methods in django. @dp.message(Command('habits')) async def handle_habits(message: types.Message): chat_id = message.chat.id profile = await TelegramProfile.objects.aget(chat_id=chat_id) user = profile.user await bot.send_message(chat_id, text=user - {user}') I get an error when I call the last line: You cannot call this from an async context - use a thread or sync_to_async. How to fix it? -
Form not valid after setting QuerySet of field in __init__
A new Workorder is created by visiting the Building page and creating a Work Order. This in turn displays the WorkOrderForm on a new page. When viewing this form, I want to display only the equipment associated to a building, not all of the equipment. I have tried overriding the __init__ of the form to set the queryset of the MultipleChoiceField, which works as intended in displaying the equipment associated to the building, however when submitting the form the form.is_valid() fail yet there are no errors displayed. I have 3 models Building, WorkOrder and Equipment as follows: Building class BuildingDetail(models.Model): location_Code = models.CharField(primary_key=True, max_length=15, help_text='Enter a location code.', unique=True) civic_Address = models.CharField(max_length=100, help_text='Enter the civic address of the location.') current_Tenant = models.ForeignKey(Tenant, on_delete=models.CASCADE, help_text='Select a Tenant.') landlord = models.ForeignKey(Landlord, on_delete=models.CASCADE, help_text='Select a Landlord.') WorkOrder class WorkOrder(models.Model): id = models.CharField(primary_key=True, max_length=7, default=increment_workorder, verbose_name="ID") building_Code = models.ForeignKey(BuildingDetail, on_delete=models.CASCADE) issue_Date = models.DateField(blank=True, null=True, default=datetime.date.today()) completion_Date = models.DateField(blank=True, null=True) tenant_Issue = models.TextField(help_text="Enter the issue description.") scope_Of_Work = models.TextField(help_text="Enter the Scope of Work required.") contact_name = models.CharField(max_length=50, help_text='Enter the contact Name.', blank=True, default="") contact_number = models.CharField(max_length=11, help_text='Enter the contact Phone Number.', blank=True, default="") rebill_Invoice = models.TextField(max_length=50, help_text='Enter the Devco Rebill Invoice number.', blank=True, default="") rebill_Date … -
Can i connect django with mongoDb
Does it good to connect django version 4.2.7 With monogdb? Is is a good practice? What is the trade off If there . If not what is best DB AND DBMS to work with it Or just use django models I have seen that a djongo is not a good one because it has a lof of drowbacks -
Django add random character in filename
I want to upload image and overwrite if the file exist without changing the filename. It's already can overwrite the file but django always add random char on the end filename. How can i overwrite with the same filename ? Here are my code. foto_content_url = models.ImageField(null=True, blank=True, upload_to=foto_path) def foto_path(instance, filename): return '/', filename + '.jpg']) -
PostgreSQL database migration problem from my Django project to AWS Elastic Beanstalk
I've just finalised my project based on **Django ** and **PostgreSQL ** *locally * on my Windows 10 machine. When migrating to AWS Elastic Beanstalk using pgAdmin 4, I'm having problems with the database. Despite my efforts to deploy the project with its data, the database on AWS does not contain any of the information previously stored locally. I followed the recommended steps to export my PostgreSQL database with pgAdmin 4 and successfully deployed my Django project on AWS Elastic Beanstalk. However, I can't find the data in the AWS database. I tried to export my PostgreSQL database from pgAdmin 4 as a backup file. Then I imported this file into my AWS database. I expected all my data, such as tables, records, etc., to be copied from my local database to the database on AWS. I checked the permissions and configurations to make sure the login details were correct, but the data doesn't seem to have transferred correctly to the database on AWS. What steps have I missed or what specific configurations are required to ensure the complete transfer of data from my local database to AWS Elastic Beanstalk? -
how to save user progress?
I'm building a learning spoken languages website where the users get to guess pictures, and I'm using Django and React. How to make each user have its own data or, in other words, how to make each user have its own progress? What do I need in Django to do this? I have a solution which is to add a user column in the model I want to save the progress of, and when someone register, an instance of that model will be created. But in this way if I have so many users, I will have a huge database, does anyone know if there is a better way to do that? -
ModuleNotFoundError: No module named 'pygments'
I try to practive with Django REST Framework. I have installed pygments module via: (venv) pip install pygments I see it in installed modules: (venv) pip list Package Version ------------------- ------------ asgiref 3.7.2 Django 4.2.7 djangorestframework 3.14.0 numpy 1.26.1 pandas 2.1.2 pip 23.3.1 Pygments 2.16.1 But when I import it to use and run make migration: (venv) python manage.py makemigrations snippets .... from pygments.lexers import get_all_lexers ModuleNotFoundError: No module named 'pygments' How to solve this problem? I follow the toturial of Django REST framework: https://www.django-rest-framework.org/tutorial/1-serialization/ and stuck at this step. -
Django html table iterating pandas df and create scrollbar
I am working on a django project where I render a pandas df in the context. I then iterate through this data frame to display it in a table td td (html below). I would like to get this as a fixed size with horizontal and vertical scrollbars instead when the data frame is too large. How can I do this? Thnx! :-) <table style="margin-left: auto; margin-right: auto;"> <tr> {% for col in df.columns %} <td> <b>{{col}}</b> </td> {% endfor %} </tr> {% for index, row in df.iterrows %} <tr> {% for cell in row %} <td> {{cell}} </td> {% endfor %} </tr> {% endfor %} </table> -
itrate ManyToMany Field and save the instance of the field
Hi im developing django app for sending bulk email to Users, i have two models name Reminder and Mail , Reminder model has a Assign_to field which is ManyToMany Field with User model, i write a signal for Reminder model for When an instance Created, for every User that assigned in reminder an instance created in Mail model, i user for loop in signal, but i dont have error but it just dosnt work My Mail Model: ``class Mail(models.Model): sender = models.ForeignKey( "accounts.User", on_delete=models.CASCADE, related_name="user_sender" ) recipient = models.ForeignKey( "accounts.User", on_delete=models.CASCADE, related_name="user_recipient" ) subject = models.CharField( max_length=255, ) body = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) is_read = models.BooleanField(default=False) is_archived = models.BooleanField(default=False) is_deleted = models.BooleanField(default=False) is_starred = models.BooleanField(default=False) cc = models.EmailField(blank=True, null=True) bcc = models.EmailField(blank=True, null=True) attachments = models.FileField(upload_to="attachments", blank=True, null=True) importance = models.CharField( max_length=20, choices=[("HIGH", "HIGH"), ("MEDIUM", "MEDIUM"), ("LOW", "LOW")] ) folder = models.CharField( max_length=20, choices=[("INBOX", "INBOX"), ("SENT", "SENT"), ("DRAFT", "DRAFT")], ) is_draft = models.BooleanField(default=False) reply_to = models.EmailField(blank=True, null=True) thread_it = models.CharField(max_length=255, blank=True, null=True) is_replied = models.BooleanField(default=False) tags = models.ManyToManyField("Tag", blank=True) is_forwarded = models.BooleanField(default=False) def __str__(self): return self.subject` ` MyReminder Model: class Reminder(models.Model): reminder = models.CharField( default=generate_pk, max_length=255, unique=True, editable=False, verbose_name="Reminder ID", ) title = models.CharField(max_length=255) description = models.TextField() date = … -
Hello, when ever i submit a contact page they show me the error
Here is the code Views.py enter image description here enter image description here models.py enter image description here Here is the image of my code. Please tell me the solution. How i submit my contact form in my django database. -
Django Channels group send doesn't send any data to the group
My websocket works, but doesn't send any data to the group # settings.py # WSGI_APPLICATION = 'gozle_ads.wsgi.application' ASGI_APPLICATION = 'gozle_ads.asgi.application' CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("localhost", 6379)], }, }, } # consumers.py import json from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer class BannerConsumer(WebsocketConsumer): def connect(self): self.accept() self.room_name = "banner_changer" self.room_group_name = "banner_changer_group" async_to_sync(self.channel_layer.group_add)( self.room_name, self.room_group_name ) self.send(json.dumps({"messgae": "Connected to the banner websocket"})) def receive(self, text_data=None): async_to_sync(self.channel_layer.group_send)( "banner_changer_group", { "type": "banner_ads_socket", "value": f"{text_data}" } ) def disconnect(self, code): print("DISCONNECTED") def banner_ads_socket(self, event): print("BANNER ADS") print(event) # asgi.py import os from django.core.asgi import get_asgi_application from django.urls import re_path from channels.routing import ProtocolTypeRouter, URLRouter from ads.consumers import BannerConsumer os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'gozle_ads.settings') ws_patterns = [ re_path(r"ws/banner/", BannerConsumer.as_asgi()) ] application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": URLRouter(ws_patterns), }) when I'm sending data to the receive method nothing is happening, method banner_ads_socket doesn't work. It doesn't raise any errors. First, I'm adding consumer to my group, then sending data to the group. I copied that from video. In the this code works, but my code not. What can I do with that? -
How to sign in to pyrogram (Client) with django instead of interactive console?
I want to create useful telegram utils for my own. The first big problem is signing into pyrogram Client (Telegram account) I did somethings in django. I've tried to login like that but I've got an error. Here is my view of django: def add_telegram_account(request): code_sent = False phone_number = '' client_sign_in_info = {} two_step = False if 'phone' in request.GET: phone_number = request.GET['phone'] client = Client(phone_number, api_id=api_id, api_hash=api_hash) client.connect() client_sign_in_info = client.send_code(phone_number=phone_number) code_sent = True if request.method == "POST" and 'code' in request.POST: code = request.POST['code'] try: client.sign_in(phone_number, client_sign_in_info.phone_code_hash, code) client.send_message("me", "logged in") except SessionPasswordNeeded: two_step = True if request.method == "POST" and 'two_step' in request.POST: client.check_password(request.POST['two_step']) client.send_message("me", "logged in") return render(request, "telegram/add_telegram_account.html", {'code_sent':code_sent}) And I've got this error --> There is no current event loop in thread 'Thread-1 (process_request_thread)'. -
Using Django paginator to display multiple Django forms page by page but unable to save the data from the pages
I am using Django paginator to create an input page that display multiple forms as single pages. With the paginator in place i would like to enable endless scrolling. I have asked questions to ChatGPT and so far the code provided does not save the data. The latest solution does not even show the save all button as intended. I am not sure if the data is actually stored in the session before changing to the next page as every time i change page, the form is blank. below is the view function and html template. The generation of the page with the correct sub template is working. `# views.py from django.core.paginator import Paginator from django.core.exceptions import ObjectDoesNotExist from django.core.exceptions import ValidationError from django.shortcuts import render, redirect, get_object_or_404 from django.urls import reverse from django.contrib.auth import authenticate, logout from django.contrib import messages from django.http import JsonResponse, HttpResponseRedirect from django.forms.models import model_to_dict from django.db import transaction ... # Define a function to handle the final save operation def save_all_forms(form_classes, form_data_list): # Start a database transaction with transaction.atomic(): # Save the first form instance first_form_class = form_classes[0] first_form_instance = first_form_class(**form_data_list[0]).save() # Save subsequent form instances instances = [first_form_instance] for form_class, form_data in zip(form_classes[1:], … -
404 1804 error when using Django template and trying to get Javascript located in static folder
I am working in a Django template and getting the error 404 1804 when trying to get a javascript script located inside the static folder. Here is my javascript code, file name is current_time.js, located inside the static folder. const displayTime = document.querySelector(".display-time"); // Time function showTime() { let time = new Date(); displayTime.innerText = time.toLocaleTimeString("en-US", { hour12: false }); setTimeout(showTime, 1000); } showTime(); Here is my Django template {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Personal Page</title> </head> <body> <div class= "heading-container"> <h1> Hi Thien </h1> </div> <div class="container"> <link rel="stylesheet" href="{% static 'style_time.css' %}"> <div class="display-date"> <h1>{% include 'personal_page_app/datetime.html' with date_time=date_time %}</h1> </div> <div class="display-time"></div> <script src="{% static 'current_time.js' %}"></script> </body> </html> and here is the error shown in the terminal (only js file, I can still get CSS to work) "GET /static/current_time.js HTTP/1.1" 404 1804 -
celery can not conect to redis in docker
i set all confing and see all question in stackoverflow but celery can not conect to redis and i get this error when i run docker-compose up in pycharm termal. consumer: Cannot connect to redis://127.0.0.1:6379/0: Error 111 connecting to 127.0.0.1:6379. Connection refused.. this is my docker-compose i try to connect all servis to main network. version: '3.3' services: redis: image: redis:7.2-alpine3.18 networks: - main db: container_name: postgres image: postgres:16 environment: - POSTGRES_DB=shop - POSTGRES_USER=comiser - POSTGRES_PASSWORD=Hosein67 networks: - main ports: - "5432:5432" restart: always volumes: - shop-data:/var/lib/postgresql/data app: build: context: . command: > sh -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000" container_name: app ports: - "8000:8000" volumes: - ./src:/src - ./data/web:/vol/web depends_on: - db restart: always networks: - main celery: container_name: celery command: celery -A shop worker -l INFO depends_on: - db - app - redis links: - redis build: context: . networks: - main networks: main: volumes: shop-data: this is my celery.py. i try best practic to confing celery from celery import Celery from datetime import timedelta import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'shop.envs.development') app = Celery('shop', broker='redis://redis:6379/0') app.autodiscover_tasks() app.config_from_object("django.conf:settings", namespace="CELERY") app.conf.result_backend = 'rpc://' app.conf.task_serializer = 'json' app.conf.result_serializer = 'pickle' app.conf.accept_content = ['json', 'pickle'] app.conf.result_expires = timedelta(days=1) app.conf.task_always_eager = False … -
How to generate an unique id for each Component of initial value of useState()
I want to create 30 empty Taskcard components at the beginning of the state my problem is that each taskcard has import React from 'react' import { useEffect, useState } from 'react' import { getTasks } from '../api/task.api' import { TaskCard } from './TaskCard' export function TaskLists() { const [tasks, setTasks] = useState(Array(30).fill({id: 1, title: 'title', description: 'description'})) useEffect(() => { async function loadTasks() { const res = await getTasks(); console.log(res.data) setTasks(res.data); } loadTasks(); },[]); const removeTask = (id) => { setTasks(tasks.filter(task => task.id !== id)); } return ( <div> {tasks.map((task) => ( <TaskCard key={task.id} task={task} onDelete={removeTask} /> ))} </div> ) } the same id how can I fix that? -
Is it possible to use variable in meta tag?
I am new at web dev. I am using Django, and I just wonder is it possible to use variable in meta description tag, Just like this: <meta name="description" content="{{blog_detail.context_1|slice:160|safe}}"> Will it still appear on search engines?