Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to improve OCR extraction from low-contrast and blurred newspaper images using Python and Tesseract?
I am working on a Django application to extract text from images of newspaper clippings. These images often have low contrast and blurring, and contain various text blocks such as headings, dates, small text, bold text, and some blurred letters. The images have dimensions of approximately 256x350 pixels with a resolution of 96 dpi. I have tried multiple preprocessing techniques to enhance the images before feeding them to Tesseract OCR, but I am still not getting satisfactory results. Here is my current code: import os from django.shortcuts import render from django.core.files.storage import FileSystemStorage import pytesseract import cv2 from PIL import Image import numpy as np import re # Set Tesseract command pytesseract.pytesseract.tesseract_cmd = '/usr/bin/tesseract' def clean_text(text): # Example of cleaning common OCR errors text = re.sub(r'\s+', ' ', text) # Remove extra whitespace text = re.sub(r'[^\w\s,.!?;:()"\']', '', text) # Keep common punctuation return text.strip() def home(request): return render(request, 'layout/index.html') def preprocess_image(image_path): # Read the image image = cv2.imread(image_path, cv2.IMREAD_COLOR) if image is None: raise ValueError(f"Error loading image: {image_path}") # Convert to grayscale gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Histogram equalization to enhance contrast gray = cv2.equalizeHist(gray) # Increase contrast further if necessary gray = cv2.convertScaleAbs(gray, alpha=2.5, beta=50) # Resize the image … -
I want to use Transaction atomic with flask
I've experience of using transaction atomic decorator in django but now i'm using flask framework. Can anyone suggest me what is the equivalent for the same. I'm dealing with mongodb and mysql at the same time. I'm trying to achieve transaction atomic in flask. -
How to LEFT OUTER JOIN without foreign key using django orm
I have following Models: class User(Model): ### user fields ### class CaseModel(Model): id = # django build in id field owner = models.ForeignKey('User') ### other fields ### class DraftMessageModel(Model): entity_id = models.IntegerField(null=True, blank=True) # CaseModel.id is linked to this ### other fields ### I need to construct queryset that generates following SQL: SELECT C.id, C.some_field, D.another_field, U.username FROM CaseModel AS C LEFT OUTER JOIN User AS U ON (C.owner_id = U.id) LEFT OUTER JOIN DraftMessageModel AS D ON (C.id = D.entity_id) WHERE C.owner_id = 100 AND < some extra condition > I know it's trivial question but I couldn't handle it queryset.extra or queryset.annotate(draft_message=FilteredRelation()). Here is what I've tried so far: queryset.annotate queryset = CaseModel.objects.filter(owner_id=100) queryset = queryset.annotate( draft_message=FilteredRelation( 'draftmessagemodel', condition=Q(draftmessagemodel__entity_id=F('id')) ) ) # error: Cannot resolve keyword 'draftmessagemodel' into field. Choices are: <CaseModel's other fields> queryset.extra queryset = CaseModel.objects.select_related('owner').filter(owner_id=100) queryset = queryset.extra( select={ 'draftmessagemodel__id': 'draftmessagemodel.id', 'draftmessagemodel__text': 'draftmessagemodel.text', }, tables=['draftmessagemodel'], where=[ 'casemodel.id = draftmessagemodel.entity_id' ] ) generating undesired sql: SELECT "casemodel"."id", "user"."username", (draftmessagemodel.id) AS "draftmessagemodel__id", (draftmessagemodel.text) AS "draftmessagemodel__text", <some other fields> FROM "casemodel" LEFT OUTER JOIN "user" ON ( "casemodel"."owner_id" = "user"."id" ), -- I didn't unserstand from where this comma come here "draftmessagemodel" WHERE ( "casemodel"."owner_id" = 100 AND … -
Visual Studio Code auto update last night and now my Django app crashes during startup
Yesterday my Django app ran on my VSC development server just fine. During the night VSC updated to version 1.92. This morning the app crashes before it even gets started. Exception has occurred: RuntimeError 'cryptography' package is required for sha256_password or caching_sha2_password auth methods. Internet search seems to indicate I need to load the Crypto package, but that does not make sense since the app ran fine yesterday. I checked my app against a CD backup copy from last week, it is identical NO changes. The check was performed using a program called axaris and it checked EVERYTHING in the app from images to code and libraries - everything is the same. It might be the upgrade corrupted the crypto libary? Not sure. I don't want to start making changes to my ubuntu 20.4 machine before I gather more information. Any suggestions? I have tried to place some breakpoints to isolate the code causing the error but the error occurs VERY early just as the server is checking the code. I was performing a MYSQL search and once the query completed the error occured when I tried to use the result. I commented out the code and tried to start … -
Broadcast data only on POST request with dJango SSE Server Side Events
I am trying to broadcast SSE to all clients once the user makes a request. I was able to get this basic example up and running async def dashboard_oc_interface(request): """ Sends server-sent events to the client. """ async def event_stream(): i = 0 while True: # yield {'id' : random.randint(0, 99) , 'status' : 'success'} yield f'data: {random.choice(range(1,40))},SUCCESS\n\n' await asyncio.sleep(100) return StreamingHttpResponse(event_stream(), content_type='text/event-stream') But I am unsure how to do it below: # user will be making this request def post_request(request): success = random.choice([True, False]) # NOT ACTUAL LOGIC return JsonResponse ({'success' : success }) # I would like to stream the success data from above async def stream(): # HOW CAN I STREAM ONLY WHEN post request # we will listen here async def event_stream(request): return StreamingHttpResponse(stream(), content_type='text/event-stream') async def dashboard_oc_interface(request): """ Sends server-sent events to the client. """ async def event_stream(): i = 0 while True: # yield {'id' : random.randint(0, 99) , 'status' : 'success'} yield f'data: {random.choice(range(1,40))},SUCCESS\n\n' await asyncio.sleep(100) return StreamingHttpResponse(event_stream(), content_type='text/event-stream') -
TemplateSyntaxError Could not parse the remainder
I have this bit of jinja2 in my Django template: {% for filesystem, total_quota, total_usage, df_usage in totals_by_filesystem %} <tr> <td>{{ filesystem }}</span></td> <td>{{ total_quota | filesizeformat }}</td> <td>{{ total_usage | filesizeformat }}</td> <td>{{ df_usage * 100 }}</td> </tr> {% endfor %} When I run it I get this error message: Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: ' * 100' from 'df_usage * 100' I am pretty sure my syntax {{ df_usage * 100 }} is correct. What am I missing here? -
Stop a Bash script run with Docker
The Dockerfile code is as follows: FROM python:3.10 COPY ./ /data/ WORKDIR /data/ RUN pip install pipenv RUN pipenv install RUN pipenv run python src/manage.py makemigrations RUN pipenv run python src/manage.py migrate # Copy the start script COPY start.sh /start.sh RUN chmod +x /start.sh ENTRYPOINT ["/start.sh"] And the code of my script is the following #!/bin/bash # Start the background process pipenv run python src/manage.py send_email & # Start the Django development server pipenv run python src/manage.py runserver --insecure 0.0.0.0:8000 The problem is that send_email was programmed to send an email every minute as a test and I can't stop the script. These were the steps I followed to try to cancel said process: Stop the container: docker stop f16. Remove the container: docker rm f16. Remove the image: docker rmi test:01. Delete the start.sh file. Clean up: docker system prune. But the emails keep coming to me. I also tried to locate the process with "ps aux", but it's not there. Can someone help me please? I caused a spam attack on myself. -
Django profiling threads? / optimisation
I've got two simple applications in django. Only running one of them, creates 47 threads on hosting server. While trying to run the second one, I've got already hosting error- because of threads limitations... The question is - is it possible somehow to limit it in django application, or am I able somehow to find places in django code I'm doing something wrong?? Is it normal, that simple django operations like - login ,or db querying, or displaying output via template create 47 threads? -
How do I display data from my Postgresql table on my Django website
I've been trying to display my Postgresql table's data on my Django website and I've been using AWS RDS to connect my Postgresql to my Django. The issue is that it's not displaying anything when there is 3 populated test data inside the table. So how can I display the contents in my table correctly? I'm currently running AWS RDS on Ubuntu with the free tier. In my Postgresql side, I have a server called mywebsiterds and 3 databases: mywebsitedb postgres and rdsadmin. However, I'm only using mywebsitedb and created a new schema inside it called newdb (there is 2 schemas total in this called newdb and public). Inside the newdb schema, I created: CREATE TABLE newdb.folders ( folderID SERIAL PRIMARY KEY, folderName VARCHAR(50), userID VARCHAR(50) ); then populated it with: INSERT INTO newdb.folders (folderName, userID) VALUES ('test folder 1', 'user1'); INSERT INTO newdb.folders (folderName, userID) VALUES ('test folder 2', 'user2'); INSERT INTO newdb.folders (folderName, userID) VALUES ('test folder 2', 'user2'); I've connected my Django to my AWS RDS in the settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ.get("DB_NAME", None), 'USER': os.environ.get("DB_USERNAME", None), 'PASSWORD': os.environ.get("DB_PASSWORD", None), 'HOST': os.environ.get("DB_HOST", None), 'PORT': '5432' } } In my Django, I created … -
Final year topic [closed]
I am thinking about to create one web application using pythno and django name is Project match maker. It will help students to find the perfect group partner for their project according their requirements and skill set. I have tried to take some advise my tutors but they all are saying this is not that complicate and I have tried to advise them because this is similar like tinder and other dating application. What are your views Any suggestion -
Can non-displayed fields of a Django model be altered during custom form validation but before committing model's data?
for the last few weeks I've been working on my first Django project: a database to register all incoming orders from Customers for a generic enterprise. Let's assume that each one of the sale reps could be assigned to a specific Customer for a whole natural year and assignments may vary from one year to another (i.e. agent A assigned to customer A in 2024, whereas in 2025, agent B might be in charge of customer A). As a start, I decided to use a FK inside Orders model to refer to the associated Product and Customer. At the same time, the Assignments model would also keep a couple of FK to the Customer and Agent tables, so everything could be connected, accessible and data loops were avoided in my relational diagram. Still, this solution was really painful to get some data, specially when I needed to retrieve filtered data for the final templates... so I decided to turn everything upside down and take a different approach: class Order (models.Model): assignment = models.ForeignKey("Assignment", on_delete=models.RESTRICT) product = models.ForeignKey("Producto", on_delete=models.RESTRICT) quantity = models.PositiveIntegerField(default=1) order_date = models.DateField() price = models.DecimalField(max_digits=10, decimal_places=2) class Assignment (models.Model): assignment_year = models.PositiveSmallIntegerField() customer = models.ForeignKey("Customer", on_delete=models.CASCADE) agent = … -
Django `Not Found: /payment_getway/` Error - URL Path Not Resolving
I’m encountering a Not Found: /payment_getway/ error in my Django application. Despite setting up the URL path and view function, Django cannot find the specified URL. I’ve provided all relevant code snippets and configurations below. I’m not sure what might be causing this issue. Here’s a brief overview of what I’ve done: URL Configuration: In my app's urls.py, I have defined the path for the payment_getway view function: urlpatterns = [ path('payment_getway/', payment_getway, name='payment_getway'), path('order-confirmation/', order_confirmation, name='order_confirmation'), ] View Function: The view function payment_getway is defined as follows: from django.shortcuts import render, redirect, get_object_or_404 from django.utils import timezone from .models import CartOrder, Address def payment_getway(request): if request.method == "POST": user = request.user address_id = request.POST.get('address_id') # Ensure this ID is passed in your form # Retrieve the address instance address_instance = get_object_or_404(Address, id=address_id, user=user) # Create a new CartOrder instance order = CartOrder( user=user, full_name=address_instance.name, email=address_instance.email, mobile=address_instance.mobile, address=address_instance, # Assign the Address instance here landmark=address_instance.landmark, city=address_instance.region, state=address_instance.region, # Update as per your address model postalCode=address_instance.pin, item="Your Item", # Update this as necessary price=100.00, # Example price, adjust accordingly saved=0.00, # Example saved amount, adjust accordingly shipping_method="Standard", # Update this as necessary tracking_id="Tracking ID", # Example tracking ID tracking_website="Tracking Website", # … -
Django query to sum the n largest related values
I have a db that tracks players' scores over a number of games. I want to create a leaderboard using each player's 4 highest scoring games. Here are my models: class Event(models.Model): name = models.CharField(max_length=120) class Player(models.Model): name = models.CharField(max_length=45) class Game(models.Model): name = models.CharField(max_length=15) class Score(models.Model): player = models.ForeignKey(Player, on_delete=models.CASCADE) game = models.ForeignKey(Game, on_delete=models.CASCADE) event = models.ForeignKey(Event, on_delete=models.CASCADE) score = models.IntegerField() class Meta: unique_together = ["player", "event", "game"] I've tried using a subquery, but it seems like my slice is being ignored and the sum returned is all of the player's scores, not just their top 4 scores: scores = Score.objects.filter(player=OuterRef('pk'), event=myEvent).order_by('-score')[:4] scores = scores.annotate(total=Func(F("score"), function="SUM")).values('total') leaders = Players.objects.annotate(total=Subquery(scores)).order_by('-total') Any ideas on how to get the subquery working? Or a better way to approach the problem? -
Conditional Rendering in Svelte Based on Server's Response
I am building a web application with Django as the server and Sveltekit on the client. During the registration process, a link with a token is sent from the server to the user's provided email, when they visit their mailbox and click on the link they are redirected to the SvelteKit's domain. Now, here is the problem - the client sends the token to the server for validation, and on the server I have a view that validates the token to see if it is valid or expired and sends the appropriate response to the client. Now, depending on the response received, I want to conditionally render out the right block of code to the user. If the server says the token is valid, they can finish their registration, otherwise, they need to resubmit their email for another token to be sent. The issue I have seems to be with my SvelteKit and not my server. This is my views.py - @method_decorator(csrf_exempt, name='dispatch') class ValidateTokenView(View): def get(self, request, token, *args, **kwargs): try: # Check if the token exists in the database token_instance = EmailConfirmationToken.objects.filter(token=token).first() print(f"Token received: {token}") print(f"Token instance retrieved: {token_instance}") if token_instance: print(f"Token created at: {token_instance.created_at}") is_expired = token_instance.is_expired() … -
Djoser Create User keeps returning field required and is not creating users
I ran into a problem in postman that was not there until yesterday when I was working with it and it was working fine, but now it is not working anymore. I'm trying to create a user using djoser default path, but whenever I send request, I face required field for username and password while both exist, I also send email field which is required by django, but no help. I tried some hints over internet but no luck. In setting, the code is like this for djoser: # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', # djoser 'djoser', # djoser 'main', ) # Password validation # https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] REST_FRAMEWORK = { # 002 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', # 012 Session --> Tokan #djoser 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticatedOrReadOnly', ), 'DEFAULT_PAGINATION_CLASS': # 011 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 1, 'DEFAULT_THOTTLE_CLASSES': ( # 014 'rest_framework.throttling.AnonRareThrottle', 'rest_framework.throttling.UserRareThrottle', ), 'DEFAULT_THROTTLE_RATES': { # 014 'anon': '5/minute', 'user': '10/minute', }, } SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME": timedelta(minutes=5), "REFRESH_TOKEN_LIFETIME": timedelta(days=1), "ROTATE_REFRESH_TOKENS": False, "BLACKLIST_AFTER_ROTATION": False, "UPDATE_LAST_LOGIN": False, # djoser } DJOSER = { 'SERIALIZERS': { 'user_create': … -
Multi Tenancy in django with user custom domains
I have a project that is currently running with an app called knowledgebase. In Knowledgebase, users can log in and see the articles created by other users in their company. There are 2 types of articles, public and private articles. Public articles can be accessed by anyone, whether logged in or not. All public articles are currently found in a public knowledgebase which is basically a page on a route like /articles/public/company-1 which shows all public articles by company 1 and we may have another like /articles/public/company-2 which shows public articles by company 2 and so on. We are currently thinkin of adding custom user domains to the project such that company 1 can add a domain like company1.com which will basically return similar view as /articles/public/company-1. Company 2 can also add company2.com and return their public articles too. How can we achieve this? Additional info: The frontend is on react and the backend running on django-rest-framework. The apsp are hosted separately in heroku and domains are from cloudflare. NOTE: we are open to any solutions, even if making the public articles a separate project. I have tried checking out projects like django-tenants but still not sure of how the … -
How to Host a Django Project with PostgreSQL and Celery on a Platform with Fixed Yearly Pricing?
I am a freelancer with a full-time job, and I am looking for a hosting solution for my Django project that requires minimal oversight and provides a fixed yearly price. Here are my specific requirements: Ease of Use: I prefer a user-friendly interface as I don’t have much time to manage and monitor the hosting environment. Managed Services: I need a hosting provider that handles most of the backend tasks such as security updates, backups, and scaling automatically. PostgreSQL Support: My Django project uses PostgreSQL, so the hosting solution should support this database. Celery Integration: My project also uses Celery for background tasks, so the hosting solution should support easy integration and management of Celery and a message broker like Redis or RabbitMQ. Fixed Yearly Pricing: I would like to have a predictable cost to effectively charge my clients, ideally with a fixed yearly pricing plan. Stability and Reliability: The hosting should be stable and reliable with good performance. Minimal Work: As I am balancing multiple responsibilities, the hosting solution should require minimal work from my end after the initial setup. I have considered using Hostinger for hosting my Django project because it offers a user-friendly interface and affordable plans. … -
how to fetch data from wordpress
how to intagrate wordpress. and how to fetch the blog post content from the wpordpress site? this is my get request url: https://wp.com/oauth/authorize?client_id=JFfZZ6rA41FU0MAWI1nKzGGX8ZrcCtEFpPMiun5q&response_type=code&redirect_uri=http://localhost&scope=basic it show this response: Forbidden You don't have permission to access this resource. Apache/2.4.41 (Ubuntu) Server at wp.ailaysa.com Port 443 how to get authorization code and then access code? -
ValueError at/account/logout
i have these codes in my django 5.0.7 and got this error which says: The view accounts.views.logout_view didn't return an HttpResponse object. It returned None instead. it seems like[text] but i have tried these: from django.urls import path from. import views from django.contrib.auth import views as auth_views urlpatterns = [ path('',views.home), path('login/', auth_views.LoginView.as_view(template_name='accounts/login.html'), name='login'), path('logout/', views.logout_view, name='logout'),] forms.py: class LogoutForm(forms.Form): confirm_logout = forms.BooleanField(label='Confirm Logout') views.py: def logout_view(request): if request.method == 'POST': form = LogoutForm(request.POST) if form.is_valid(): form.save() return redirect('home') # Replace 'home' with your desired redirect URL else: form = LogoutForm() # Create an empty form for GET requests return render(request, 'logout.html', {'form': form}) -
Order of filters affect the query result in Djongo
I use Djongo package to connect to MongoDB from my Django app. However, there is inconsistency in the query results, even though not expected. Here is my model: class Item(models.Model): name = models.CharField(max_length=100) description = models.TextField() date = models.DateTimeField(db_index=True) port_inventory_id = models.IntegerField(db_index=True) This query first filters by port_inventory_id, then date__range and returns the correct result items = Item.objects.filter(port_inventory_id=999999).filter(date__range=(date_from, date_to)) However, this query first filters by date__range, then port_inventory_id and returns the same number of items without the filter(port_inventory_id=999999) items = Item.objects.filter(date__range=(date_from, date_to)).filter(port_inventory_id=999999) I also tried making one filter call with two filters items = Item.objects.filter(date__range=(date_from, date_to), port_inventory_id=999999) And also reverse items = Item.objects.filter(port_inventory_id=999999, date__range=(date_from, date_to)) The only it works is this: items = Item.objects.filter(port_inventory_id=999999).filter(date__range=(date_from, date_to)) I did not expect the result to change this way. Any help is much appeciated... -
How to add authentication to a Django custom admin view?
I created a custom admin view in django for one of the models. But the url is available to anyone who is not logged it. from django.contrib import admin from django.urls import path from django.shortcuts import render, redirect from .models import Question from django.contrib.admin.views.decorators import staff_member_required class QuestionAdmin(admin.ModelAdmin): list_display = ('question_text', 'pub_date') # Your model fields def get_urls(self): urls = super().get_urls() new_urls = [path('upload-csv/',self.upload_csv),] return new_urls + urls @staff_member_required def upload_csv(self,request): return render(request,"admin/csv_upload.html") admin.site.register(Question,QuestionAdmin) I tried adding the staff_member_required decorator but there is an error message saying 'QuestionAdmin' object has no attribute 'user' -
How does Django know that it needs to slugify title field?
@admin.register(Post) class PostAdmin(admin.ModelAdmin): list_display = ['title', 'slug', 'author', 'publish', 'status'] list_filter = ['status', 'created', 'publish', 'author'] search_fields = ['title', 'body'] prepopulated_fields = {'slug': ('title',)} raw_id_fields = ['author'] date_hierarchy = 'publish' ordering = ['status', 'publish'] I know that prepopulated_fields doesn't only slufigy fields. How does Django know that slug field should be populated with a slug of the title? -
I get an error: "AttributeError: type object 'UserList' has no attribute 'as_view'", like, it doesn't see "as_view()" [closed]
I get an error: "AttributeError: type object 'UserList' has no attribute 'as_view'", like, it doesn't see "as_view()" My urls.py in Userapp from django.urls import path from .views import * urlpatterns = [ path('list', UserList.as_view(), name = 'user-view') ] views.py: from django.shortcuts import render from rest_framework.views import APIView from django.contrib.auth.models import User from .serializer import UserSerializer from rest_framework import response class UserList(): def get(self, request, *args, **kwargs): user_list = User.objects.all() serializer = UserSerializer(instance = user_list, many = True) return response(data = serializer.data) serializers.py: from rest_framework.serializers import ModelSerializer from django.contrib.auth.models import User class UserSerializer(ModelSerializer): class Meta: model = User fields = ['username', 'email', 'first_name',] -
Django can't find urls
Page not found in django. I already built startapp named posts already update the settings.py - apps - posts and put include in urls.py. still doesn't work, before posts, I have sample html file since I'm just learning, they both worked, posts doesn't. I did try rework or rewrite it, but still same error. YT don't have errors but I have -
problems with django logout Url
I have a problem with logout, which is when I define the logout path in urls.py: path ('logout/', auth_views.LogoutView.as_view(template_name='accounts/logout.html'), name='logout'), I get HTTP error 405, which says: this page isn't working right now but when i change the path to: path ('logout/', auth_views.LoginView.as_view(template_name='accounts/logout.html'), name='logout'), it displays logout page, even though, technically, the user is still logged in and the profile is displayed while it should be anonymous! settings.py LOGIN_URL = '/account/login/' LOGOUT_URL = '/account/logout' urls.py from django.urls import path from. import views from django.contrib.auth import views as auth_views urlpatterns = [ path ('login/', auth_views.LoginView.as_view(template_name='accounts/login.html'), name='login'), path('logout/', auth_views.LoginView.as_view(template_name='accounts/logout.html'), name='logout'),