Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to detect client disconnects on StreamingHttpResponse (Server Side Events) using Django/Django-Ninja?
We want to add Server Side Events in our application, but currently the while True loop runs indefinitely and client disconnect is not causing the task to stop. Reproducible example: @api.get("/events") async def get_events(request: ASGIRequest) -> StreamingHttpResponse: async def generate_message() -> AsyncGenerator[str, None]: while True: await asyncio.sleep(1) yield 'data: {"test": "testvalue"}\n\n' print("Working...") return StreamingHttpResponse( generate_message(), content_type="text/event-stream", headers={ "X-Accel-Buffering": "no", "Cache-Control": "no-cache", "Connection": "keep-alive", }, ) Above example will print Working... until server is closed (even if client closes connection and is not receiving the data). Any way to detect client disconnect to stop the while True loop? Already tried to return simple HttpResponse, putting code in try..except, creating def close, async def close methods on StreamingHttpResponse. django-ninja==0.22.2 django==4.2.13 uvicorn[standard]==0.29.0 -
How do I generate a PDF using pyppeteer in Django? Got error signal only works in main thread of the main interpreter
#urls.py path('pdf/', views.generate_pdf), #views.py from pyppeteer import launch import os import asyncio async def main(): browser = await launch() page = await browser.newPage() await page.goto("https://python.org") await page.waitFor(1000) await page.pdf({"path": "python.pdf"}) await browser.close() async def generate_pdf(request): print("Starting...") await main() print("PDF has been taken") return HttpResponse("PDF has been generated") I got an error: signal only works in main thread of the main interpreter. It works nicely while running in a standalone Python file but not inside Django. I got a runtime error This event loop is already running. while using async def generate_training_pdf(request): asyncio.get_event_loop().run_until_complete(main()) -
How to use LangChain to generate AI-based quiz questions in a specific JSON format in a Django application? [closed]
I'm new to LangChain and I'm working on creating a Django quiz generator app that uses AI to generate quiz questions. I want the generated questions to be in a specific JSON format as shown below: [ { "id": 1, "question": "What common aspect do physics and chemistry share?", "choices": { "a": "Laws of motion", "b": "Laws governing matter and energy", "c": "Laws of thermodynamics", "d": "Laws of electromagnetism" }, "answer": "b", "explanation": "Physics and chemistry share fundamental laws governing matter and energy, making it the correct choice." }, { "id": 2, "question": "What common aspect do physics and chemistry share?", "choices": { "a": "Laws of motion", "b": "Laws governing matter and energy", "c": "Laws of thermodynamics", "d": "Laws of electromagnetism" }, "answer": "b", "explanation": "Physics and chemistry share fundamental laws governing matter and energy, making it the correct choice." } ] Requirements: Input Parameters: The input to the model will have three parameters along with the text that the questions need to be generated from and I want it to return a response based on that. Output Format: The output should strictly be in the JSON format without any additional conversational text (e.g., no "Here are the questions you … -
Domain resolution fails for python requests-package in multithreading scenario
I am having a microservice hosted as an Azure Web App that sends outbound HTTP-POST calls based on various events. The calls have the characteristics of "fire-and-forget". Thus, I start a thread for each performed HTTP-request as follows: t = threading.Thread(target=self.perform_call, args=(target_url, notification_dto), daemon=True) t.name = f'notification_sending_{notification_dto.id}' t.start() The request itself is executed via the requests-package as follows (without any explicit session-management etc.): response = requests.post(target_url, timeout=5, headers=headers_dict, data=data_str) Sporadically, I see the following error in my log-file: Traceback (most recent call last): File "/agents/python/urllib3/connection.py", line 203, in _new_conn sock = connection.create_connection( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/agents/python/urllib3/util/connection.py", line 60, in create_connection for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/python/3.11.8/lib/python3.11/socket.py", line 962, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ socket.gaierror: [Errno -2] Name or service not known The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/agents/python/urllib3/connectionpool.py", line 790, in urlopen response = self._make_request( ^^^^^^^^^^^^^^^^^^^ File "/agents/python/urllib3/connectionpool.py", line 491, in _make_request raise new_e File "/agents/python/urllib3/connectionpool.py", line 467, in _make_request self._validate_conn(conn) File "/agents/python/urllib3/connectionpool.py", line 1096, in _validate_conn conn.connect() File "/agents/python/urllib3/connection.py", line 611, in connect self.sock = sock = self._new_conn() ^^^^^^^^^^^^^^^^ File "/agents/python/urllib3/connection.py", line 210, in _new_conn raise NameResolutionError(self.host, self, … -
Docker build . hangs indefinitely without feedback on MacOS Big Sur
I'm new to Docker, and following along a course. I went step by step creating some basic files to start a Django project on Docker, which are the following: My DockFile is this one: FROM python:3.9-alpine3.13 LABEL maintainer="user" ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /tmp/requirements.txt COPY ./app /app WORKDIR /app EXPOSE 8000 RUN python -n venv /py && \ /py/bin/pip install --upgrade pip && \ /py/bin/pip install -r /tmp/requirements.txt && \ rm -rf /tmp && \ adduser \ --disabled-password \ --no-create-home \ django-user ENV PATH="/py/bin:$PATH" USER django-user Then, my .dockerignore file is this: # Git .git .gitignore # Docker .docker #Python app/__pycache__/ app/*/__pycache__/ app/*/*/__pycache__/ app/*/*/*/__pycache__/ .env/ .venv/ venv/ Finally, the requirements reads: Django>=3.2.4,<3.3 djangorestframework>=3.12.4,<3.13 After that I'm supposed to run docker build ., but when I do it hangs and does nothing. I had to shut it down a couple of times. Any idea of what I am doing wrong or at least have some feedback? -
Template File Not Found in Django
So I have been trying to serve a template file in Django. My main issue is that the index.html page is found , but the static files (js,css,png) files are not found . They are all under the same directory as index.html file. Here are my configurations : Settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates') ], 'APP_DIRS': True, }, ] urls.py (Main) path('rest-framework/', include('rest_framework.urls')), path('api/', include('accounts.urls')), path('admin/', admin.site.urls), url(r'^rest-auth/', views.obtain_auth_token), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urls.py (App) urlpatterns = [ path('homepage/', views.index, name='index'), ] views.py def index(request): return render(request, 'index.html') And here is the exact error I get: [15/May/2024 08:31:40] "GET /api/homepage/ HTTP/1.1" 200 1837 Not Found: /api/homepage/flutter.js [15/May/2024 08:31:40] "GET /api/homepage/flutter.js HTTP/1.1" 404 2674 Not Found: /api/homepage/manifest.json [15/May/2024 08:31:40] "GET /api/homepage/manifest.json HTTP/1.1" 404 2683 My template files directory is like this: accounts\ -migrations\ -templates\ server\ media\ static\ manage.py requirements.txt How can I solve this problem? -
I can't authenticate login
I have problem with login authentication. I have successfully registered an account via the register function. class RegisterView(APIView): def post(self, request): serializer = RegisterSerializer(data=request.data) try: if serializer.is_valid(): username = serializer.validated_data['username'] password = serializer.validated_data['password'] display_name = serializer.validated_data['display_name'] user = User(username=username, password=make_password(password), display_name=display_name) user.save() return Response({'success': 'User created successfully'}, status=status.HTTP_201_CREATED) else: return Response({'error': 'Invalid credentials'}, status=status.HTTP_400_BAD_REQUEST) except Exception as e: return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) enter image description here enter image description here But I can't authenticate my login information class LoginView(APIView): def post(self, request): serializer = LoginSerializer(data=request.data) if serializer.is_valid(): username = serializer.validated_data['username'] password = serializer.validated_data['password'] print(f"Attempting login with username: {username} and password: {password}") user = authenticate(request, username=username, password=password) if user is not None: token, created = Token.objects.get_or_create(user=user) return Response({'token': token.key}, status=status.HTTP_200_OK) else: print("Authentication failed: Invalid credentials") return Response({'error': 'Invalid credentials'}, status=status.HTTP_400_BAD_REQUEST) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) enter image description here I just learned django so here is the serializer file and model file if it is necessary for you from rest_framework import serializers from .models import User class LoginSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() class RegisterSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() display_name = serializers.CharField() from django.db import models import uuid class User(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) display_name = models.CharField(max_length=191) username … -
django.urls.exceptions.NoReverseMatch: Reverse for 'detail' with arguments '('',)' not found
Why does the error message appear? I got stuck in Django Official tutorial part 5. Writing your first Django app, part 5 I understand the error message is, but I can NOT spot the cause of error. And I didn't forget to execute python manage.py makemigrations and python manage.py migrate once after I change my code. Here are commands and error messages (in conda Terminal) (myenvtest2) C:\Users\40843\mysite>python manage.py makemigrations No changes detected (myenvtest2) C:\Users\40843\mysite>python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, polls, sessions Running migrations: No migrations to apply. (myenvtest2) C:\Users\40843\mysite>python manage.py test polls 404 revindex: /polls/ Found 1 test(s). System check identified no issues (0 silenced). E ====================================================================== ERROR: polls.tests (unittest.loader._FailedTest.polls.tests) ---------------------------------------------------------------------- ImportError: Failed to import test module: polls.tests Traceback (most recent call last): File "C:\Users\40843\.conda\envs\myenvtest2\Lib\unittest\loader.py", line 394, in _find_test_path module = self._get_module_from_name(name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\40843\.conda\envs\myenvtest2\Lib\unittest\loader.py", line 337, in _get_module_from_name __import__(name) File "C:\Users\40843\mysite\polls\tests.py", line 59, in <module> response = client.get(revindex) ^^^^^^^^^^^^^^^^^^^^ File "C:\Users\40843\.conda\envs\myenvtest2\Lib\site-packages\django\test\client.py", line 836, in get response = super().get(path, data=data, secure=secure, **extra) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\40843\.conda\envs\myenvtest2\Lib\site-packages\django\test\client.py", line 424, in get return self.generic( ^^^^^^^^^^^^^ File "C:\Users\40843\.conda\envs\myenvtest2\Lib\site-packages\django\test\client.py", line 541, in generic return self.request(**r) ^^^^^^^^^^^^^^^^^ File "C:\Users\40843\.conda\envs\myenvtest2\Lib\site-packages\django\test\client.py", line 810, in request self.check_exception(response) File "C:\Users\40843\.conda\envs\myenvtest2\Lib\site-packages\django\test\client.py", line 663, in check_exception … -
My Django project is opening very slowly on the server
Please check out my site: pyterminator.com The site opens very late. I don't know what the reason is. I used dj-static package in wsgi file. Does this affect performance? wsgi.py : import os from dj_static import Cling from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings') application = Cling(get_wsgi_application()) I bought the "Starter hosting" package and deployed there. Through C-Panel. Could this be the reason for poor performance? I use these packages. arabic-reshaper==3.0.0 asgiref==3.8.1 asn1crypto==1.5.1 certifi==2024.2.2 cffi==1.16.0 chardet==5.2.0 charset-normalizer==3.3.2 click==8.1.7 colorama==0.4.6 cryptography==42.0.6 cssselect2==0.7.0 dj-static==0.0.6 Django==5.0.4 django-cleanup==8.1.0 django-tinymce==4.0.0 html5lib==1.1 idna==3.7 lxml==5.2.1 mysqlclient==2.2.4 oscrypto==1.3.0 pillow==10.3.0 pycparser==2.22 pyHanko==0.24.0 pyhanko-certvalidator==0.26.3 pypdf==4.2.0 pypng==0.20220715.0 python-bidi==0.4.2 python-dotenv==1.0.1 PyYAML==6.0.1 qrcode==7.4.2 reportlab==4.0.9 requests==2.31.0 six==1.16.0 sqlparse==0.5.0 static3==0.7.0 svglib==1.5.1 tinycss2==1.3.0 typing_extensions==4.11.0 tzdata==2024.1 tzlocal==5.2 uritools==4.0.2 urllib3==2.2.1 webencodings==0.5.1 xhtml2pdf==0.2.15 settings.py import os from pathlib import Path # ---------------------- * ------------------------- from django.contrib.messages import constants as messages # ---------------------- * ------------------------- from dotenv import load_dotenv load_dotenv() # ---------------------- * ------------------------- BASE_DIR = Path(__file__).resolve().parent.parent # ---------------------- * ------------------------- SECRET_KEY = "xxxx" # ---------------------- * ------------------------- DEBUG = True ALLOWED_HOSTS = ["pyterminator.com", "127.0.0.1", "www.pyterminator.com"] # ---------------------- * ------------------------- INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_cleanup.apps.CleanupConfig', 'tinymce', # ---> Apps <--- # 'home.apps.HomeConfig', 'post.apps.PostConfig', 'fusion.apps.FusionConfig', 'contact.apps.ContactConfig', 'c_profile.apps.CProfileConfig', ] # ---------------------- * ------------------------- MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', … -
Django forms access (file) field from relation
I have a view that locks like this: def table_form_combined(request: HttpRequest) -> HttpResponse: if request.method == "POST": formset = TransActionFormSet(data=request.POST) print(formset.errors) if formset.is_valid(): formset.save() return render(request, "evidence/table_form_combined.html", {'formset': TransActionFormSet}) My Form looks like this: class TransactionForm(ModelForm): class Meta: model = Transaction fields = ("source_id", "transaction_date", "data", "evidence", "meta_data") widgets = { 'data': Textarea(attrs={'rows': 1}), # set the row amount of # the data Text fields to 1 --> data : Name of Textfield in Model } My model (just the relevant stuff): class TransactionEvidence(Base): file = models.FileField(upload_to='evidence/') class Transaction(Base): evidence = models.ForeignKey( TransactionEvidence, on_delete=models.CASCADE, help_text="A evidence file (i.e. pdf invoice) that can be assigned to a transaction.", ) source_id = models.CharField( "Source ID", max_length=150 ) transaction_date = models.DateTimeField(default=timezone.now, help_text="The transaction date") And finally, my template locks like this: {% extends "website/base.html" %} {% block content %} <table class="table"> <thead> <tr> <th scope="col"> # </th> <th scope="col"> Name </th> <th scope="col"> Transaction Date </th> <th scope="col"> Data</th> <th scope="col"> Evidence</th> <th scope="col"> file</th> <th scope="col"> Amount</th> </tr> </thead> <tbody> {{ formset.management_form }} {% comment %} https://docs.djangoproject.com/en/3.2/topics/forms/formsets/#understanding-the-managementform, without that, the form will be invalid {% endcomment %} {% for form in formset %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {% if form.source_id.value … -
Django query with OR operator
I'm trying to do an OR operator for a Django query. But for some reason my query syntax is wrong. Not sure why it's wrong. Basically I'm trying to query for the site and get any device with Role as 'Router' or 'Other'. Below is my query. Any help is much appreciated! Thank you in advance. Method 1 tried- from django.db.models import Q numRouters= Device.objects.filter(location__name__startswith=site,Q(role__name__in=["Router"]) | Q(role__name_in=["Other"])) SyntaxError: positional argument follows keyword argument from django.db.models import Q Method 2 tried- numRouters = Device.objects.filter(location__name__startswith=site,Q(role__name__in=["Router"]) | Q(role__name__in=["Other"])) SyntaxError: positional argument follows keyword argument -
ForeignKeyWidget in django-import-export Showing ID Instead of Custom Column Value
I am using the django-import-export library to handle data import and export in my Django application. I have several models with ForeignKey relationships, and I want to display and use the custom column values instead of the IDs in my import/export files. # models.py class YearCategoryMalnutrition(models.Model): id = models.AutoField(primary_key=True) year_recorded = models.CharField(max_length=4, default="") last_update = models.DateTimeField(auto_now=True, null=True) def __str__(self): return self.year_recorded class AgeCategory(models.Model): AGE_CATEGORIES = ( ('0-5 years old (0-60 months)', '0-5 years old (0-60 months)'), ('5.08-10.0 years old (61-120 months)', '5.08-10.0 years old (61-120 months)'), ('10.08-19.0 years old (121-228 months)', '10.08-19.0 years old (121-228 months)'), ('Adults 20 years old above', 'Adults 20 years old above'), ) age_category_name = models.CharField( max_length=50, choices=AGE_CATEGORIES, default='0-5 years old (0-60 months)', ) last_update = models.DateTimeField(auto_now=True, null=True) class Meta: verbose_name_plural = "Age Categories" def __str__(self): return self.age_category_name class LevelCategory(models.Model): LEVEL_CATEGORIES = ( ('National Level', 'National Level'), ('Regional Level', 'Regional Level'), ('Province Level', 'Province Level'), ('Municipality Level', 'Municipality Level'), ('Barangay Level', 'Barangay Level'), ) level_category_name = models.CharField( max_length=50, choices=LEVEL_CATEGORIES, default='National Level', ) last_update = models.DateTimeField(auto_now=True, null=True) class Meta: verbose_name_plural = "Level Categories" def __str__(self): return self.level_category_name class NationalLevel(models.Model): id = models.AutoField(primary_key=True) country_name = models.CharField(max_length=255, default="Philippines") overweight = models.FloatField(default=0.0) underweight = models.FloatField(default=0.0) stunting = models.FloatField(default=0.0) wasting = … -
Django authentication testing failure: Authentication credentials were not provided
I am working on the user logic of my Django project. Despite the fact that logout (using session cookie authentication) works perfectly fine in the browser, it is not working during testing for some reason. It appears as if the cookie from the login response isn't being correctly saved for the subsequent request. Here are the relevant excerpts from my project code: views.py class UserLogoutView(generics.GenericAPIView): permission_classes: list[permissions.BasePermission] = [permissions.IsAuthenticated] def get_serializer_class(self) -> serializers.Serializer: return serializers.Serializer # Return basic Serializer class def delete(self, request: Request) -> Response: response: Response try: session_key: str = request.COOKIES.get("session") token: Token = Token.objects.get(key=session_key) response = Response( status=status.HTTP_200_OK, data={"detail": "Logout successful"}, ) response.delete_cookie(key="session") token.delete() except ObjectDoesNotExist: response = Response( {"error": "Session cookie not found"}, status=status.HTTP_401_UNAUTHORIZED, ) except Exception as error: print(error) response = Response( {"error": str(error)}, status=status.HTTP_400_BAD_REQUEST, ) return response tests_views.py class TestLogoutViews(TestCase): def setUp(self) -> None: self.client = Client() self.data: dict[str, str] = { "username": "testuser", "email": "test@test.com", "password": "Password1", } self.logout_url: str = reverse("user_logout") self.login_url: str = reverse("user_login") self.client.post( reverse("user_register"), json.dumps(self.data), content_type="application/json", ) self.data.pop("email") def test_logout_view_correct_DELETE(self) -> None: # Log in first response: HttpResponse = self.client.post( self.login_url, json.dumps(self.data), content_type="application/json", ) print() print(response.status_code, self.client.cookies) print() # Send the DELETE request response: HttpResponse = self.client.delete(self.logout_url) # Check … -
Changing just the name of the django settings file causes error
I ran into a problem trying originally to use cookiecutter-django when using the docker compose production.yml vs the local.yml files Managed to shrink it down to this: https://github.com/xmclej/django-testing-01 The code is currently defaulted to use "config.settings.base" See the README.md file for the very minimal setup and instructions The problem is that when I change only the DJANGO_SETTINGS_MODULE value from "config.settings.base" to "config.settings.trial". Noting that the two files are identical inside. Get error.. ModuleNotFoundError: No module named 'config.settings.trial' Any thoughts? Originally was trying to use the default cookiecuttter approach of split settings files. Until I hit this little bug. Using config.settings.base ... it works (venv) D:\Beanycode\Projects\django-testing-01>docker compose -f production.yml up [+] Running 2/2 ✔ Container django-testing-01-postgres-1 Running 0.0s ✔ Container django-testing-01-django-1 Recreated 0.1s Attaching to django-1, postgres-1 django-1 | PostgreSQL is available django-1 | start of production entrypoint django-1 | django django-1 | /app django-1 | 10 django-1 | 20 django-1 | 30 django-1 | 50 django-1 | 60 django-1 | [2024-05-14 23:37:22 +0000] [1] [INFO] Starting gunicorn 21.2.0 django-1 | [2024-05-14 23:37:22 +0000] [1] [INFO] Listening at: http://0.0.0.0:5000 (1) django-1 | [2024-05-14 23:37:22 +0000] [1] [INFO] Using worker: sync django-1 | [2024-05-14 23:37:22 +0000] [9] [INFO] Booting worker with pid: … -
djnago scrapy TypeError: RepoSpider.start_requests() missing 1 required positional argument: 'url'
I.m trying to build a webapp to fetch data from a repo. Its near completion but i am facing this error currently The codes: this is the spider code import scrapy from App.models import Repo class RepoSpider(scrapy.Spider): name = "RepoSpider" allowed_domains = ["github.com"] start_urls = [] def start_requests(self, url): yield scrapy.Request(url) def parse(self, response): url = response.url url_parts = url.split('/') username = url_parts[-1] repo = url_parts[-2] description = response.css('.f4.my-3::text').get(default='').strip() language = response.css('.color-fg-default.text-bold.mr-1::text').get(default='') stars = response.css('a.Link.Link--muted strong::text').get(default='0').strip() yield { 'username': username, 'repo': repo, 'description': description, 'top_language': language, 'stars': stars } scraped_repo = Repo( url=url, username=username, description=description, top_language=language, stars=stars ) scraped_repo.save() django view from django.shortcuts import render, redirect from .models import Repo from scrapy.crawler import CrawlerProcess from .tester.tester.spiders.repo import RepoSpider def index(request): if request.method =='POST': url = request.POST.get('url') process = CrawlerProcess() process.crawl(RepoSpider, url) process.start() return render(request, 'index.html') Tried whatever i could get on, but running out of options now. This is a project i need to get done as soon as possible, it would mean a lot to me to have this working -
Is there a way to restrict users to only see children of a parent element they belong to in Django Rest?
I have built a Django REST app for a client that allows users to join communities. The Community model has 20+ models that link back to it in some way (things like events, event dates, meetings, messages etc). I need a way to restrict users to only being able to perform CRUD operations on elements belonging to communities they are a part of. For example if user "John Smith" is a member of the "Animal Rescue Volunteers" community, he should only be able to read messages for that community and should not be able to create/edit messages in other communities. I have seen people use the get_queryset method of a ViewSet to restrict RUD processes like so: class MessageView(viewsets.ModelViewSet): queryset = Message.objects.all() serializer_class = MessageSerializer def get_queryset(self): return self.queryset.filter(message__community__in=self.request.user.communities) However this doesn't solve the problem with Creates and needs to be applied to each ViewSet to work. Is there a better way to do this? -
Only able to upload PNG images with django-ckeditor-5
I am building a simple blog application in Django and istalled django-ckeditor-5. I am able to upload PNG images with no problem, but when I try to upload JPG image of any size (or any other format), the browser throws an alert localhost:8000 says Couldn't upload file: filename.jpg I didn't include any restrictions in the models or in the settings. I basically copied the ckeditor configurations from their documentation. I didn't have this problem with the previous version of ckeditor, but apparently it has some vulnerability issues... Any ideas how I can enable other file formats for images? -
"Method \"GET\" not allowed."
I really need help explaining why I pass the method as DELETE but the error appears "Method "GET" not allowed." Thank you very much. class DeleteUserByUsernameView(APIView): def delete(self, request, username): try: instance = User.objects.filter(username=username) instance.delete() return HttpResponse("Success") except Exception as e: return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('delete/user/<str:username>/', views.DeleteUserByUsernameView.as_view()), path('register/', views.RegisterView.as_view(), name="Register"), path('login/', views.LoginView.as_view(), name="Login"), ] enter image description here enter image description here enter image description here -
Django cannot find page with multiple similar URL paths
I am trying to create a Django site with different views/models spanning from the same level of the URL structure. Here is the URL structure I am trying to create: HOME PAGE -- Country --- State ---- City --- Topic ---- Article I am using the following code in urls.py: urlpatterns = [ path( "<slug:country_slug>/<slug:state_slug>/<slug:city_slug>/", CityIndex.as_view(), name="city_index", ), path( "<slug:country_slug>/<slug:topic_slug>/<slug:article_slug>/", ArticleDetail.as_view(), name="article_detail", ), path( "", HomeIndex.as_view(), name="home", ), The City Index path works fine. The issue I have is trying to access an article. Django only seems to attempt to match the first URL path. I enter a URL: "example-country/example-topic/example-article" Django returns the following error message: Page not found (404) No Destination matches the given query. Request Method: GET Request URL: http://127.0.0.1:8000/example-country/example-topic/example-article/ Raised by: content.views.destinations.CityIndex It seems that, because the pattern is similar to the URL pattern for "city_index", it attempts to match this, then return a 404 error. It doesn't move on to check the next URL pattern for "article_detail", which would then match an article and return a template. I tried switching the "article_detail" URL path to come first, above "city_index". This causes "article_detail" to return a template correctly, but now "city_index" does not. Effectively, Django will match … -
How to save data by Button Click handler in DJANGO
Let's assume I have a buy button. In my card. On the card, I'm showing some car details. If the user clicks on the buy button the car/product details will be saved into a new Table. How i can implement this with the Button Click handler in DJANGO? <div class="card-body"> <img src="{{object.car_image.url}}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title fw-bold text-uppercase gap-2"> {{object.car_name}} </h5> <p class="card-text btn btn-sm btn-light disabled">Brand : {{object.car_brand}}</p> <div class="d-flex gap-2"> <p class="btn btn-sm btn-primary disabled">Quantity :{{object.quantity}}</p> <p class="btn btn-sm btn-warning disabled ">Price :{{object.price}}</p> </div> <p class="card-text">{{object.description }}</p> {% if user.is_authenticated %} <button class='btn btn-sm btn-success'>Buy Car</button> {% endif %} </div> -
when trying to send the message form docker worker container it's not sending it's getting connection timeout 110
I have all the firewall port active, tried telnet and other to test connectivity to smtp server it's giving response, also when trying to send the mail in django with send_mail() it's able to sending but when trying to send mail using from django.core.mail import EmailMessage send() it's getting connection timeout 110 the i also increase the timeout to 60s by increasing it in django setting.py for email backend still when trying to send mail it's showing this log error return self.get_connection(fail_silently).send_messages([self]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/matrixadm/.local/lib/python3.11/site-packages/django/core/mail/backends/smtp.py", line 134, in send_messages sent = self._send(message) ^^^^^^^^^^^^^^^^^^^ File "/home/matrixadm/.local/lib/python3.11/site-packages/django/core/mail/backends/smtp.py", line 152, in _send self.connection.sendmail( File "/usr/local/lib/python3.11/smtplib.py", line 902, in sendmail (code, resp) = self.data(msg) ^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/smtplib.py", line 580, in data (code, msg) = self.getreply() ^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/smtplib.py", line 398, in getreply line = self.file.readline(_MAXLINE + 1) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/socket.py", line 706, in readinto return self._sock.recv_into(b) I tried to send mail but it's showing connection timeout 110 error -
Unable to view the table in Django admin panel
Okay so i am new to django. I created a superuser and then i created a 'Customer' model as shown below in models.py inside my app called 'products' Now , ran the migration command i.e python manage.py makemigrations followed by python manage.py migrate. After i log into the admin panel i see the 'Customers table and as soon as i click on it i get this error attached in the screenshot. Note: A weird thing i noticed , i did not get the migrations directory even after i ran the migration command The Customer model i defined: `from django.db import models Create your models here. class Customer(models.Model): GENDER=( ('Male','Male'), ('Female','Female') ) name=models.CharField(max_length=200) email=models.EmailField(max_length=200) Mobile_Number=models.CharField(max_length=100) Gender=models.CharField(max_length=200,choices=GENDER) admin.py: from django.contrib import admin # Register your models here. from .models import Customer admin.site.register(Customer) The error that i am getting: enter image description here -
Lock file "postmaster.pid" contains wrong PID
I started my app with docker-compose.yml. Everything starts fine and works, but after a few minutes container database stops with lock file "postmaster.pid" contains wrong PID: 7834 instead of 1. I tried to delete postmaster.pid inside docker and containers, but this didn't help. I also did this procedure: How do I fix stale postmaster.pid file on Postgres?. But the problem persists. I don't understand what to do. I want to notice that I've added these lines to /opt/homebrew/var/postgresql@15/postgresql.conf and /opt/homebrew/var/postgresql@15/pg_hba.conf: postgresql.conf # Add settings for extensions here listen_addresses = '*' pg_hba.conf host movies_database app 0.0.0.0/0 md5 /opt/homebrew/var/postgresql@15/postmaster.pid 8111 /opt/homebrew/var/postgresql@15 1715706343 5432 /tmp * 936360 3407872 ready /var/lib/postgresql/data/postmaster.pid 8234 /opt/homebrew/var/postgresql@15 1715706583 5432 /tmp * 936360 3473408 ready docker logs database-1 | 2024-05-14 19:32:32.038 [1] LOG: lock file "postmaster.pid" contains wrong PID: 7834 instead of 1 database-1 | 2024-05-14 19:32:32.038 [1] LOG: performing immediate shutdown because data directory lock file is invalid database-1 | 2024-05-14 19:32:32.038 [1] LOG: received immediate shutdown request database-1 | 2024-05-14 19:32:32.056 [1] LOG: database system is shut down database-1 exited with code 0 docker-compose.yml version: '3.8' services: django: build: context: . volumes: - "./movies_admin:/movies_admin" env_file: - "movies_admin/config/.env" depends_on: - database - elasticsearch database: image: postgres:15.7 environment: - … -
Django Update on UniqueConstraint
I'm trying to work with UniqueConstraint but I've been facing some issues trying to update it the way I want. I have the following model class QueryModel(models.Model): id = models.AutoField(_("query id"), primary_key=True) user = models.ForeignKey(UserModel, on_delete=models.CASCADE) name = models.CharField(_("query name"), max_length=150) status = models.CharField( _("query status"), choices=QueryStatus.choices, default=QueryStatus.ACTIVE, ) is_favorite = models.BooleanField(_("favorite"), default=False) date_created = models.DateTimeField(_("date created"), auto_now_add=True) class Meta(object): app_label = "app" db_table = "query" constraints = [ models.UniqueConstraint( fields=("user",), condition=Q(is_favorite=True), name="unique_favorite_per_user", ) ] So in my system, users can create queries and set them as favorites, but each user can only have 1 favorite query, so I created the UniqueConstraint to enforce that business rule. Then I would have an endpoint to set a query as favorite, but is there a way for me to update that field without having to check all is_favorite fields of each user and manually setting them to False? I found this StackOverflow post from 2 years ago that proposes a solution, but this solution is not working for me, I would really appreciate some help -
Django models: a player can play many games and a game can be played exactly by two players?
I have a problem in my django models.. i have 2 models (tables) Player and Game as many to many relationship, and a third model as a intermediate table between them, that has player username as a foreignkey (the username is the player's table pk) and a game_id fk as well, and an additional attribute score, the problem is more than 2 players can have the same game, and this is not what i want, what i want is every single game can be played exactly and only by two players. how can achieve that using django? here is the models: class Player(models.Model): username = models.CharField(max_length=20, primary_key=True) fname = models.CharField(max_length=20, blank=False) lname = models.CharField(max_length=20, blank=False) avatar = models.ImageField(upload_to='./app/avatars/', blank=True, null=True) is_online = models.BooleanField(default=False) game_theme = models.ImageField(upload_to='./app/themes/', blank=True, null=True) played_games_num = models.IntegerField(default=0) def __str__(self): return self.username class Game(models.Model): mode_choices = { 'classic': 'Classic', 'vs_robot': 'Vs Robot' } difficulty_choices = { -1: 'Vs Player', 1: 'Easy', 2: 'Medium', 3: 'Hard' } game_id = models.AutoField(primary_key=True) mode = models.CharField(max_length=10, choices=mode_choices) difficulty = models.IntegerField(choices=difficulty_choices) game_date_time = models.DateTimeField(auto_now_add=True) duration = models.IntegerField() players = models.ManyToManyField(Player, through='Player_game') def __str__(self): return str(self.game_id) class Player_game(models.Model): username = models.ForeignKey(Player, on_delete=models.CASCADE) game = models.ForeignKey(Game, on_delete=models.CASCADE) score = models.IntegerField() class Meta: unique_together = …