Django and Python "Questions and answers"

14.11.2023
Websocket disconnects after hadnshaking Django Channels

I am coding a real time chat using django and channels My code consumers.py: class ChatConsumer(WebsocketConsumer): def connect(self): room_hash = self.scope["url_route"]["kwargs"]["room_hash"] #self.room_group_name = self.scope["url"]["kwargs"]["hash"] self.send(text_data = json.dumps({ 'type':'room_hash', 'hash': room_hash })) chat_room = Room.objects.get(hash = hash) print(chat_room) self.accept({ 'type': 'websocket.accept' …

14.11.2023
How do I create an emptry LineString in GeoDjango

I am having a problem with the latest version of the GeoDjango extensions in Django version 4.2.6 when I create an empty LineString. The same code is behaving differently than it did in version 4.0.10. The default seems to have …

14.11.2023
JavaScrip Gmail API code not working on Django template

Im testing a simple Gmail API integration to my django app and its not working. Im trying to migrate the javascript example from the Google docs website, and migrate it to my django proyect, yet doesnt work, …

14.11.2023
Async function isn't behaving as intended in Django websocket consumer

I'm having some trouble with my django consumer for a game I'm making. The problem arises specifically when calling handle_timer in handle_round() from the loop in start_game(), update_timer isn't called until after the loop finishes. Why? Can you help me …

14.11.2023
Request Issue With Django On AWS

I have recently been working on developing an application that can answer questions from documents. It has been going well so far, as the project itself works locally, and answers questions with great accuracy. However, when I brought this project …

14.11.2023
How would I handle another POST request on my site

Hello in my login site I have a form that sends a POST request on submit. this is how I handle the forms POST request in my view def SignUp(request): if request.method == 'POST': stuff goes here else: form = …

14.11.2023
Django / Pytest / Splinter : IntegrityError duplicate key in test only

I know it's a very common problem and I read a lot of similar questions. But I can't find any solution, so, here I am with the 987th question on Stackoverflow about a Django Integrity error. I'm starting a Django …

14.11.2023
Django: General Questions about API views

I am working on a project and I have a front-end in React which makes some basic CRUD axios calls to the Django server. I am trying to figure the best way to administer my Django views to receive and …

13.11.2023
Django - Update database entry if it exists or insert new entry combining two tables together (models)

