Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-react basic system architecture required
I am trying to understand how a django react project operates? If someone can give me a rough system architecture it would be really helpful. I am creating a music room based on spotify API using django react as my pillars of the project. Help me create a system architecture for it -
gradual migration of django monolith to async
I have huge django2 app (without django ORM) and I want to make it asynchronous. Right now i've come up with two strategies: upgrade to django 3/4 and migrate to async view by view add separate app (fastapi), migrate each view to the new app, and while migration is in progress split traffic between apps on load balancer level. the problem with first approach is that django will switch between sync and async mode and I will not see any improvements before migrating most of the views. the problem with second approach is that it is somewhat complicated and will require more code migrations and infra tinkering. any suggestions? -
Django Environment Identifying the DEBUG as False while it is set to True
I get and error CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False Below are the edits I attempted seeing at stackoverflow's suggestion from various (queries)[https://stackoverflow.com/questions/66923320/why-it-doesnt-set-debug-true] around 5 of them were relevant and tried to edit accordingly. ... I also checked for views and urls for any filename mistyping and typo errors. Yet I am getting CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False. I closed the session and changed the open .py file default from vscode and then with python. Yet this error is persistent PLEASE HELP My settings.py has DEBUG = TRUE ALLOWED_HOSTS = [] I have also tried ALLOWED_HOSTS = ['*'] then ALLOWED_HOSTS = ['localhost'] then ALLOWED_HOSTS = ['127.0.0.1'] then ALLOWED_HOSTS = ['localhost', '127.0.0.1'] once with DEBUG = FALSE and then with DEBUG = TRUE Alternately I Tried this TEMPLATE_DEBUG = DEBUG if not DEBUG: ALLOWED_HOST = ['0.0.0.0', '127.0.0.1','localhost','*'] ALLOWED_HOSTS = []``` The issue still persists despite Changing VS code settings .py extension change from VSCODE to Python interpreter and vice versa. -
Django circular import (models-views(-forms))
Watched all the previous related topics devoted to this problem, but haven't found a proper solution, so decided to create my own question. I'm creating a forum project (as a part of the site project). Views are made via class-based views: SubForumListView leads to a main forum page, where its main sections ("subforums") are listed. TopicListView, in its turn, leads to the pages of certain subforums with the list of active topics created within the subforum. ShowTopic view leads to a certain topic page with a list of comments. The problem manifests itself because of: Models.py: Method get_absolute_url in the model Subforum, which in its return section's reverse function takes a view as the 1st argument; I've tried to avoid a direct import of the view, but the program doesn't accept other variants; Views.py: most of the views have imported models either in instance arguments (model = Subforum), or in methods using querysets (like in get_context_data: topics = Topic.objects.all()); I can't surely say whether the change of instance argument model = Subforum to model = 'Subforum' really helps, as it's impossible to do with queryset methods and thus can't be proved; Forms.py: my form classes were created via forms.ModelForm and … -
Django: How to add objects to ManyToManyFields of multiple objects in a fast way?
We have models.py file : class Car(models.Model): brand = models.CharField(max_length=50 , null=True , blank=True) sub_brand = models.CharField(max_length=50 , null=True , blank=True) code = models.CharField(max_length=20 , unique=True) class Skill(models.Model): car = models.ForeignKey(Car , on_delete=models.CASCADE, null=True , blank=True) skill = models.CharField(max_length=50 , null=True , blank=True) class Provider(models.Model): name = models.CharField(max_length=100) skills = models.ManyToManyField(Skill , blank=True) and we want to add some skills based on cars to the provider model so I use views.py like this: def skills_add(request , id): provider = get_object_or_404(Provider , id=id) if request.method == 'POST': form = AddSkill(request.POST) if form.is_valid(): data = form.cleaned_data cars = Car.objects.filter(brand=data['brand']) for i in cars: for x in data['skills']: skill = Skill.objects.get(car=i , skill=x) provider.skills.add(skill) provider.save() else: return redirect("managers:dashboard_manager") return redirect(request.META.get('HTTP_REFERER')) the data["brand"] is a string of one brand of car and data["skills"] is a list of strings that each one of them are name of one skill that we have in out database. you send the data to form and then it's start to filter cars with that brand . after that , We start to loop over those cars and loop over the skills that sended . We add each one of them to skills field of the provider. But the problem … -
How can I handle multiple separate models in a single AJAX request using Django REST Framework?
In my Django project (version 5.1.2), I need to handle data from multiple models in a single AJAX request from the front end. For example, I have a form that collects user information and shipping addresses at the same time. I want to submit this data in a single request and have it saved in separate models in the database. I’m using Django REST Framework to manage the API, but I’m unsure how to properly validate and save multiple models at once in one request. Currently, I am using one ViewSet per model, but I don’t know how to combine them in a single AJAX request and ensure that if there’s an error in one of the models, none of the data is saved (i.e., I want proper transaction handling). Is there a recommended solution for this in Django 5.1.2? What is the best way to handle multiple models in a single AJAX request in Django REST Framework? Details: I'm using Django 5.1.2. Both user and address information need to be saved transactionally. What I Tried: I created two separate ViewSets for the user information and shipping address models. Then, I tried to send the form data via a single … -
Encoding problem when migrating postgresql database tables to models.py django
When performing table migration python manage.py inspectdb > example/models.py all Cyrillic strings are transposed as a set of unknown characters: 'id_шёїюф ∙хую' Encoding of the database server as well as python script is UTF-8. Is there any way to solve this problem? I tried show server_encoding; and got UTF8, tried set PYTHONIOENCODING=UTF-8 Also, I added 'OPTIONS': { 'client_encoding': 'UTF8', } into settings.py. All aforementioned methods didn't help and problem is still existing. I use psycopg package. -
swagger select a defintion for django
so, I've been working on my Django project Apis and i'm using drf-spectacular for the swagger view this is in my settings.py: SPECTACULAR_SETTINGS = { 'TITLE': 'Your Project API', 'DESCRIPTION': 'Resume Swagger API', 'VERSION': '1.0.0', 'SERVE_INCLUDE_SCHEMA': False, } and ofc this in my main urls.py: urlpatterns = [ # Swagger Url path('api/schema/', SpectacularAPIView.as_view(), name='schema'), # Optional UI: path('', SpectacularSwaggerView.as_view(), name='swagger-ui'), ] it has no drop down in order to select a definition, I mean i don't know if such thing exist for django: this is how my swagger looks like: enter image description here but i've seen this for as far as i know for an ASP.NET project that has such drop down to navigate between different api endpoints as below: enter image description here is this achievable in django? I've searched alot through docs and everything but i guess there is no such a guide to do this i hope someone comes up with a solution? -
bin/bash logs screw up after running django query create - ÄDEBUGÅ instead [DEBUG]
When running this django command: MyObjectBase.objects.create( ..., report_pdf=open(f"{REPORT_PATH}/{file_name}.pdf", "rb").read(), ... ) My log output in the bin/bash console of VS Code in WSL2 on Win11 gets screwed. Instead before the command: [2024-10-21 13:40:52 +0200] [923356] [DEBUG] this is a debug message I am getting logs like: Ä21/Oct/2024:11:47:18 +0000Å ÄDEBUGÅ Backticks turn into 'é'. It looks like that during the create-command the binaries of the file are printed to the log like (just thousands of chars longer than this sample) ÖxecoÖxc6Öxd2ÖxffÖxd6ÖxffKÖx00xyÖxchÖxfaÖxe66Öx7fÖx98Ö This does not happen for every report, using different base data does not cause this effect. Unfortunately it is impossible for me to detect differences. I can say that the base data only contains strings and doubles and so on but no nested blobs or strings like code, but special chars like # are possible. I tried another terminal. tmux was available by default. It does not face this problems, logs stay fine. But not using (one of) the most default terminals is not a valid solution for me. So I am looking after the cause and hope to get it solved somehow. As an alternative I could imagine to suppress the binaries from the log when running django create. … -
The code_verifier does not match the code_challenge supplied in the authorization request for PKCE. error
I'm trying to get access token and refresh token of Microsoft account. const loginAndGetAuthorizationCode = async () => { const code_verifier = generateCodeVerifier(); const code_challenge = await generateCodeChallenge(code_verifier); localStorage.setItem('code_verifier', code_verifier); localStorage.setItem('code_challenge', code_challenge); const loginRequest = { tenant: "common", scopes: ["User.Read", "Mail.Read"], response_type: "code", responseMode: "query", state: code_verifier, codeChallenge: code_challenge, codeChallengeMethod: "S256", }; try { const loginResponse = await msalInstance.acquireTokenRedirect(loginRequest); console.log("loginResponse => ", loginResponse); } catch (error) { console.error("Login failed: ", error); } }; This is config import { PublicClientApplication } from "@azure/msal-browser"; const msalConfig = { auth: { clientId: "ID", // client ID authority: "https://login.microsoftonline.com/tenantID", // tenant ID redirectUri: "http://localhost:3000/dashboard", }, cache: { cacheLocation: "sessionStorage", storeAuthStateInCookie: true, } }; const msalInstance = new PublicClientApplication(msalConfig); await msalInstance.initialize(); // await msalInstance.handleRedirectPromise(); export { msalInstance }; This are utils functions export function generateCodeVerifier() { const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"; const array = new Uint8Array(43); // Minimum length of 43 window.crypto.getRandomValues(array); return Array.from(array, (b) => characters[b % characters.length]).join(""); } // Generate the code challenge from the code verifier export async function generateCodeChallenge(codeVerifier: string) { const encoder = new TextEncoder(); const data = encoder.encode(codeVerifier); const digest = await window.crypto.subtle.digest("SHA-256", data); // Convert Uint8Array to an array using Array.from() before processing const base64Digest = btoa(String.fromCharCode(...Array.from(new Uint8Array(digest)))) .replace(/\+/g, … -
Issue with updating read-only fields in Django admin: flags not saving
I’m working on a Django admin interface where certain fields (specifically, review status flags such as is_pending_review_section_title_en and is_pending_review_section_title_uk) should be marked as read-only in the admin interface, but still be updated programmatically when content changes. I’ve implemented the logic to dynamically determine the fields as read-only using the get_readonly_fields method inside an inline admin class (SectionInline). Although the fields correctly display as read-only in the interface, the problem arises when I try to update these fields in the save_model method of the PageAdmin class (or even in forms). The flags appear to be set correctly in the code, but they do not persist in the database after saving. Here is a summary of what I’ve tried: 1. Marked fields as read-only using get_readonly_fields — This works for the admin UI. 2. Tried updating the fields programmatically inside save_model in the PageAdmin class and verified the values through logging. The flags are set to True, but after saving, the values in the database remain unchanged. 3. Commented out form save logic to check if it’s interfering with saving, but the issue persists. 4. Ensured flags are not present in forms to avoid user interaction. What could be causing the fields … -
Unable to exclude foreign keys in django
I'm failing to get Profiles whithout an Interaction. Does anybody see what I'm doing wrong? #models.py class Profile(models.Model): username = models.CharField(max_length=100) class Interaction(models.Model): user_id = models.ForeignKey(Profile,on_delete=models.CASCADE, null=True, blank=True) #test.py class TestQueries(TestCase): def test_get_profiles_without_interaction(self): profile_with_interaction = Profile.objects.get(username='foobar') interactions_from_profile = Interaction.objects.filter( user_id=profile_with_interaction) assert interactions_from_profile #####FAILS##### all_profiles_without_interaction = Profile.objects.exclude( pk__in=Interaction.objects.all()) assert profile_with_interaction not in all_profiles_without_interaction -
How to Send Authentication Token from Frontend using Both Fetch & Ajax to Restful API Backend?
I am currently working with django restframwork, I am on my training period. I created a api for lottery management system using DRF and in this restful api i added IsAuthenticated permission class. Now i am creating demo project for this api, now i am using ajax for requests & sending authorization using btoa. but i am sure that this is not a professional method. I wanted to learn how to send the authorization token to backend with username and password. & also how to achieve same in reactjs as i am little bit familiar with react js and working on it as well. function ajaxCall(type, url, data, callback) { /**Common Method to handle all the Ajax Requests */ $.ajax({ url: url, type: type, data: data, headers: { "Authorization": "Basic " + btoa(USERNAME + ":" + PASSWORD) }, success: function (response, status, xhr) { console.log(response); console.log(xhr); if (xhr.status != 204) { if (callback) { callback(response); } } }, error: function (xhr, status, error) { console.error("Error occurred:", xhr.responseText, status, error); }, }); } -
django rest-frame-work user_id related "violates not-null constraint"
I have this error jango.db.utils.IntegrityError: null value in column "user_id" of relation "defapp_actionlog" violates not-null constraint DETAIL: Failing row contains (13, "{\"action\":\"push\"}", 2024-10-21 06:11:30.43758+00, 2024-10-21 06:11:30.43759+00, null). What I want to do is push the actionlog from javascript and set the login user to model. I set the CustomUser object to user row, however it still requies user_id? my viewset,model,serializer is like this below. class ActionLogViewSet(viewsets.ModelViewSet): queryset = m.ActionLog.objects.all() serializer_class = s.ActionLogSerializer def perform_create(self, serializer): obj = serializer.save() return obj def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) request.data._mutable = True request.data['user'] = m.CustomUser.objects.get(id=request.user.id) try: serializer.is_valid(raise_exception=True) except Exception as e: logger.info(e) self.perform_create(serializer) return Response(serializer.data) class ActionLog(models.Model): user = models.ForeignKey(CustomUser,on_delete=models.CASCADE,related_name='action_user') detail = models.JSONField(default=dict,null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class ActionLogSerializer(ModelSerializer): id = serializers.IntegerField(read_only=True) user = CustomUserSerializer(read_only=True,source="actionlog_user") detail = serializers.CharField() class Meta: model = m.ActionLog fields = ('id','user','detail') -
Data from forms not saved in database (Django)
The information I enter on my Website when I want to create a new quiz is only partially saved, the data for the Quiz model is saved in my database, but the Questions with Answers are not saved in the database when creating a quiz. Could this be a problem with the routes? Because the Quiz model is in quizes models.py, and the Answers and Questions are in questions models.py [20/Oct/2024 18:57:06] "GET / HTTP/1.1" 200 15893 [20/Oct/2024 18:57:06] "GET /static/css/style.css HTTP/1.1" 404 1966 [20/Oct/2024 18:57:06] "GET /static/js/script.js HTTP/1.1" 404 1963 [20/Oct/2024 18:57:06] "GET /favicon.ico/ HTTP/1.1" 204 0 [20/Oct/2024 18:57:06] "GET /add_quiz HTTP/1.1" 200 26109 [20/Oct/2024 18:57:06] "GET /static/js/script.js HTTP/1.1" 404 1963 [20/Oct/2024 18:57:06] "GET /static/css/style.css HTTP/1.1" 404 1966 [20/Oct/2024 18:57:07] "GET /favicon.ico/ HTTP/1.1" 204 0 [] [20/Oct/2024 18:57:25] "POST /add_quiz HTTP/1.1" 302 0 [20/Oct/2024 18:57:25] "GET / HTTP/1.1" 200 16290 [20/Oct/2024 18:57:25] "GET /static/js/script.js HTTP/1.1" 404 1963 [20/Oct/2024 18:57:25] "GET /static/css/style.css HTTP/1.1" 404 1966 [20/Oct/2024 18:57:25] "GET /favicon.ico/ HTTP/1.1" 204 0 also console returns me empty list Earlier python console return [{'id': ['This field is required.']}, {'id': ['This field is required.']}, {'id': ['This field is required.']}, {}] but it fixed when I hide management_form **Attach my code below** **add_quiz.html** … -
Product Screen is not showing up product on React, Django code
Im writing a shop using React + Django. After using Redux , the Product screen is giving an error. Request failed with status code 500 [enter image description here][1] enter image description here This is the error which i wrote in the codeblock. However, it should look like this when i choose a product: enter image description here The HomeScreen looks like this: enter image description here My code blocks: ProductActions: ` import axios from 'axios' import { PRODUCT_LIST_REQUEST, PRODUCT_LIST_SUCCESS, PRODUCT_LIST_FAIL, PRODUCT_DETAILS_REQUEST, PRODUCT_DETAILS_SUCCESS, PRODUCT_DETAILS_FAIL, } from '../constants/productConstants' export const listProducts = () => async(dispatch) => { try { dispatch({type:PRODUCT_LIST_REQUEST}) const {data} = await axios.get('/api/products/') dispatch({ type:PRODUCT_LIST_SUCCESS, payload:data }) } catch (error) { dispatch({ type:PRODUCT_LIST_FAIL, payload:error.response && error.response.data.message ? error.response.data.message : error.message, }) } } export const listProductDetails = (id) => async(dispatch) => { try { dispatch({type:PRODUCT_DETAILS_REQUEST}) const { data } = await axios.get('/api/products/${id}') dispatch({ type:PRODUCT_DETAILS_SUCCESS, payload:data }) } catch (error) { dispatch({ type:PRODUCT_DETAILS_FAIL, payload:error.response && error.response.data.message ? error.response.data.message : error.message, }) } } ``` **ProductReducers:** ``` import { PRODUCT_LIST_REQUEST, PRODUCT_LIST_SUCCESS, PRODUCT_LIST_FAIL, PRODUCT_DETAILS_REQUEST, PRODUCT_DETAILS_SUCCESS, PRODUCT_DETAILS_FAIL, } from '../constants/productConstants' export const productListReducer = (state = { products: [] },action ) => { switch(action.type) { case PRODUCT_LIST_REQUEST: return {loading: true,products: [] } case … -
Using OpenCV cv2.selectROI in Django raises error libc++abi.dylib: terminating with uncaught exception of type NSException
Using OpenCV in a Django app is causing the server to shutdown with following error: libc++abi.dylib: terminating with uncaught exception of type NSException Goal: Select ROI from the displayed image in browser What I am trying: Select an image (using cv2.imread()) and display in the browser <-- Working Select ROI using r = cv2.selectROI(...) <-- At this step the above error happens Using the code in Python shell works. But when included in Django views.py I am getting the error. What I am trying to find: Is it possible to use cv2.selectROI in Django? What are the basic requirement to accomplish what I am trying? -
How to Delete an Annotation Using Wagtail Review and Annotator.js on Button Click?
I am working with both Wagtail Review and Annotator.js in my project. I want to add a delete button (an "X" inside a red circle) to annotations, and when clicked, it should delete the corresponding annotation. I have added the delete button inside the annotation's controls, but I am struggling to properly trigger the deletion. What I have so far: I am using Annotator.js to create and manage annotations. The annotations appear on hover over the parent element (annotator-outer annotator-viewer). The delete button is injected dynamically inside the .annotator-controls span when the annotation becomes visible. I am trying to use the click event to trigger the annotation deletion, but I am not sure how to properly call the Annotator.js delete function or if I am handling the interaction correctly within Wagtail Review. Here’s the current approach I have: When the annotation parent (.annotator-outer.annotator-viewer) is hovered, I dynamically add the "X" delete button inside .annotator-controls. I attach a click event listener to the delete button. I expect the click to trigger the annotation deletion using Annotator.js. Code snippet: document.addEventListener('DOMContentLoaded', (event) => { function deleteAnnotation() { console.log('Delete function triggered!'); // Assuming annotator.js method is accessible to delete the annotation if (window.annotator && … -
Can anyone show me how to make a proper login system for my django application?
I need help building a proper login system for my homework in my django class. I am supposed to build an app that users can login in token based authentication and can post a destination and review it, but I'm stuck in the login section. I've manage to build the register systems correctly, but now I need to help with logging in. This is my login view I have. It keeps throwing a "NOT NULL constraint failed:" error so I have no idea what I'm doing wrong def login(request: HttpRequest): if request.method == "POST": email = request.POST.get('email') password_hash = request.POST.get('password') hasher = hashlib.sha256() hasher.update(bytes(password_hash, "UTF-8")) password_hash = hasher.hexdigest() token = "" letters = string.ascii_lowercase for _ in range(32): token = "".join(random.choice(letters) for _ in range(32)) session_token = Session.objects.create(token=token) response = HttpResponse("Cookie Set") try: user = User.objects.get(email=email, password_hash=password_hash) if user.check_password(password_hash): response = redirect("/") response.set_cookie('token', token) return response else: return HttpResponse("Invalid password") except User.DoesNotExist: return Http404({"Invalid email"}) return render(request, "destination/login.html") Here are my models from django.db import models import hashlib class User(models.Model): id = models.BigAutoField(primary_key=True) name = models.TextField() email = models.EmailField(unique=True) password_hash = models.TextField() def check_password(self, hashed_password): hasher = hashlib.sha256() hasher.update(bytes(self.password_hash, "UTF-8")) hashed_password = hasher.hexdigest() return self.password_hash == hashed_password class Session(models.Model): id … -
Periodic Task Not Execute With Celery Beat
when beat and worker is run then the periodic task is being created in Django Celery Beat, but it does not execute when the time interval is completed. This task is not executed : 'task': 'stripeapp.tasks.create_google_sheet_with_payments_task', Commented 2 hours ago Tasks.py from celery import shared_task from django_celery_beat.models import PeriodicTask, IntervalSchedule import json from .models import TaskSchedule from datetime import timedelta from .stripe_to_sheet_saving import create_google_sheet_with_payments from django.utils import timezone @shared_task def schedule_automated_tasks(): print("Scheduling automated tasks.") # Log all existing periodic tasks for debugging existing_tasks = PeriodicTask.objects.all() for task in existing_tasks: print(task.name, task.task, task.interval, task.expires) # Get tasks from TaskSchedule model where status is 'running' running_tasks = TaskSchedule.objects.filter(status='running') for task_schedule in running_tasks: print(f"Found task schedule: {task_schedule}") task = task_schedule.task frequency = task.stripe_source.run_frequency if task.stripe_source else None occurrence = task.stripe_source.occurence if task.stripe_source else None end_date = task_schedule.end_date # Determine the interval based on frequency interval = get_interval_from_frequency(frequency) if interval is None: print(f"Invalid frequency: {frequency} for task {task.id}. Skipping.") continue # Invalid frequency, skip # Check if the task should be marked as complete running_count = TaskSchedule.objects.filter(task=task, status='running').count() if occurrence is not None and end_date is None and running_count >= occurrence: task_schedule.status = 'complete' # Update status to complete task_schedule.save() print(f"Task {task.id} marked as … -
Problem with testing Messages in Django 5 CreateView
I am writing unit tests of ebook catalog applications in Django 5. The book creation page uses the built-in CreateView. The class code looks like this: class BookCreate(SuccessMessageMixin, PermissionRequiredMixin, CreateView): model = Book fields = ['title', 'author', 'genre', 'publisher', 'pages', 'cover', 'summary'] template_name = 'books/add_book.html' permission_required = 'catalog.add_book' permission_denied_message = 'Not enough permissions to add a book' success_message = 'Book successfully added' success_url = reverse_lazy('add-book') It works as follows: the user fills in the book data, clicks the submit button, then the page is redirected to the same page, plus the page displays the message specified in the success_message attribute of the class For testing, I use the MessagesTestMixin as described in the Django documentation. Here is the unit test code: class TestBookCreateView(MessagesTestMixin, TestCase): @classmethod def setUpTestData(cls): cls.test_user = User.objects.create_user( email='john123@gmail.com', username='John', password='Fiesta123' ) cls.add_book_permission = Permission.objects.get(codename='add_book') def setUp(self): login = self.client.login(username='Ivan', password='Fiesta123') self.test_user.user_permissions.set([self.add_book_permission]) def test_if_view_success_message_attached(self): author = Author.objects.create( first_name='Charles', last_name='Dickens' ) genre = Genre.objects.create( genre='Novel' ) book_data = { 'title': 'Great Expectations', 'author': author, 'genre': genre } response = self.client.post(reverse('add-book'), data=book_data, follow=True) self.assertMessages(response, 'Book successfully added') The test fails, I see an empty list in the results instead of a message. However, in the application, the message is successfully … -
Vercel is deploying my django website without css attachement
I deployed my Django website on Vercel successfully, yet it is hosted without static files, mainly; the CSS file. Here is my files structure: And here is my form.html code: <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Form</title> <link rel="stylesheet" href="{% static 'client/style.css'%}"> <style> @media (max-width: 768px) { .container { width: 100%; padding: 10px; } } </style> </head> <body> <div class="content"> <div class="container"> <div class="navinfo"> <nav class="navitems"> <ul> <li class="ServiceAnass"><h3>ServiceAnass</h3></li> </ul> </nav> </div> <div class="title"> <h2>200dh Competition By Anass</h2> </div> <div class="form"> <div><h3>Fill in the information below</h3></div> <div><form action="/submit" method="post"> <div > <label class="firstname" for="firstname">Nom</label> <input type="text" name="nom" id="firstname"> </div> <div> <label class="lastname" for="lastname">Prenom</label> <input type="text" name="prenom" id="lastname"> </div> <div> <label class="ID" for="ID">ID</label> <input type="number" name="nombre" id="number"> </div> <div> <label class="nwhatsapp" for="nwhatsapp">Numero Whatsapp</label> <input type="number" name="nwhatsapp" id="nwhatsapp"></label> </div> <div class="screenshot-comb"> <label class="screenshot" for="screenshot">Screenshot</label> <input type="file" name="screenshot" id="screenshot"> </div> <div> <input type="submit" name="submit" value="Submit" id="submit"> </div> </form></div> </div> </div> </div> </body> </html> This is the client/settings.py: """ Django settings for client project. Generated by 'django-admin startproject' using Django 5.0.7. For more information on this file, see https://docs.djangoproject.com/en/5.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/5.0/ref/settings/ """ from pathlib import Path … -
Django project hosting with Vercel
I am trying to host my Django project on Vercel, but it shows some errors related to the 'requirements.txt' file in my project, something related to dependencies. This is the error message: Error: Command failed: pip3.12 install --disable-pip-version-check --target . --upgrade -r /vercel/path0/requirements.txt ERROR: Cannot install -r /vercel/path0/requirements.txt (line 19) and idna==3.3 because these package versions have conflicting dependencies. ERROR: ResolutionImpossible: for help visit https://pip.pypa.io/en/latest/topics/dependency-resolution/#dealing-with-dependency-conflicts -
In Django, combining and ordering counts across two model fields
I have these two simplified models, representing people and letters that have been sent and received by those people: class Person(models.Model): name = models.CharField(max_length=200, blank=False) class Letter(models.Model): sender = models.ForeignKey(Person, blank=False) recipient = models.ForeignKey(Person, blank=False) I want to display a list of Persons ordered by how many times they've sent or received any letters. I started doing this very laboriously, but figure there must be a simpler way. e.g., this gets the Person IDs and counts of how many times they've sent a Letter: senders = ( Letter.objects.order_by() .values(person_id=F("sender")) .annotate(count=Count("pk")) .distinct() ) I can do the same for recipients. Then combine the two into a single list/dict, adding the counts together. Sort that. Then inflate that data with the actual Person objects, and pass that to the template. But I feel there must be a less laborious way, starting, I think, with a single query to get the combined sent + received counts. -
can't connect to mysql docker
when i launch the command 'python manage.py makemigrations' error : C:\Users\pc\AppData\Local\Programs\Python\Python313\Lib\site-packages\django\core\management\commands\makemigrations.py:160: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': (2003, "Can't connect to MySQL server on 'mysql' ([Errno 11001] getaddrinfo failed)") warnings.warn ( No changes detected im using docker and i launched mysql-container (dev-mysql) I am trying to launch django as backend with mysql database in docker container locally and stumble upon the error. i dont why know why im getting this problem, i tried so many solutions my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'tp', 'USER': 'root', 'PASSWORD': '125', 'HOST': 'mysql', 'PORT': 3306, } } docker-compose version: '3.8' services: mysql: image: mysql:8.0 container_name: dev-mysql restart: always environment: MYSQL_ROOT_PASSWORD: 125 MYSQL_DATABASE: tp ports: - "3307:3306" volumes: - mysql_data:/var/lib/mysql # Use the named volume networks: - my_bridge healthcheck: test: ["CMD", "mysqladmin", "ping", "-h", "localhost"] interval: 30s timeout: 10s retries: 5 backend-app: image: backend:latest # Use the already built image container_name: backend-app restart: always ports: - "8001:8000" depends_on: mysql: condition: service_healthy networks: - my_bridge healthcheck: test: ["CMD-SHELL", "curl -f http://localhost:8000/admin/login/?next=/admin/ || exit 1"] interval: 30s timeout: 10s retries: 5 frontend-app: image: frontend-app:latest # Use the already built image container_name: frontend-app restart: always ports: …