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

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 …

01.05.2024
Import Error while using python manage.py migrate command

Recently, i forked some source code from github to use as a basis for a project that i'm using to learn Django. As per the deployment instructions, i tried to use this command for the database in my terminal: python …

01.05.2024
What's the best approach to keeping data consistent in a django-based app used in parallel by three or four users?

I'm making a Django app using a postgresql database for a family who need to coordinate their grocery purchases. Say one person has on their mobile device a full list of the groceries and is in the supermarket, buying and …

01.05.2024
Django: Pass model ID to url using bootstrap modal

I'm trying to create a delete confirmation dialog using bootstrap 5 modals in my Django project. {% extends 'base.html' %} {% block content %} &lt;div class=&quot;col-md-6 offset-md-3&quot;&gt; {% if messages %} {% for message in messages %} &lt;div class=&quot;alert alert-success …

01.05.2024
Django URL 404 - 1 week spent debugging with GPT4, Claude luck. One specific function is just NOT resolving

Issue Summary: I'm facing an issue where the /LS/mark-text-responses/ URL in my Django application is not being found when an AJAX request is sent to the mark_text_responses view. This issue is occurring in the user-facing part of my application, specifically …

01.05.2024
A "django.core.exceptions.SuspiciousFileOperation" error is occurring despite setting everything up correctly

Currently attempting to serve all of my static files via whitenoise. Funnily enough, the function itself works a treat. It seeks out all the directories labelled static in all of my Django apps. However, why is Django consistently returning the …

01.05.2024
401 unauthorized Django Rest API Login

I'm having problems with my login API endpoint; it was working the last time I checked, now after working blindly for a few hours it doesn't work anymore and I don´t know what I've done. :) Register is working smoothly, …

01.05.2024
Deployment not found error on deploying django project on cpanel

I have an issue in deploying my django project to cpanel after creating the python setup on cpanel pointing my subdomain to the setup project .I get 404(deployment not found) error once i click the url how can i fix …

01.05.2024
Make authenticated and login work for multiple table other then auth User table django?

I have created hostTable model in hostlogin app and I want to use this table for login purpose for that i have created custom authenticate function because default authenticate() was working for auth user table only. Also login() is not …

01.05.2024
When we upload a selfie we get a 500 error [closed]

Def upload_selfie_document(self,cleardil_id,document_id,selfie_image): url = f&quot;{self.url}customers/{cleardil_id}/identifications&quot; print(url, &quot;url&quot;) selfie_image.seek(0) selfie_image = selfie_image.read() selfie_image_base64 = base64.b64encode(selfie_image).decode('utf-8') payload = json.dumps({ 'document_id': document_id, 'selfie_image': selfie_image_base64, }) # print(payload, &quot;payload&quot;) headers = { **self.headers , 'Content-Type': 'application/json'} print(headers, &quot;headers&quot;) try: response = requests.post(url, …

01.05.2024
No output in serializermethodfield()

I defined a serializermethodfield. My problem in displaying the output. When this method exists, the image field is empty for me. But if I delete this serializermethodfield, my image output will be correct. serilizer: class ArticleSerializer(serializers.ModelSerializer): user = serializers.StringRelatedField(read_only=True) image=serializers.SerializerMethodField() …

01.05.2024
Unable to start Django app, error related to what seems like a circular import?

I'm currently attempting to build my first django app, a resume website. I get this error when trying to start the app. &lt;class 'mainapp.admin.CertificateAdmin'&gt;: (admin.E108) The value of 'list_display[3]' refers to 'is_active', which is not a callable, an attribute of …

01.05.2024
Memcached-MemcacheIllegalInputError - Data values must be binary-safe: 'ascii' codec can't encode characters in position 2-5: ordinal not in range(128

I'm doing some tests with memcached on my django project to understand if I can get benefit of it. But I stuck at unicode character caching. I read many article about it but still could not understand how can I …

01.05.2024
Unit Test pipeline - Django Unit tests

I am working on a django project and it has 20+ apps in it which means I have to run tests of 20+ apps which includes 3000+ tests. So I decided to make subjobs in my pipeline and now running …