I have an app that merges two excel files into one (data from Students and data from their subjects' grades). Therefore, one table for students and one for the grades. Here is what my models.py looks like: models.py …

13.11.2023
Unexpected tag on my dom object when I am working with js

Function makeList(response) { const div = document.querySelector( ".main__collection-swiper-wrapper"); const ul = document.createElement("ul"); ul.className = "main__collection-list main__session-list swiper-slide "; response.sessions.forEach((session) => { const li = document.createElement("li"); li.className = "main__collection-item main__session-item"; const element = session.movie_id ? `<a href="http://127.0.0.1:8000/detail/${session.movie_id}" class="main__collection-link main__session-link"> <figure class="main__collection-box …

13.11.2023
Django authenticate dont work for Custom User

In my django-rest project , I am trying to make a login autentication using knox But in my views , even when the user exists and I provide the username and password correctly, serializer.is_valid(raise_exception=True) always returns False …

13.11.2023
Gunicorn daemon fails to start

I'm trying to deploy my django api on AWS EC2 but I keep getting this error. I've checked everything seems to be fine. Here is my gunicorn.service file [Unit] Description=gunicorn …

13.11.2023
Django Rest Framework - How to store a GIF image

I am working on a Django project using Django Rest Framework, and I am facing an issue related to storing and processing GIF images in one of my models. class GiftCardPlan(model.Model): # ... other fields ... image = ProcessedImageField(null=True, blank=True, …

13.11.2023
(Django) Need help getting things from the database

So, lets try this again, I very new to programing and don't understand much about the specifics so bear with me for a little, I am making a website that have a login and ticket system, I followed a tutorial …

13.11.2023
Getting error "Unknown command: 'load_data'. Did you mean loaddata?" while running "python manage.py load_data"

While running python manage.py load_data I am getting an error Unknown command: 'load_data'. Did you mean loaddata?. Below I have attached the folder structure where load_data.py is present. I also tried running …

13.11.2023
Can make migration in django

I cant migrate this model in django class ApprovedCourse(models.Model): course_name = models.CharField(max_length=50) provider_college = models.ManyToManyField('processes.College', related_name="provider_college") prerequisites = models.ManyToManyField('ApprovedCourse', related_name="courses_that_need_this_course",null=True) both_needs = models.ManyToManyField('ApprovedCourse', related_name="courses_required_for_this_course",null=True) number_of_course_units = models.IntegerField() course_type = models.CharField(max_length=50) class SemesterCourse(models.Model): approved_course=models.ForeignKey('ApprovedCourse', on_delete=models.CASCADE , null=True, related_name='approved_course') class_day_and_time …

13.11.2023
Django.db.utils.ProgrammingError: (1146, "Table 'test_conect.projects' doesn't exist") while testing

I'm trying to test models for the first time in my django app,but when i run python manage.py test I get the following error django.db.utils.ProgrammingError: (1146, "Table 'test_conect.projects' doesn't exist") Here is the model I want to test class Files(models.Model): …

13.11.2023
Getting Permission denied: '/vol/web/media' when trying to create file in my django application

Here is my dockerfile. FROM python:3.9-alpine3.13 ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt COPY ./electron /electron COPY ./scripts /scripts WORKDIR /electron EXPOSE 8000 RUN apk add --no-cache --virtual .build-deps gcc musl-dev RUN python3.9 -m venv /py && \ /py/bin/pip install …

13.11.2023
AssertionError: PermissionDenied not raised

I'm new to testing in django , i'm trying to test a view that raises PermissonDenied when the test user is not authenticated , this is part of the view code @login_required def files_raw(request): user = request.user # Get the …

13.11.2023
Why i can't run my Django project with : python manage.py runserver

I encountered an error: File "<frozen importlib._bootstrap>", line 1204, in _gcd_import File "<frozen importlib._bootstrap>", line 1176, in _find_and_load File "<frozen importlib._bootstrap>", line 1140, in _find_and_load_unlocked ModuleNotFoundError: No module named 'C:\\Users\\Youssef\\Documents\\Hello_Django\\import_data' However, I do not have a file named …

13.11.2023
Can Anyone tell if my ERD(Entity Relation Diagram) is correct or not?

I am creating an ERD for my college project. can anyone tell me if my ERD is correct or not. if not then what are my mistakes. I am creating this ERD from django app. I generated the UML diagram …

13.11.2023
Django - Created a web app which is linked to my PSQL, but when inserting data to one of my tables gives error for no ID

I have a table where it has only two columns being exercise_id and muscle_id create table if not exists exercise_muscle( exercise_id INT not null, muscle_id INT not null, primary key (exercise_id, muscle_id), foreign key (exercise_id) references exercise(exercise_id), foreign key (muscle_id) …

13.11.2023
Django simple jwt login with OTP without password

I have a django-rest app , for auth system i need help . i want to use JWT for auth (simple_jwt) but i was reading the doc , that i have find that i need to send the password …

13.11.2023
How to get all pages awaiting moderation in Wagtail

I'm trying to find a way to query all pages that are currently awaiting moderation. I tried PageRevision.objects.filter(submitted_for_moderation=True).values('page_id'), but it seems to return only a few of them, I don't understand why. If i can get all pages in moderation, …

13.11.2023
How to create orders and order items in DRF

I want to know, how efficiently i can create order and its order items in DRF using views and serializers. I am sending many=True for POST request to OrderItemSerializer because i will be having a list of order items and …

13.11.2023
How can I use static img file in windows's django

I'm trying to make django webapplication. It worked on linux and wsl.But now I need to make windows native development environment. However when I try to get the static img file I get following errors. django.core.exceptions.SuspiciousFileOperation: The joined path (C:\tcgcreator\img\devirun.png) …

13.11.2023
Button for adding an instance of formset in Django

I want to create a button for dynamically adding and removing an instance of formset from the displayed page. It is my first experience with formset in Django and I do not know any JavaScript, so I would be grateful …

13.11.2023
Handling 401 Unauthorized Error on Page Refresh with JWT and React/Django

I'm developing an authentication application using Django for the backend and React for the frontend. I've implemented JWT Tokens for authentication. When I log in, the HttpOnly cookies (access_token and refresh_token) are set correctly. However, I encounter a 401 (Unauthorized) …

13.11.2023
Duplicate MongoDB Records Issue with update_one and upsert under High Traffic

I am currently facing a challenging issue in my Django application integrated with MongoDB, particularly when dealing with high traffic and concurrent users. Despite using update_one with upsert, I'm observing instances where double (at times tripple) records are being created …

13.11.2023
Django not connected to the Apache server

This error came up when I tried to match Django with Apache 2.4. But when I access the server, I get 500 errors I haven't solved this error yet error code [Mon Nov 13 20:44:10.540478 2023] [wsgi:error] [pid 16020:tid 1112] …

09.11.2023
Как правильно добавить на все страницы сайта форму?

Я создал в папке проекта файл forms.py from django import forms class ContactForm(forms.Form): your_name = forms.CharField(label="Your name", max_length=100, required=False) В общем шаблоне прописал так: ...html... <form action="" method="post"> {% csrf_token %} {% for field in form %} <div class="fieldWrapper"> …

08.11.2023
При обращении к бд в вебсокете django возвращаются неправильный данные

Пишу вебсокет для карточной браузерной игры на django и channels. Когда раунд заканчивается происходит подсчет результатов, сам подсчет работает правильно и даже сохраняет подсчеты в бд. Но в конце следующего раунда, при обращении к бд, она возвращает данные, которые были …

08.11.2023
Как сделать чтоб пользователи сами добавляли отзывы через бот

STATUS_TOP = ( ('0', '☁️➖➖➖➖'), ('1', '➖🌥➖➖➖'), ('2', '➖➖⛅️➖➖'), ('3', '➖➖➖🌤➖'), ('4 ', '➖➖➖➖☀️'), ) class Reviews(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT, verbose_name='Аккаунт') text = models.TextField(max_length=1500, verbose_name='Отзыв', null=True, blank=True, help_text="<xmp><b></b> <i></i> <del></del> <u></u> <code></code> <a href='https://postimages.org'>фото</a></xmp>") is_public = models.BooleanField(verbose_name='Опубликован', …

07.11.2023
PyLint Django: django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured

Мое Django-приложение работает нормально, если я запускаю его через python src/manage.py runserver. Однако я хочу интегрировать в проект pylint, и при запуске команды pylint src --load-plugins pylint_django я получаю следующую ошибку: Traceback (most recent call last): File "/venv/lib/python3.11/site-packages/pylint_django/checkers/foreign_key_strings.py", line 87, …

07.11.2023
Не могу обработать исключения при обновление

День добрый, проблема в том что при обновлении у меня в обязательном порядке запрашивает что бы я что то ввел в поля username или же email, но я хочу обновить только данные о avatar без изменения других полей. View.py …

07.11.2023
POST, DELETE method записать в таблицу

Подскажите, как записать в таблицу методы post, delete Например, есть модель users. И модель tags (связанная по many to many с users). На выходе нужно получить в третей таблицы такие данные: user_id -> 1 tag_slug -> slug_name action -> post …

06.11.2023
Django SQL сырой запрос не работает

Models.py class Birds(models.Model): id_birds = models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID') id_user = models.ForeignKey('User', on_delete=models.PROTECT, null=True) name = models.CharField(max_length=100, null=False, unique=True) PNG = models.ImageField(upload_to='images') feather_color = models.TextField(max_length=70, null=False) class ViewedUser(models.Model): id_view = models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID') id_birds = models.ForeignKey('Birds', on_delete=models.PROTECT, …

05.11.2023
Структура проекта django с постоянно работающим воркером

Мне нужен совет по структуре проекта. У меня есть скрипт-воркер, который постоянно держит коннект со SteamAPI под логином и паролем для того, чтобы получать данные о пользователях и заполнять ими html. Мне интересны ответы на любой из следующих вопросов, буду …

04.11.2023
Переход по url Django, в url адрес не меняется

Urls.py urlpatterns = [ path('', views.auth, name='auth'), # Страница входа. path('viewBirds.html/', views.viewBirds, name='viewBirds'), # Представление птиц. path('creatBirds.html/', views.creatBirds, name='creatBirds'), # Создание птиц. path('creatUser.html/', views.rgstrUser, name='rgstrUser'), # Создание пользователя. path('viewUser.html/', views.viewUser, name='viewUser'), # Просмотренные птицы. ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) …

03.11.2023
Можно подогнать к моему боту кнопку отмены вместо команды

@dp.message_handler(state="*", commands='Назад') #@dp.message_handler(text(equals='Назад', ignore_case=True), state='*') async def cancel_handler(message: types.Message, state: FSMContext): current_state = await state.get_state() if current_state is None: return await state.finish() await message.reply('Cancelled.', reply_markup=types.ReplyKeyboardRemove()) photo=open(f'.uploads/rp.png', 'rb') await message.answer_photo(photo, f'{bot.rules}', reply_markup=keyboard, parse_mode='HTML')