"Вопросы и ответы" Django и Python

03.05.2024
How to configure Daphne channels in Nginx server

I have a Django application that serves both http and websocket requests. The application is working properly in local. I have configured gunicorn and daphne services in Nginx server but Daphne service stops automatically within few seconds of starting even …

03.05.2024
`request` parameter in Django - HTTPRequest or WSGIRequest

All of Django documentation says request is of type django.http.request.HTTPRequest. I use NGINX -> Waitress WSGI in my development, and I see see request is django.core.handlers.wsgi.WSGIRequest which inherits directly from HTTPRequest. I understand that Django must always run under WSGI, …

03.05.2024
CSS loaded but failed to apply when using Django

These are my folders: folders my setting.py: STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'static' STATICFILES_DIRS = [ os.path.join(BASE_DIR,'blog','static'), ] my html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" …

03.05.2024
Why does my Django URL parameter result in an error?

I am a Django noob and this is my first post in stackoverflow. I need help in fixing my code. It was working well previously until I got an error regarding URL parameters as I tried adding an image for …

03.05.2024
Problem when styling django form fields upon errors

I have a bug I've been trying to fix for months but can't figure out. I'm building a website with Django. The site has a form, that, among other fields, has a field to input the name (called "nombre") and …

03.05.2024
Dockerizing django app with Nginx, gunicorn and docker-compose - data base connectivity issue

Amateur programer here. I usually can google my way out of every issue but I struggle with the huge diversity in set ups for docker (and honestly feel al ittle overwhelmed). I am aware the the biggest tutorials out there …

02.05.2024
Здравствуйте, начал изучать Django, CSS, HTML сейчас пробую создать шапку для сайта но CSS не применяется, что с этим можно сделать. Не судите строго [закрыт]

HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="../static/css/styles.css"> <title>Главная</title> </head> <body> <section> <header class="header"> <a href="#"> <img src="../static/images/ITGO_nazvanie_bezfona.png" class="logo"> </a> <nav> <ul> <li><a href="#">Главная</a></li> <li><a href="#">О нас</a></li> <li><a href="#">Контакты</a></li> <li><a href="#">Отзывы</a></li> </ul> </nav> …

02.05.2024
Override CSS when Debug=True

In order to avoid confusion between my production and development instance (where DEBUG = True), I'd like to override the CSS of my bootstrap Navbar in development (only) to show up e.g. in red instead of blue. What is the …

02.05.2024
Display a converted .docx to PDF file from Django REST framework backend in React frontend

I am running a django REST framework backend and a React frontend. I want to convert a .docx to PDF bytes in the backend and display it on the frontend but I keep getting Failed to load PDF Document error. …

02.05.2024
How to store my user-uploaded files on Digital Ocean Spaces using django-storages?

I am totally new to this. My Django app is run in Docker. My app allows users to upload files which are stored, followed by executing some functions on the file then generating a new file that the user can …

02.05.2024
Dynamic in the setting file

In the code below, I want to make it dynamic, for example using models, what should I do so that it is called in the settings file EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = False EMAIL_PORT = 465 EMAIL_USE_SSL = True EMAIL_HOST_USER …

02.05.2024
Django's filter clears foreign keys

In views.py, if I defining variable like clients_list = Clients.objects.all() and reading them in html like {{ clients_list }} then I get all data correct. But if I make filtering like clients_list = Clients.objects.filter(cli_account='123').values() then all the foreign keys are …

02.05.2024
Django Password form not loading

Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/5/password/ Using the URLconf defined in My_Blog_Project.urls, Django tried these URL patterns, in this order: admin/ account/ blog/ \[name='index'\] The current path, 5/password/, didn’t match any of these. You’re seeing this …

02.05.2024
Overwrite django rest response for return only pk

I'm trying to overwrite the response that is sended by django when create a new object. I need to return only the primary key of the created object instead the whole object. The function that I'm trying to overwrite is …

