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' …
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 …
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, …
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 …
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 …
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 = …
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 …
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 …
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 …
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 …
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 …
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 …
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, …
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 …
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 …
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 …
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): …
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 …
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 …
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 …
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 …
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) …
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 …
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, …
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 …
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) …
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 …
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) …
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 …
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] …
Я создал в папке проекта файл 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"> …
Пишу вебсокет для карточной браузерной игры на django и channels. Когда раунд заканчивается происходит подсчет результатов, сам подсчет работает правильно и даже сохраняет подсчеты в бд. Но в конце следующего раунда, при обращении к бд, она возвращает данные, которые были …
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='Опубликован', …
Мое 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, …
День добрый, проблема в том что при обновлении у меня в обязательном порядке запрашивает что бы я что то ввел в поля username или же email, но я хочу обновить только данные о avatar без изменения других полей. View.py …
Подскажите, как записать в таблицу методы post, delete Например, есть модель users. И модель tags (связанная по many to many с users). На выходе нужно получить в третей таблицы такие данные: user_id -> 1 tag_slug -> slug_name action -> post …
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, …
Мне нужен совет по структуре проекта. У меня есть скрипт-воркер, который постоянно держит коннект со SteamAPI под логином и паролем для того, чтобы получать данные о пользователях и заполнять ими html. Мне интересны ответы на любой из следующих вопросов, буду …
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) …
@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')