"Вопросы и ответы" Django и Python, страница 2

08.05.2024
Cannot resolved keyword 'date_created' into field

I have a problem with runserver on PowerShell. entries_detail.html: <article> <h2>{{ entry.date_created|date:'Y-m-d H:i' }}</h2> <h3>{{ entry.title }}</h3> <p>{{ entry.content }}</p> </article> entries_list.html: {% for entry in entry_list %} <article> <h2 class="{{ entry.date_created|date:'l' }}"> {{ entry.date_created|date:'Y-m-d …

08.05.2024
How to connect to broker Websocket in django

I am building an algotrading platform, i have access to broker apis and websockets, but i dont know how to connect to broker websocket and consume the data on realtime basis in django I have setup channels: #consumers.py class ChatConsumer(WebsocketConsumer): …

08.05.2024
Why is django debug toolbar causing a 'ValueError at ... Another profiling tool is already active' error when Htmx ajax fires?

I had django-debug-toolbar working fine in my application until I added htmx. Now I'm getting Another profiling tool is already active error. The page loads then htmx fires on load …

08.05.2024
Docker-compose: Creating same container for different projects

I'm facing an issue with my Django projects that have a similar structure. Each project has a backend folder containing a docker-compose.yml and Dockerfile. The structure is as follows: project1/backend/docker-compose.yml project2.backend/docker-compose.yml The problem arises when I switch between projects …

08.05.2024
How to use Django AutocompleteFilter thtough 2 relations?

I have Django models hierarchy class Workspace(Model): title = CharField() class User(Model): workspace = ForeignKey(to=Workspace) class Chat(Model): user = ForeignKey(to=User) In Django admin at Chats page i want to filter them by workspace, but there are many workspaces, so …

08.05.2024
How to connect Django 5.0.3 to SQL Server database 2024 [duplicate]

I have been trying to connect Django with SQL server but there are errors occurring continuously no matter what I try. For example DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'xxxxx', 'USER': 'xxxx', 'PASSWORD': 'xxxx', 'HOST': 'xxxxx', 'PORT': '1433', …

08.05.2024
DJANGO ImportError: cannot import name 'url' from 'django.conf.urls' version 5.0.3 [duplicate]

I'm following this DJANGO Rest Framework tutorial: https://www.youtube.com/watch?v=eA4H3p95hbM&list=PLmDLs7JbXWNjr5vyJhfGu69sowgIUl8z5&index=4 After modifying in 'urls.py', then type "python manage.py migrate" I get this error: from django.conf.urls import url ImportError: cannot import name 'url' from 'django.conf.urls' (F:\Learning HTML and CSS\DJANGO_DAVE …

08.05.2024
His error originates from a subprocess, and is likely not a problem with pip

Pip install validate email Collecting validate Using cached validate-1.0.1.tar.gz (32 kB) Installing build dependencies ... done Getting requirements to build wheel ... error error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: …

08.05.2024
Django Annotation: Convert time difference to whole number or decimal

I am trying to sum the hours user spent per day. I wanted to convert this into whole number or decimal (e.g. 2, 6.5) hrs, to easily plot this to my chart. But the result of below code is in …

08.05.2024
Use the Django ORM to do a left outer join between unrelated models?

Suppose I have two models: class One(models.Model): name = models.CharField(max_length=300, unique=True) class Two(models.Model): name = models.CharField(max_length=300, unique=True) They are not related by a foreign key, and there are reasons to leave it that way in this project. …

08.05.2024
How to deliver Django+Postgresql projects to clients?

I have been working on a project where my client wants me to load some csv files data into the database and he wants me to use Postgresql. The problem is that sqlite has a physical database stored in django …

07.05.2024
How do I expose information from Django model to the forms/views(?)/html(?) to be able to see all information built-in the model

I am trying to add more information to a form dropdown built using Django forms. A basic explanation of the program is: The user logs in The user can create 'decks' that are to be displayed on the 'game_tracking' …

07.05.2024
Users that will be using a django form and posting data

I have created a django web app with CRUD functionality, i want to be able to see the users (With their names) that have posted on the form and see a full list of the data they post along with …

07.05.2024
I have some errors while im trying to have a special number for each page in Django

I used int:observatory_id to provide a special number for each pages without any special typos and mistakes and i have this error Reverse for 'observatory' with arguments '('',)' not found. 1 pattern(s) tried: ['observatorys/(?P<observatory_id>[0-9]+)\Z'] here is my code : urls.py …

07.05.2024
Django - Removing subdomains from my multitenancy app

I have a working multitenancy app in Django with isolated databases that currently uses a subdomain for each tenant and threading. The subdomain prefix is used to make a connection to the corresponding database, so: client1.mysite.com access the database …

07.05.2024
How to set up DJANGO_SETTINGS_MODULE with absolute path of the settings.py file

I need to write some scripts for django and trying to set up the DJANGO_SETTINGS_MODULE environment variable at the beginning of each script. The scripts, manage.py and myproject directory are in the same parent directory. Additionally, settings.py file is in …

07.05.2024
Django: динамическое обновление списка в форме

Проблема с отображением списка в форме при выборе города: JavaScript и AJAX не обновляют содержимое. Как исправить? Есть функция по оформлению заказа (create_order), которая обрабатывает форму. В форме есть поле (country) - город. Задумка такая, хочу чтобы пользователь выбирал …

07.05.2024
How to make user in Django choose the workshop he added to make a service record for his own car?

Im struggling with same problem for 3 days now, im trying to make my finish project which is some kind of online servicebook for cars we own, i have models vehicle, workshop, filter, servicerecord and i cant add servicerecord to …

07.05.2024
Serve django staticfiles with nginx inside docker

I have problem with staticfiles for django admin panel. for rest framework frontend panel the files are served without problem settings.py STATIC_URL = "/static/" STATIC_ROOT = BASE_DIR / "staticfiles" STATIC_ROOT.mkdir(exist_ok=True) Dockerfile: FROM python:3.10-slim-buster ENV PYTHONDONTWRITEBYTECODE 1 ENV …

07.05.2024
How to add results to a test in Django quiz app?

I'm just learning Django and trying to create a test. I watched the video on YouTube, but I didn't quite understand how to add the test results to the page. I created the test and in the SQLite database, I …

07.05.2024
Graphene django. Get error: String cannot represent value '(value, )' after mutation attempt

I'm new to graphene library and make updating mutation as was in documentation. Also I looked at this video about CRUD : https://youtu.be/C-EfYVXShLE?si=uksgjJEuavU1k9GW I thought, that problem was in mutate arguments, I tried to make it with …

07.05.2024
Not able to connect to external mysql db in django

I am again and again failing to connect to external mysql db on phpmyadmin db as my django keeps connnecting to its localhost database i have tried many things but not getting success can you guys help me please #db …

07.05.2024
Why my content is not showing between blockcontent and endblock in django?

I have build an other app in my django project and have a template in my templates folder and i am including the base.html from my other app but the …

07.05.2024
I can't add an image through object.create in Django

Good afternoon, I'm trying to insert an image into the database through object.create, but it's not being inserted in any way, everything else is inserted until the other image. The image is being created that I have already tested, and …

07.05.2024
Django Reverse for '' not found. '' is not a valid view function or pattern name

I am getting an error "Django Reverse for '' not found. '' is not a valid view function or pattern name.". I was searching for a way to fix this but couldn't find anything the urls.py and views.py, home.html and …

07.05.2024
Django form saving wrong information to database

So in my form, when I select a time choice, for example "8 PM" it stores in the database as a different time, I've checked the form submission and it is being submitted as the correct time, but not being …

07.05.2024
KeyError: '__reduce_cython__' when trying to import sklearn package into Django app

When attempting to run my Django app with python manage.py runserver, I am getting the following error relating to a scikit-learn module import: File "sklearn\\metrics\\_pairwise_distances_reduction\\_argkmin.pyx", line 1, in init sklearn.metrics._pairwise_distances_reduction._argkmin KeyError: '__reduce_cython__' This is the last line in a …

07.05.2024
Page not found (404) appears when performing tutorial

I get the following error after many tries Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/polls Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ The current path, polls, didn’t match any …

07.05.2024
How do I customize Djoser endpoint '/users/me/' to return all custom user fields?

From djoser.serializers import UserCreateSerializer, UserSerializer from django.contrib.auth import get_user_model User = get_user_model() class UserSerializer(UserSerializer): class Meta(UserSerializer.Meta): model = User fields = ('id','email','name','phone_number','address') The endpoint only returns id, email and name. I want it to return all other fields.

07.05.2024
Used django filterset field not working true and returning empty result?

I used filterset for my view in django like this : class CalendarEventListFilter(filters.FilterSet): start_time = filters.DateTimeFilter(field_name='start_time', lookup_expr="gte") end_time = filters.DateTimeFilter(field_name='end_time', lookup_expr="lte") class Meta: model = CalendarEvents fields = ['start_time', 'end_time'] and this is my model : class CalendarEvents(BaseTimestampModel, BaseOwnershipModel): …

07.05.2024
Will Django Transaction Stop Other Connections From Selecting Until Its Completed

In Django I have a table that contains records that need to be processed by celery workers. The way this works is that the worker will grab the next X number of rows from the table in a batch to …

07.05.2024
SMTP disconnected Error occured in Django

So i've been working on a repo of a project for some time now in an effort to learn and get familiar with Django. In the project, once a student register's onto the site, it's supposed to send a confirmation …

07.05.2024
Django PasswordResetForm not sending emails

I have the following function manages adding a new employee to the selected workshop, def add_employee(request, shop_number): workshop = get_object_or_404(Workshop, shop_number=shop_number) context = {"workshop": workshop} if request.method == "POST": form = ProfileForm(request.POST, files=request.FILES) if form.is_valid(): employee = form.save(commit=False) employee.added_by = …

07.05.2024
Как указать на то, что пользователь авторизован? для проверки логаута

Def api_post_users_login(client: APIClient): user = UserFactory.create() user.set_password('123QQ') user.save() response = client.post('/api/users/login/', {'username': user.email, 'password': '123QQ'}) assert response.status_code == HTTPStatus.OK def test_api_post_users_logout(client: APIClient, api_post_users_login): api_post_users_login response = client.post("/api/users/logout/") assert response.status_code == HTTPStatus.OK В данный момент использую фикстуру, но это получается …

07.05.2024
How to display dropdown menu in javascript

I'm using a javascript to display a table in a django template. If the receipt's is_disbursed value is True and the paid_status is Settled, I want the dropdown menu to contain Print only. If is_disbursed is False and the paid_status …

07.05.2024
Django 4.2 how to display deleted object failure in modeladmin page?

Code used to override the delete_queryset in the modeladmin: def get_actions(self, request): actions = super().get_actions(request) del actions['delete_selected'] return actions def really_delete_selected(self, request, queryset): ''' # 1. Update the group-mailbox relation: `goto` values if mailbox(es) are deleted # 2. Sending …

07.05.2024
I want to convert the python data structure into yaml format

@require_http_methods(["POST"]) @csrf_exempt @api_view(['POST']) @permission_classes([IsAuthenticated]) def SetAlertRules(request): try: if not request.body: return Response({'error': "Data for setting alert not provided"}, status=http_status.HTTP_400_BAD_REQUEST) payload = json.loads(request.body) if not payload: return Response({'error': "Data for setting alert not provided"}, status=http_status.HTTP_400_BAD_REQUEST) vm = payload.get('vm') connector = payload.get('connector') …

07.05.2024
Django compilemessages does not apply changes in production

I am currently developing a web application using django + postgres + nginx + docker, everything runs already. I now developed a feature where you can change the translation file (.po) while logged in as admin. It works on my …

07.05.2024
How to add email sending port to the security group in AWS ec2 instance

I'm trying to send an email from my back end that is hosted on an ec2 instance on amazon web services , but the function that runs this part takes a very long time to start the request that it …

07.05.2024
Validation error doesn't render on the template with 2 form

I have in my template with a form in which data is collected in 2 Django forms but sent to the view in the same post like this: <form action="" method="post"> {% csrf_token %} <div class="form1"> <div> <label …