02.05.2024
How to get all relations for items in database model in Django

I'm trying to make an online business canvas. In this app, we have a database containing Project, User and 9 other models. All models are connected to one specific project. In the app, when user click on on of the …

02.05.2024
Forbidden (CSRF cookie not set.) Django and Angular

I am gettig error CSRF cookie not set here is my angular coponent.ts file sendMessage(nick:string) { const formData = new FormData(); this.nickname = nick; formData.append('nickname',this.nickname); const headers = new HttpHeaders({ 'X-CSRFToken':this.getCookies('csrftoken') }); this.http.post('http://127.0.0.1:8000/api/send/', formData, {headers:headers, withCredentials:true }).subscribe( (response:any) …

02.05.2024
Django async - OperationalError: the connection is closed - does not recover after db restart

I have something like the following coroutine, running by an async task: from django.db import OperationalError from my_app.models import User async def update_user_name(user: User): while True: try: user.name = coolname.generate_slug() await user.asave(update_fields=["name"]) except OperationalError: logging.exception( "DB operational error occurred, Wait …

02.05.2024
I cant implement AJAX in my django forum app to post a question

I have a forum app in which users can post their questions. I want to prevent page reloading each time a user post a comment for a question. I've tried implementing ajax but it didn't work. I've done this: this …

02.05.2024
Django Project Depolyment in Windows Server using Apache

I have installed python 3.12, Django, Apache, and tested all without pasting my project inside htdocs and that run. Now in htdocs, I have kept my project two folder core and myenv. Inside core main project files C:\Apache24\htdocs\core\core\wsgi.py httpd.conf. LoadFile …

02.05.2024
Django hidden field obligatory field error in double form in a view [duplicate]

I'm developing a Django page where a user fills out a lottery form. This data is stored in a MySQL database. Part of the functionality of the page is that the user can retrieve the form with the lottery data …

02.05.2024
Создание модели ManyToMany с обязательным полем

Есть модельки Городов и Туров. Тур может проходить по нескольким городам, в городе может проходить несколько туров. Логично - Many To Many. Но городу никто не запрещает существовать без тура, а вот тур 100% должен проходить как миниму по одному …

02.05.2024
Comments asigned correctly to answer objects but display in one answer objects

I'm building a question-and-answer platform to help companies understand their customers' needs. As you can see in the view_question views, I'm displaying an answer based on the question, and it is working perfectly. However, when displaying comments on the answer …

02.05.2024
How to tokenize a filed in elk?

I want to tokenize a field(text) in all documents(60k) of index(post) what is the best approach? GET /_analyze { "analyzer" : "standard", "text" : ["this is a test"] } need tokenized text for tag cloud in my Django app

02.05.2024
Why can't I deploy project (passenger wsgi)

When I change the passenger_wsgi.py to import <project_name>.wsgi application = <project_name>.wsgi.application I encounter with below error: Web application could not be started by the Phusion Passenger(R) application server. Please read the Passenger log file (search for the Error …

02.05.2024
Django : Locally save an instance of a Model

Using signals, I try to track the difference between the old instance of an object and the new instance when the Model is saved. I tried this : But logically …

02.05.2024
Integrating Microsoft Forms Authentication in Python Django: Troubleshooting Terminal Error

To integrate the Microsoft Forms authentication flow into my Python Django project for accessing various forms URLs and storing form details and responses, I'm employing the provided MS Forms authentication code within my project's backend. Additionally, I've configured my project …

02.05.2024
How do I write tests for my django-extensions cron job?

I have a cron job in my Django app that's defined as a MinutelyJob (from django-extensions). How do I write tests for the job? The module documentation is quite sparse, and doesn't tell me how to call …

02.05.2024
How can I customize Django Rest Framework documentation without using decorators?

I'm currently working on a Django project and utilizing Django Rest Framework (DRF) for building APIs. I've integrated drf-pectacular for automatic API documentation generation, but I'm finding that using decorators to customize the documentation is making my codebase messy. I'm …

02.05.2024
How to Handle and Send Various File Types (Images, Videos, Audios, PDFs, Documents) in a Django Chat App Using WebSockets and Django REST Framework

I'm working on a chat application where I need to handle and store various types of files such as images, videos, audios, PDFs, and documents using Django and Django REST framework. I have a WebSocket consumer with events like connect, …

02.05.2024
How to serve images from backend to frontend

I have an application with following three different docker containers:- Frontend(react) Back-end(django) Nginx for serving static files from frontend, I am trying to access nginx website in Kubernetes (minikube).from minikube service my-service all other data is being served from …

01.05.2024
How to implement preview page with files Django?

I have my News model: class News(models.Model): subject = models.CharField(max_length=30) text = models.TextField() created = models.DateTimeField(auto_now_add=True) I also have File model to store files and NewsFile model to connect models to each other: class File(models.Model): file = models.FileField( 'файл' …

01.05.2024
Google Authentication Not Appearing in Django Project

Body: I am trying to set up Google authentication in my Django project using django-allauth, but the Google login option is not appearing on my login page. I suspect I might be missing a configuration step or setting. I have …

01.05.2024
Speeding up Django's total record count calculation for a site with 20 million records MySQL

I've encountered a problem with my Django website. Given that my database contains more than 20 million records, the operation of counting the total number of data (count) becomes extremely slow. I am using the following queries: company_count_query = f"SELECT …

01.05.2024
Django reverse ForeignKey returns None

I have Student and Mark models in different apps of one project. # project/study # models.py class Mark(models.Model): ... student = models.ForeignKey( "students.Student", on_delete=models.PROTECT, related_name="marks", related_query_name="mark", ) # project/students # models.py class Student(models.Model): ... # views.py class StudentDetailView(DetailView): queryset = …

01.05.2024
Django admin inlines that has multilanguage field , TabbedTranslationAdmin does not work correctly

I have a django project, i use django-modeltranslation for translation fields. it have two model with one-to-many relation and i use django admin with inline for @admin.register(News) class NewsAdmin(nested_admin.NestedModelAdmin, TabbedTranslationAdmin): inlines = (NewsImageInline,) and image inline is: class NewsImageInline(nested_admin.NestedTabularInline,TranslationTabularInline …

01.05.2024
Nginx is active but I don't see static files

I have a django project. Settings.py: STATIC_URL = 'static/' STATIC_ROOT = 'static' MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' I've made collectstatic and everything worked fine. Now static folder on my server contains all the files. Nginx: <img …

01.05.2024
403 Error when renewing Let's Encrypt Certbot using Django and Apache. I have 6 days to renew

When running the certbot renew command I first change my firewall permissions to allow connections on port 80, I put Cloudflare into Development Mode, then I run the renewal command. However this time I received a 403 Forbidden error trying …

01.05.2024
Python Celery route task using hostname

I'm currently utilizing Celery for task management within my application, and I'm facing a challenge regarding task distribution to specific workers based on their unique hostnames. In my use case, I'm deploying multiple worker containers for a particular application. These …

01.05.2024
Why my Elasticsearch request doesn't show any hits?

I have dockerized Django project. I want to use Elasticsearch, so I choosed django-elasticsearch-dsl. My steps were: In my Django project's settings file (settings.py), I configured the Elasticsearch connection settings. ELASTICSEARCH_DSL = { 'default': { 'hosts': [&quot;http://localhost:9200&quot;], }, …

01.05.2024
CSRF verification failed. Request aborted. Origin checking failed

Here is my setup: localhost (Windows 11) - Nginx listening on port 80 and 443, 80 is NOT automatically redirected to 443 each proxy_passed to http://wsgi-server where wsgi-server=127.0.0.1:8080 - waitress_wsgi running as a service on port 8080 Here is …