Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery task result persistent strategy
I have a web server, a rabbitMQ server and two task processing servers in the system. Using Celery to manage the tasks. The web server needs to query the status of the tasks. Based on Celery's doc, I can choose database as result backend. In this case, should I set a database for the web server and another database for each task processing server or use one database for all these 3 servers? I also tried to use RPC as the backend, but each time the web server restarts, the status of tasks are "PENDING" after querying from AsyncResult. This is my configuration of Celery. CELERY_RESULT_BACKEND = 'rpc://' CELERY_RESULT_PERSISTENT = True CELERY_TRACK_STARTED = True CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_RESULT_EXPIRES = None Anyone can help? Thanks! -
django and s3 doesn't use X-Amz-Algorithm on ec2
I have recently deployed a test server for one of my projects on AWS EC2, utilizing an Ubuntu server with Gunicorn and Nginx. During testing on my localhost, the Django server functioned correctly. Specifically, I have a function generating presigned URLs for files to be accessed in my frontend. These presigned URLs include the X-Amz-Algorithm. However, upon obtaining the link from my EC2 server, I noticed that it incorporates a form of signing, including AWSAccessKeyId, a Signature, and an "Expires" parameter. But not the presigned link with the X-Amz-Algorithm My objective is to achieve the same presigned URL functionality on the EC2 server. How can I accomplish this? settings.py (S3 Bucket Config #S3 BUCKETS CONFIG AWS_ACCESS_KEY_ID = '*************' AWS_SECRET_ACCESS_KEY = '*******************************' AWS_STORAGE_BUCKET_NAME = 'project-backend' AWS_S3_SIGNATURE_VERSION = 's3v4' S3_USE_SIGV4 = True AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' #STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_S3_ADDRESSING_STYLE = 'virtual' AWS_S3_ENDPOINT_URL = 'https://s3.eu-central-1.amazonaws.com' AWS_S3_REGION_NAME = 'eu-central-1' -
view on the django server giving 404 error
I have created 2 functions in a views file and the second function is showing a 404 error. Below is the code for the urls and views from django.contrib import admin from django.urls import path, include from mysite.views import current,hello urlpatterns = [ path('',current,name='time'), path('',hello,name='hello'), ] import datetime from django.http import HttpResponse def hello(request): return HttpResponse("Hello world. I Love you alot.Did you not know?") def current(request): now = datetime.datetime.now() html = "<html><body>It is now %s.</body></html>" % now return HttpResponse(html) When i run the server I can see the time output but when i cant see hello world on http://127.0.0.1:8000/hello. As in I have 2 views defined but I can see one view and not the second one. Any suggestions? -
AttributeError: 'EditViewDevis' object has no attribute 'render'
Need help again. My aim is to create a quote and allow the user to add items dynamically. I'm having trouble validating the grouped form: 'EditViewDevis' object has no attribute 'render'. My createView class and updateView class are not working. I got always this error: AttributeError at /nrn/ebe907fe-9711-4657-9319-4b7cb7873ff6/editdevis/. 'EditViewDevis' object has no attribute 'render' I thought the error was due to my form_valid function, What did I do wrong? Any ideas how to resolve this error? Here's my code: forms.py from django import forms from .models import Article, Customer, Devis class ClientForm(forms.ModelForm): class Meta: model = Customer fields = ['name', 'gerant', 'siret', 'email', 'phone', 'address'] class DevisForm(forms.ModelForm): class Meta: model = Devis fields = ['customer', 'paid', 'comments'] labels = { "customer": "Nom Client", "paid": "Paid ? ", "comments": "Comments", } class ArticleForm(forms.ModelForm): class Meta: model = Article fields = ['designation', 'category', 'quantity', 'unit', 'prix_unit', 'devise', ] ArticleFormSet = forms.inlineformset_factory(Devis, Article, form=ArticleForm, fields=['designation', 'quantity', 'prix_unit', ], extra=5, can_delete=True, can_delete_extra=True) views.py from django.shortcuts import redirect, render from django.urls import reverse_lazy from django.views.generic.detail import DetailView from django.views.generic import ListView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.contrib.auth.mixins import LoginRequiredMixin from nrn_app.forms import ClientForm, DevisForm, ArticleForm, ArticleFormSet from nrn_app.models import Article, Customer, Devis class … -
Export Django logs to Azure AppInsights with OpenTelemetry
I'm trying to use OpenTelemetry to send my Django project logs to Azure Application Insights. According to my research, it is possible to do it in OpenCensus by adding the following configuration. Is it possible to do it in OpenTelemetry? If it is what can I use instead of this class 'opencensus.ext.azure.log_exporter.AzureLogHandler'? My goal is to connect my all logs inside my django app with azure by changing only settings of logging. # Set the AppInsights Key as an env variable so it can be used by the logging system os.environ['APPLICATIONINSIGHTS_CONNECTION_STRING'] = 'InstrumentationKey=XXXXXXXXXXXXXXXXXXXXXXX' LOGGING = { 'disable_existing_loggers': True, #False, #<-- if true then make sure that you have a 'django' and '' logger 'filters': { "require_debug_false": { '()': 'django.utils.log.RequireDebugFalse', }, 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'formatters': { 'simple': { 'format': '[%(asctime)s] %(levelname)s %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S' }, 'verbose': { 'format': '[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S' }, 'azure_verbose': { 'format': '[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s traceId=%(traceId)s spanId=%(spanId)s', 'datefmt': '%Y-%m-%d %H:%M:%S' }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'level': 'INFO', 'filters': ['require_debug_true'], 'formatter': 'verbose' }, 'azure':{ 'level': 'INFO', 'filters': ['require_debug_false'], 'class': 'opencensus.ext.azure.log_exporter.AzureLogHandler', 'formatter': 'azure_verbose' }, }, 'loggers': { 'mylogger': { "handlers": [ "azure", "console", ], }, 'django': { 'handlers': … -
Having difficulty with datePicker in python-django project
The django web-app project I am working on has numerous apps. I am creating a new app with forms. The forms use 'datePicker'. The datePicker class is referenced in an 'attrs{}' block. On my new form I have exactly the same format as forms used in other parts of the project, but the datePicker refuses to display. The application uses Bootstrap 3 and javascript/css, but neither of the latter are referenced in the template. Code is below. I am relatively new to django, and it is not clear to me why this doesn't work. Some part of the is missing, but I can't identify it. What am I missing in this code? Best, Joe White template.html: {% extends 'common/base.html' %} {% load menu_tags %} {% load static %} {% block page_title %}Add New Project{% endblock %} {% block content %} Add New Project {% csrf_token %} {% load bootstrap3 %} {# Display django.contrib.messages as Bootstrap alerts #} {% bootstrap_messages %} {% bootstrap_form form layout="horizontal" %} {% buttons layout='horizontal' %} <button type="submit" class="btn btn-primary"> {% bootstrap_icon "star" %} Submit </button> {% endbuttons %} back to list $(document).ready(function () { $('.datepicker').datepicker({ format: 'yyyy-mm-dd', autoclose: true, }); $('.timepicker').timepicker({ format: 'hh:ii:ss', autoclose: true, showMeridian: … -
Django cannot get values from ManToMany
I have a problem. I write the little blog I have a post model and if I create a new post it has to send a link of the new post to the telegram group. The post has telegram_chat field ManyToMany when I save the post it runs the signal and must send the link, but when I want to get chat ID the query is empty. Sorry for my bad English. class Post(models.Model): """Post Model""" hash = models.UUIDField(default=uuid.uuid4, editable=False) title = models.CharField("Title", max_length=255) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE) published_date = models.DateTimeField(auto_now_add=True) category = models.ForeignKey('Category', on_delete=models.CASCADE) tags = TaggableManager() image = models.ImageField(upload_to='post_images/', blank=True, null=True) content = RichTextUploadingField() telegram_chats = models.ManyToManyField('TelegramChat', related_name='posts', blank=True) def __str__(self): return f"{self.title}" def get_absolute_url(self): return reverse("main:post_detail", args=[self.slug]) def save(self, *args, **kwargs): if str(self.hash) not in self.slug: self.slug = f"{self.slug}-{self.hash}" super().save(*args, **kwargs) @receiver(post_save, sender=Post) def send_telegram_message(sender, instance, **kwargs): bot_token = 'YOUR_TELEGRAM_BOT_TOKEN' # Check if the post has associated chat IDs if instance.telegram_chats.exists(): chat_ids = instance.telegram_chats.values_list('chat_id', flat=True) bot = Bot(token=bot_token) # You may customize the message format as needed message = f"New post: {instance.title}\n\n{instance.content}\n\nLink: https://yourdomain.com/path-to-post/{instance.id}/" if instance.image: image_path = instance.image.path for chat_id in chat_ids: bot.send_photo(chat_id=chat_id, photo=InputFile(image_path), caption=message) else: for chat_id in chat_ids: bot.send_message(chat_id=chat_id, text=message) -
Proper way of react native - django authentication
What is the proper way of creating authentication in react native Login component with Django CBV Login(LoginView). Do I need to write API using DRF? Or can I just fetch POST request to .../login with username and password as body? -
Heroku and Django giving a 500 error when Debug is not set to False
I have been following and checking every forum post, setup instruction and video I can find. I've been checking git hub repos and comparing to my code. I cannot get my Django application to run on Heroku with DEBUG set to false and not get a 500 server error. So I wanted to reach out to ask two questions: How critical is it that I have DEBUG set to False? I have seen that it could expose information but the application is more of an online resume/portfolio site ("Hey, this is some information about me and here are some small apps I've made") Could someone take a look at my code and see what I am missing ( https://github.com/seanhayes13/codingHavoc )? I'm not using any databases for this part of the app Thank you If DEBUG is set to False, 500 error. If DEBUG is set to True, everything runs fine. I have the Heroku recommended if block setting the ALLOWED_HOSTS to ['*']. All of the static files (style sheets, pages and images) are loading fine -
how to make the session lifetime counted from the start of the page load, checked every minute and not disrupted by post request?
session life settings SESSION_COOKIE_AGE=120 (2 minutes) now a question, at the first rendering of the page of the template confirm_email.html the form of code input from 6 fields is loaded, if you do not enter the code (inactivity) and wait, then every minute will be checked to send a get request from the script check_session.js every minute in the view CheckSession and it will give json response back and 30 seconds before the end of session life will trigger the script timer.js and after the end of 2 minutes the user will be redirected to the main page - everything is fine here!!!!. And if at the first rendering of the confirm_email.html template page (for example, the page loaded at 18:00:00) the form of code input from 6 fields is loaded, and suppose you enter an incorrect code after 30 seconds (at 18:00:30), then a post request is sent to the ConfirmEmail view and the check_session script. js will send a request to the CheckSession view from this post request time, i.e. the script will send a request at 18:01:30, i.e. a minute from the post request, but not from the time the page loaded at 18:00:00. Where it is … -
How to connect a react native app without docker to a django docker container?
I have a react native app for web configured. And I have a django app for the backend. I can connect this two apps with each other. But now I have dockerized the django app. But not the react app. And if I run the react app with the running django docker app. I get this error if I try to login from the react app: authentication.service.js:32 POST http://192.168.1.135:8000/api/user/token/ 400 (Bad Request) So this is my docker compose.yml file: version: "3.9" name: dwl_backend services: app: image: crdierenwelzijn2.azurecr.io/web1 build: context: C:\repos\dierenwelzijn\dwl_backend dockerfile: Dockerfile args: DEV: "true" command: - sh - -c - "python manage.py wait_for_db && python ./manage.py migrate && python ./manage.py runserver 0:8000" depends_on: db: condition: service_started required: true environment: DB-PORT: "5432" DB_HOST: db DB_NAME: name DB_PASS: pass DB_USER: user DEBUG: "1" DJANGO_ALLOWED_HOSTS: localhost 127.0.0.1 [::1] SECRET_KEY: django-insecure-kwuz7%@967xvpdnf7go%r#d%lgl^c9ah%!_08l@%x=s4e4&+(u networks: default: null ports: - mode: ingress target: 8000 published: "8000" protocol: tcp volumes: - type: bind source: C:\repos\dierenwelzijn\dwl_backend\DierenWelzijn target: /app bind: create_host_path: true db: environment: POSTGRES_DB: db POSTGRES_PASSWORD: password POSTGRES_USER: user image: postgres:13-alpine networks: default: null volumes: - type: volume source: dev-db-data target: /var/lib/postgresql/data volume: {} networks: default: name: dwl_backend_default volumes: dev-db-data: name: dwl_backend_dev-db-data and my login method for react looks … -
data inserted in email filed is not broadcasted properly to backend, request.is_ajax() returns false
I am following a tutorial about an ecommerce app. The app is made with Django 4, and ajax is used in the frontend. I am currently working on a contact page. compiling the form and submiting should trigger a jquery-confirm popup displaying message "thank you a lot!". This is obtained not by simple javascript submit form button , but via a custom ajax logic. The problem is that, when I compile and submit the form, the form is validated, the javascript is loaded, but the email data is not transmitted properly (I get None), and in views.py, request.is_ajax() returns None. This is what happens when I fill up all the form fields and click on submit: backend: contact_form.cleaned_data {'fullname': 'John Doe', 'email': None, 'content': 'uvyibuon'} no ajax in this request: <WSGIRequest: POST '/contact/'> [20/Nov/2023 16:21:15] "POST /contact/ HTTP/1.1" 200 16035 frontend: Navigated to http://127.0.0.1:8000/contact/ contact/:255 readyyyy contact/:261 before submit Here are my files mainapp_ecommerce/urls.py urlpatterns = [ ... path('contact/', contact_page, name="contact"), ] mainapp_ecommerce/views.py from .forms import ContactForm def contact_page(request): contact_form = ContactForm(request.POST or None) context = { "title":"Contact", "content":"Welcome to the contact page!", "form": contact_form, "brand":"new brand name", } if contact_form.is_valid(): print("contact_form.cleaned_data", contact_form.cleaned_data) if request.is_ajax(): # asinchronous javascript and xml … -
Implementing Multi-Tenant Architecture in Django with Shared and Unique Models
I am working on a large, multi-tenant Django project primarily utilizing Django's ORM capabilities. The project involves a PostgreSQL database where each schema represents a different tenant. Django commands are used to insert data into the db, import data from the db and perform some calculation and then send it back to the db, and delete certain data from the database. In each schema, several tables and views are designated for Business Intelligence (BI) tools. Many of my Django models are shared across tenants (in structure, not data), but each tenant should also have unique models, which is where my problem stems from. I want to be able to implement unique models per tenant that can have foreign keys to the common models of that tenant. Implementing these unique tenant models in Django has proven to be difficult and I am aware that this is an unconventional use case for Django. I would like to keep data separate, so using a single schema with a tenant identifier column isn't a preferred option. And as some tables will be exposed I'd prefer to keep power over the table names and not go to general tables and general fields where the data … -
watchlist in Django
This code adds the product to the watchlist before making some changes, and the product could be removed from the list by clicking on the Remove button on the list page. But Product information wasn't displayed on the watchlist page. The link for more information on the watchlist page didn't work and gave an error. After adding the product, the Add to Watchlist button on the product introduction page wasn't changed to Remove. I came across this error while solving these bugs. When you click on add button, it gives this error. Page not found (404) No Watchlist matches the given query. Request Method: GET Request URL: http://127.0.0.1:8000/add/1/?productid=1 Raised by: auctions.views.add Using the URLconf defined in commerce.urls, Django tried these URL patterns, in this order: admin/ [name='index'] login [name='login'] logout [name='logout'] register [name='register'] product_detail/<int:product_id>/ [name='product_detail'] watchlist/<str:username>/ [name='watchlist'] add/<int:productid>/ [name='add'] The current path, add/1/, matched the last one. models.py class User(AbstractUser): pass class List(models.Model): choice = ( ('d', 'Dark'), ('s', 'Sweet'), ) user = models.CharField(max_length=64) title = models.CharField(max_length=64) description = models.TextField() category = models.CharField(max_length=64) first_bid = models.IntegerField() image = models.ImageField(upload_to="img/", null=True) image_url = models.CharField(max_length=228, default = None, blank = True, null = True) status = models.CharField(max_length=1, choices= choice) active_bool = models.BooleanField(default … -
I can't install pillow in my venv with pip install Pillow
I can't install pillow in my venv with pip install Pillow. This is the error message that I got. Building wheel for Pillow (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for Pillow (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [199 lines of output] running bdist_wheel running build running build_py creating build creating build\lib.win32-cpython-39 creating build\lib.win32-cpython-39\PIL copying src\PIL\BdfFontFile.py -> build\lib.win32-cpython-39\PIL copying src\PIL\BlpImagePlugin.py -> build\lib.win32-cpython-39\PIL copying src\PIL\BmpImagePlugin.py -> build\lib.win32-cpython-39\PIL copying src\PIL\BufrStubImagePlugin.py -> build\lib.win32-cpython-39\PIL copying src\PIL\ContainerIO.py -> build\lib.win32-cpython-39\PIL copying src\PIL\CurImagePlugin.py -> build\lib.win32-cpython-39\PIL copying src\PIL\DcxImagePlugin.py -> build\lib.win32-cpython-39\PIL copying src\PIL\DdsImagePlugin.py -> build\lib.win32-cpython-39\PIL copying src\PIL\EpsImagePlugin.py -> build\lib.win32-cpython-39\PIL copying src\PIL\ExifTags.py -> build\lib.win32-cpython-39\PIL copying src\PIL\features.py -> build\lib.win32-cpython-39\PIL copying src\PIL\FitsImagePlugin.py -> build\lib.win32-cpython-39\PIL copying src\PIL\FliImagePlugin.py -> build\lib.win32-cpython-39\PIL copying src\PIL\FontFile.py -> build\lib.win32-cpython-39\PIL copying src\PIL\FpxImagePlugin.py -> build\lib.win32-cpython-39\PIL copying src\PIL\FtexImagePlugin.py -> build\lib.win32-cpython-39\PIL copying src\PIL\GbrImagePlugin.py -> build\lib.win32-cpython-39\PIL copying src\PIL\GdImageFile.py -> build\lib.win32-cpython-39\PIL copying src\PIL\GifImagePlugin.py -> build\lib.win32-cpython-39\PIL copying src\PIL\GimpGradientFile.py -> build\lib.win32-cpython-39\PIL copying src\PIL\GimpPaletteFile.py -> build\lib.win32-cpython-39\PIL copying src\PIL\GribStubImagePlugin.py -> build\lib.win32-cpython-39\PIL copying src\PIL\Hdf5StubImagePlugin.py -> build\lib.win32-cpython-39\PIL copying src\PIL\IcnsImagePlugin.py -> build\lib.win32-cpython-39\PIL copying src\PIL\IcoImagePlugin.py -> build\lib.win32-cpython-39\PIL copying src\PIL\Image.py -> build\lib.win32-cpython-39\PIL copying src\PIL\ImageChops.py -> build\lib.win32-cpython-39\PIL copying src\PIL\ImageCms.py -> build\lib.win32-cpython-39\PIL copying src\PIL\ImageColor.py -> build\lib.win32-cpython-39\PIL copying src\PIL\ImageDraw.py -> build\lib.win32-cpython-39\PIL copying src\PIL\ImageDraw2.py -> build\lib.win32-cpython-39\PIL copying src\PIL\ImageEnhance.py -> build\lib.win32-cpython-39\PIL copying src\PIL\ImageFile.py -> build\lib.win32-cpython-39\PIL copying src\PIL\ImageFilter.py -> build\lib.win32-cpython-39\PIL copying src\PIL\ImageFont.py -> build\lib.win32-cpython-39\PIL copying … -
How do I implement the place bid functionality with django
I have really tried different methods in order to implement a place bid functionality, but it seems not to be working out, pls I need help. Here's my code: views.py def place_bid(request): if request.method == "POST": #create and save the bid value item_id = request.POST("item_id") listing_item_id = get_object_or_404(Listing, pk=item_id) bid_value = request.POST("bid_value") Bids.objects.create(bidder=request.user, bid_price=bid_value, listing_id=listing_item_id) listing_item_id.initial_price = bid_value listing_item_id.save() return render(request, "auctions/listing_view.html", { "price": listing_item_id, "message": "Your bid has been placed successfully" }) models.py class Listing(models.Model): product_name = models.CharField(max_length=64, verbose_name="product_name") product_description = models.TextField(max_length=200, verbose_name="product description") product_image = models.ImageField(upload_to="images/", verbose_name="image", blank=True) is_active = models.BooleanField(blank=False, default=True) initial_price = models.DecimalField(decimal_places=2, max_digits=6, null=True, blank=True) owner = models.ForeignKey(User, related_name="auction_owner", on_delete=models.CASCADE, default=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="category") def __str__(self): return self.product_name class Bids(models.Model): bidder = models.ForeignKey(User, null=True, on_delete=models.CASCADE) bid_price = models.DecimalField(decimal_places=2, max_digits=6, null=True, blank=True) listing_id = models.ForeignKey(Listing, null=True, on_delete=models.CASCADE) def __str__(self): return self.bid_price templates <div class="right"> <h3>{{ listing.product_name }}</h3> <h4>${{ price.initial_price }}</h4> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. </p> <div class="btn-groups"> {% if listing in watchlist_items %} <a href="{% url 'remove_from_watchlist' item_id=listing.id %}" class="fas fa-shopping-cart"><button type … -
Is there a common way to deploy a Django application with Windows Server ISS?
I deployed a Django application on a Windows Server 2016 of a customer, but he wants it deployed through ISS, which as a Linux person i had no idea what it was. So I searched for it, and how to deploy a Django application using ISS. The best content I could find about this was on Matt Woodward post from years ago. Still it didn't work as expected, and I can't find where the problem is. specs: django 4.2 wfastcgi 3.0 python 3.11 windows server 2016 folder structure: Steps This was my steps trying to get it working. Setting up dependencies 1 - Installed Python and ISS on the OS; 2 - Created virtual environment and installed project requirements + wfastcgi; 3 - Tested Django application - working fine with runserver; Configure FastCGI 1 - As Full path value: C:\Users\one\Documents\app\myApplication\virtualenv\Scripts\python.exe 2 - As arguments value: C:\Users\one\Documents\app\myApplication\virtualenv\Lib\site-packages\wfastcgi.py 3 - For environment variables: DJANGO_SETTINGS_MODULE: core.settings PYTHONPATH: C:\Users\one\Documents\app\myApplication\core WSGI_HANDLER: django.core.wsgi.get_wsgi_application() Configure IIS Site 1 - As Content Directory/Physical path: C:\Users\one\Documents\app\myApplication\core 2 - For Handler Mappings: Request path: * Module: FastCgiModule Executable: C:\Users\one\Documents\app\myApplication\virtualenv\Scripts\python.exe|C:\Users\one\Documents\app\myApplication\virtualenv\Lib\site-packages\wfastcgi.py Now when I go to http://localhost:81 I receive this page Now I don't know if there's some problem with configs or … -
How to Convert and Save Uploaded Video File to M3U8 Format Using Django?
I'm working on a Django project where users can upload video files, and I need to convert these uploaded videos into the M3U8 format for streaming purposes. Could anyone provide guidance or a code example on how to achieve this conversion and save the resulting M3U8 file using Django? I'm open to using any libraries or tools that could simplify this process. Thanks in advance for any help or suggestions! # models.py class Video(AdvertisementModelMixin): text = models.CharField(max_length=255) description = models.TextField() image = WEBPField( verbose_name='Image', upload_to=video_folder, ) video = models.FileField( upload_to='video/', validators=[FileExtensionValidator( allowed_extensions=[ 'MOV', 'avi', 'mp4', 'webm', 'mkv', 'm' ]) ] ) skip_duration = models.PositiveSmallIntegerField( null=True, blank=True, validators=[ MinValueValidator(3), MaxValueValidator(20) ] ) def __str__(self): return f"{self.id}. {self.text}" class Meta: verbose_name = "video" # views.py class VideoViewSet(ModelViewSet): queryset = (Video.objects.all() .prefetch_related("devices") .prefetch_related("provinces")) serializer_class = VideoSerializer pagination_class = AdsPagination ads_type = "video" -
Websocket not receiving messages from Django Channels
I'm currently working on a project using Django Channels for WebSocket communication. However, I'm facing an issue where the WebSocket connection is established successfully, but messages are not being received on the client side. WebSocket connection is established without errors. I've verified that the Django Channels server is sending messages. However, the client-side WebSocket does not seem to receive any messages my asgi.py import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from channels.security.websocket import AllowedHostsOriginValidator import transposys_main.routing import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'transposys_main.settings') django.setup() application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AllowedHostsOriginValidator( URLRouter( transposys_main.routing.websocket_urlpatterns ) ), }) consumer.py import json from channels.generic.websocket import AsyncWebsocketConsumer import logging logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) class DepartmentCreatedConsumer(AsyncWebsocketConsumer): async def connect(self): logger.info(f"WebSocket connected: {self.channel_name}") await self.accept() async def disconnect(self, close_code): logger.info(f"WebSocket disconnected: {self.channel_name}") async def receive(self, text_data): logger.info(f"WebSocket message received: {text_data}") try: text_data_json = json.loads(text_data) message_type = text_data_json.get('type') message = text_data_json.get('message') if message_type == 'department.created': logger.info(f"New Department: {message}") except json.JSONDecodeError as e: logger.error(f"Error decoding JSON: {e}") async def department_created(self, event): try: logger.info(f"Department created event received: {event['message']}") await self.send(text_data=json.dumps({ 'type': 'department.created', 'message': event['message'], })) except Exception as e: logger.error(f"Error sending WebSocket message: {e}") routing.py: from django.urls import re_path from .consumers import DepartmentCreatedConsumer websocket_urlpatterns … -
Django Admin Recent Actions in a react Js website
I want to know if I can use the logs that are displayed on Django Admin in a custom React Js Admin Panel. I have a requirement which is to show all recent changes done by any user. Django admin already has that Recent Actions widget. How can I use that data and serialize it in some API/View I tried using django-simple-history but it shows specific history for a specific object. I want a complete generic log list -
Django: Implementing fund reversal in post_save signal
I'm using django post_save signal to update the status of a transaction based on whether funds are received. The problem is that funds_received is not working as expected. The issue is in using .exists(), because, it checks if there is any account with the exact balance equal to the transaction amount. If anyone has suggestions or knows of a better way for checking if funds are received, I would greatly appreciate the guidance. from django.db.models.signals import post_save from django.dispatch import receiver from .models import Transaction, Account @receiver(post_save, sender=Transaction) def transaction_status(sender, instance, created, **kwargs): if created: amount = instance.amount sender_account = instance.sender.account receiver_account_number = instance.account_number receiver_account = account.objects.get(account_number=receiver_account_number) check_if_funds_received = Account.objects.filter(account_balance=amount).exists() funds_received = check_if_funds_received if funds_received: instance.status = 'Reversed' instance.save() else: instance.status = 'Reversed' instance.save() # return funds to sender sender_account.account_balance += amount sender_account.save() My Models: class Account(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) account_number = models.BigIntegerField(unique=True) account_balance = models.DecimalField(max_digits=12, decimal_places=6) account_id = models.CharField(max_length=15, unique=True) user_qrcode = models.ImageField() first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) account_status = models.CharField(max_length=50, choices=ACCOUNT_STATUS) pin = models.CharField(max_length=4) def __str__(self): return str(self.user.first_name) class Transaction(models.Model): STATUS = ( ('Success', 'Success'), ('Reversed', 'Reversed') ) sender = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='sender') receiver = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='receiver') amount = models.DecimalField(max_digits=12, decimal_places=6) account_number = models.BigIntegerField() first_name … -
stocks quantity only decreasing not increasing
after updating the data, the stocks. Quantity is only decreasing does not matter if we only increase the quantity or decrease the quantity. I want when we update the data the stocks quantity will also be updated for ex-, we increase 2 points then only 2 quantities will be decreased. suppose we have 5 unit of shoes in cart and stocks have 10 quantities left so if we increase 2 so the total quantity will in cart 7 and left quantity in stocks will be 8 quantity shoes and if we decrease 3 quantities so the total quantity in cart will be 4 and total quantity in stocks are 11. for ex-, we increase 2 points then only 2 quantities will be decreased. suppose we have 5 unit of shoes in cart and stocks have 10 quantities left so if we increase 2 so the total quantity will in cart 7 and left quantity in stocks will be 8 quantity shoes and if we decrease 3 quantities so the total quantity in cart will be 4 and total quantity in stocks are 11. I just need the logic. hope you guys get that! ================================================================================== views.py > def supplier_edit(request, id): try: … -
problem loading static files with django nginx gunicorn on AWS lightsail
I installed my django app on lightsail, on a ubuntu server from scratch. The webpage is working ok but the static files are not loading. I read about adding some info on the web_app.conf (cht_web.conf) and it looks like this: `server { listen 80; server_name xxx.xxx.xxx.xxx; location / { include proxy_params; ` proxy_pass http://localhost:8000/; } location /static/ { autoindex on; root /home/ubuntu/cht_web/cht_web/static/; } I´m not sure if i have to install Supervisor, so I´ve not installed it yet, im running gunicorn with: gunicorn cht_web.wsgi --bind 0.0.0.0:8000 --workers 4 and the log is: \[2023-11-20 12:47:13 +0000\] \[38774\] \[INFO\] Starting gunicorn 21.2.0 \[2023-11-20 12:47:13 +0000\] \[38774\] \[INFO\] Listening at: http://0.0.0.0:8000 (38774) \[2023-11-20 12:47:13 +0000\] \[38774\] \[INFO\] Using worker: sync \[2023-11-20 12:47:13 +0000\] \[38775\] \[INFO\] Booting worker with pid: 38775 \[2023-11-20 12:47:13 +0000\] \[38776\] \[INFO\] Booting worker with pid: 38776 \[2023-11-20 12:47:13 +0000\] \[38777\] \[INFO\] Booting worker with pid: 38777 \[2023-11-20 12:47:13 +0000\] \[38778\] \[INFO\] Booting worker with pid: 38778 my settings.py static config is: STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'staticfiles' #representa la raiz del directorio STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), my base dir is: BASE_DIR = Path(__file__).resolve().parent.parent (maybe the extra.parent is an issue, but it loads media!) Its in debug … -
Django app, how to download all files asociated a project?
I'm trying to create a definition in my view.py file to download all files associated with a project. This time I'm using the python ZipFile package to zip all the files, but I'm having a lot of trouble finding the right code My Models class File(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) project_slug = AutoSlugField(populate_from='project', always_update=True) pub_date = models.DateTimeField(auto_now_add=True) def directory_path(instance, filename): return 'files_project/project_{0}/{1}'.format(instance.project_slug, filename) upload = models.FileField(upload_to=directory_path) My view def DownloadAllFilebyProject(request, id): project = Project.objects.get(id=id) files = project.file_set.all() zf = zipfile.ZipFile(os.path.join(settings.MEDIA_ROOT, 'files_project/project_{0}/'.format(project.slug), 'allfile.zip'), 'w') for file in files: zf.writestr(os.path.join(settings.MEDIA_ROOT, 'files_project/project_{0}/'.format(project.slug)), file) zf.close() return HttpResponse(print(zf)) My Template <a href="{% url 'apppro:DownloadAllFilebyProject' project.id %}" class="btn btn-warning float-right" method="get"> descargar todos los archivos</a> The error TypeError at /downloadallzipfiles/13 object of type 'File' has no len( -
POST data not registering in Django custom admin action with intermediate form
I am trying to add a custom admin action do my Django model. The goal is to show a form to the user where they can select a group which will get linked to all my selected candidates. My issue is that the code works in the render part, and the form is shown. However when I click apply my code never enters the if 'apply' in request.POST condition. It also seems the code is never called a second time. Here are the relevant parts of my code: CandidateAdmin.py from django.contrib import admin from django.utils.safestring import mark_safe from exem_poi.models import Candidate from django.urls import reverse from django.utils.html import format_html from django.http import HttpResponseRedirect from django.shortcuts import render from exem_poi.views.utils import convert_to_wgs84 from exem_poi.models.Candidate import Group @admin.register(Candidate) class CandidateAdmin(admin.ModelAdmin): list_display = ('batiment_construction_id', 'emitters_100m', 'height', 'display_owners', 'is_public') list_filter = ('emitters_100m', 'height', 'is_public') search_fields = ('batiment_construction_id', 'emitters_100m', 'height', 'is_public') readonly_fields = ('centroid',) actions = ['assign_to_group'] def assign_to_group(self, request, queryset): # Handle the form submission for assigning candidates to a group print(request.POST) if 'apply' in request.POST: group_id = request.POST.get('group_id') group = Group.objects.get(id=group_id) for candidate in queryset: group.candidates.add(candidate) self.message_user(request, f'Successfully assigned candidates to group {group.name}') return HttpResponseRedirect(request.path) groups = Group.objects.all() context = {'groups': groups, 'candidates': …