Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Import 'django.urls' could not be resolved from source Pylance(Report Missing Module Source)
For configuring the global URLconfig on a project name, the codes "from django.urls import include, path" was required. When implemented on VScode, the warning is shown: 'django.urls could not be resolved from source--Pylance'. I followed exactly as per the tutorial in W3 school. I am new to this area. I am unable to detect the mistake on my part despite several checking on the step by step procedure detailed in the tutorial -
Authorize.Net throws "User authentication failed due to invalid authentication values" but works in sandbox. All credentials are verified as correct
I've test it for valid card and also few times I recreate transaction keys but it helpless. I checked all forums about this. Ive got 007 code error which says Posting a live account's API Login ID and Transaction Key to the test environment at https://apitest.authorize.net/xml/v1/request.api. For live accounts, please post to https://api.authorize.net/xml/v1/request.api instead. Posting a test account's API Login ID and Transaction Key to the live environment at https://api.authorize.net/xml/v1/request.api. For test accounts, please post to https://apitest.authorize.net/xml/v1/request.api instead. The API Login ID or Transaction Key have errors. Im sure all my creds are correct, I cheched it 100 times. first of all I create customer payment profile if it does not exists already def create_customer_profile(cls, user: User, merchant_auth): if not user.customer_profile_id: customer_data = { "merchantCustomerId": str(user.id), "email": user.email, } create_customer_profile = apicontractsv1.createCustomerProfileRequest() create_customer_profile.merchantAuthentication = merchant_auth create_customer_profile.profile = apicontractsv1.customerProfileType( **customer_data ) controller = createCustomerProfileController(create_customer_profile) controller.execute() response = controller.getresponse() if response.messages.resultCode == "Ok": user.customer_profile_id = response.customerProfileId user.save() return response.customerProfileId else: raise TransactionCanceled( message=str(response.messages.message[0]["text"].text) ) return user.customer_profile_id after that I try to create customer payment profile with all credit card and billing data @classmethod def create_customer_payment_profile( cls, card_details, billing_address, user: User, default: bool ): merchant_auth = cls.merchant_auth() payment = apicontractsv1.paymentType() credit_card = apicontractsv1.creditCardType() … -
connecting the backend directly to a distant postgresql database is slow (10 insertions/sec )
i tried to host the postgres 16 db in a windows 19 server that is in the same region of the backend server that is also a windows server , it only saves 10 rows per second even when having pool of open sessions with db , but on localhost it saves 100k in less than a sec , I don't believe that two servers in same region will have this slow connection , because when sending via HTTP , I can receive them requests , but connecting backend to db directly is not able to surpass 10 insertions/sec . note that I'm only trying to insert new rows , I'm not trying to execute complex queries . if someone have a solution please help. -
How to execute a Python script which uses a library which produces a visualization in a Angular JS dashboard?
I'm trying to figure out the best way to integrate Python code and render the output onto an Angular dashboard. Here is the library I'd like to execute in Python and then take the rendered output and place it into a Angular JS dashboard: https://robert-haas.github.io/gravis-docs/index.html The library is called Gravis and this rendering can be outputted in several ways such as using gv.vis(), gv.d3(), fig.display(), fig.export_html(), as well as export to svg and others. I'm trying to figure out what is the most optimal way to do this with Angular Javascript or just JS in general. Here is an example Python code that outputs a Gravis visualization: import gravis as gv graph1 = { 'graph':{ 'directed': True, 'metadata': { 'arrow_size': 5, 'background_color': 'black', 'edge_size': 3, 'edge_label_size': 14, 'edge_label_color': 'white', 'node_size': 15, 'node_color': 'white', }, 'nodes': { 1: {'metadata': {'shape': 'rectangle', 'y': 200}}, 2: {}, 3: {}, 4: {'metadata': {'shape': 'rectangle', 'y': 200}}, 5: {'metadata': {'shape': 'hexagon', 'y': 0}}, }, 'edges': [ {'source': 1, 'target': 2, 'metadata': {'color': '#d73027', 'de': 'Das', 'en': 'This'}}, {'source': 2, 'target': 3, 'metadata': {'color': '#f46d43', 'de': 'ist', 'en': 'is'}}, {'source': 3, 'target': 1, 'metadata': {'color': '#fdae61', 'de': 'das', 'en': 'the'}}, {'source': 1, 'target': 4, 'metadata': {'color': … -
Django NoReverseMatch Error: How do I generate urls for each Model
I'm facing a NoReverseMatch error in my Django application when trying to generate URLs for product detail pages. The error message indicates that the URL pattern for 'product-detail' with the provided pk and slug is not found. Here are the details of my setup: NoReverseMatch at /earrings Reverse for 'product-detail' with arguments '('', '')' not found. 1 pattern(s) tried: ['product/(?P[0-9]+)/(?P[-a-zA-Z0-9_]+)/\Z'] Model: class Product(models.Model): name = models.CharField(max_length=400) price = models.IntegerField(default=0) description = RichTextField(null=True, blank=True) slug = models.SlugField(unique=True, null=True, blank=True, max_length=400) create_at = models.DateTimeField(null=True, blank=True) id = models.AutoField(primary_key=True) def get_absolute_url(self): return reverse('product-detail', kwargs={'pk': self.pk, 'slug': self.slug}) def __str__(self): return f'{self.name}' View: class ProductDetailView(DetailView): model = Product template_name = 'tehApp/product_detail.html' context_object_name = 'product' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['Products'] = Product.objects.all() return context def get_object(self): return get_object_or_404(Product, pk=self.kwargs['pk'], slug=self.kwargs['slug']) URL: urlpatterns = [ path('product/<int:pk>/<slug:slug>/', ProductDetailView.as_view(), name='product-detail'), ] Template: {% for product in products %} <div class="item" data-name="{{ product.name }}" data-price="{{ product.price }}" data-date="{{ product.create_at|date:"Y-m-d\TH:i:s" }}"> <div class="relative"> <div class="relative thumbnail"> {% with images=product.images.all %} {% if images|length > 0 %} <a href="{% url 'product-detail' product.pk product.slug %}"> <img width="250px" height="250px" class="" src="{{ images.0.image.url }}" alt=""> </a> {% endif %} {% if images|length > 1 %} <img width="100%" height="100%" class="hidden" src="{{ images.1.image.url }}" … -
Problem sending Persian emails with django's EmailMessage
I'm fairly new to django and was trying to send an email containing Persian letters using django.core.mail.EmailMessage . here is my code: from django.core.mail import EmailMessage from django.conf import settings def custom_sender(subject: str, body: str, recipient_list: list[str], attachments: list[str] = (), content_type_html: bool = False): try: email = EmailMessage( subject, body, settings.DEFAULT_FROM_EMAIL, recipient_list, ) if content_type_html: email.content_subtype = "html" for attachment in attachments: email.attach_file(attachment) email.send() except Exception as e: print(f'\n\nFailed to send email: {e}\n\n') and this is how I tried to use it in my view : custom_sender(subject='ایمیل تستی', body='این یک ایمیل تستی است.', recipient_list=[user.email]) but I encounter this error : 'charmap' codec can't encode character '\u06cc' in position 1: character maps to <undefined> I have noticed that I can't even print Persian stuff out in the console in my django project and I keep encountering this same error (this doesn't happen outside of my django project, and I CAN print Persian letters out in the console). can someone please tell me what this error is about and how I can fix it? I asked some AIs and tried a bunch of solutions like encoding the subject and body using .encode('utf-8') and using django's smart_str , or using python's unicode … -
Issue with Extracting Text from Images Using Django and Tesseract OCR
I am working on a Django project where I need to extract text from images using Tesseract OCR. The images are often blurred and low in contrast, and contain various text blocks such as headings, dates, small letters, bold letters, and sometimes even blurred letters. The image dimensions are approximately 256 x 350 pixels with a resolution of 96 DPI. 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}") # Use the red channel to improve contrast red_channel = image[:, :, 2] # Convert to grayscale (using red channel) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Manually stretch the histogram to improve contrast # Histogram stretching min_val = np.min(gray) max_val = np.max(gray) stretched_gray = ((gray - min_val) / (max_val - min_val) * 255).astype(np.uint8) # If text … -
OK issue #4,54645,546546546, either have your form data submitted to your CRM system, or don' have your form redirected to a success page
You're going to love this one. This one is hilarious.... Have you ever developed a website whereby you can either have your form data submitted to your CRM system, OR you have your website not redirect to a confirmation page upon successful submission of said form. I have. This could only happen to me, couldn't it ? I mean, why would this make my life easy, eh? I mean, that would just way waaaay too much to ask for, wouldn't it? For something just work, just to have your form submit your data with no issues AND redirect to a success page? Oh no because that would just be waaaaay too simple. Why not have it completed in circa 10 minutes when you can waste 6 hours of your life ripping your hair out Here it is! My views.py def raise_support_ticket(request): '''Function to create the ticket. Once created, this will be passed to the "handle_ticket_creation() function" Vendor: freshdesk.com ''' from legal.forms import LegalDocumentsFeedback if request.method == 'POST': form = LegalDocumentsFeedback(request.POST) if form.is_valid(): # Extract data from the form name = form.cleaned_data['name'] subject = form.cleaned_data['subject'] description = form.cleaned_data['description'] email = form.cleaned_data['email'] #Pass this data to the ticket creation handler result = … -
How to set up logging for just my code in Django
I'm having trouble figuring out how to set up a logger for just my app. My app is named calibration. This is what I have in settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'root': { 'handlers': ['console'], 'level': 'INFO' }, 'formatters': { 'verbose': { 'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}', 'style': '{', }, 'simple': { 'format': '{levelname} {asctime} {module} {message}', 'style': '{', }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple' }, 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR, 'cerfServer.log'), 'formatter': 'verbose' } }, 'loggers': { 'django.db.backends': { 'handlers': ['console'], 'level': 'INFO', }, 'django': { 'handlers': ['console', 'file'], 'level': 'INFO', 'propagate': True, }, 'django.request': { 'handlers': ['console', 'file'], 'level': 'DEBUG', 'propagate': True, }, 'calibration': { 'handlers': ['console', 'file'], 'level': 'DEBUG', 'propagate': False } } } I assume that I create a logger with the same name as my app. But this is not working. I am not seeing my Debug messages. If I set the root logger to DEBUG, then I do see the Debug messages, as we as for everything else such as Boto. I want to leave Root set to Info and only see my Debug messages -
"IntegrityError at /payment_getway/ FOREIGN KEY constraint failed in Django"
I'm working on a Django project where users can place orders and I’m encountering an IntegrityError related to a foreign key constraint. Error: IntegrityError at /payment_getway/ FOREIGN KEY constraint failed View code: def payment_getway(request): if request.method == "POST": user = request.user # Retrieve address data from the form # address_id = request.POST.get('address_id') # Make sure you pass this ID in your form # Retrieve the address instance address_instance = get_object_or_404(Address, 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, ) order.save() cart_total_ammount=0 if 'cart_data_obj' in request.session: for p_id, item in request.session['cart_data_obj'].items(): cart_total_ammount += int(item['qty']) * float(item['price']) #getting total ammount for the cart # for p_id, item in request.session['cart_data_obj'].items(): # cart_total_ammount += int(item['qty']) * float(item['price']) cart_order_products = CartOrderItems.objects.create( user=request.user, order=order, invoice_num= str(order.id), # INVOICE_NO-3 item=item['title'], image=item['image'], qty=item['qty'], price=item['price'], total=float(item['qty']) * float(item['price']), # product = Product.objects.get(pid=item['pid']) ) # Redirect or render a success page return redirect('core:order_confirmation') # Update with your success URL # Render payment page with context user = request.user addresses = Address.objects.filter(user=user) return render(request, "core/payment-getway.html", {"addresses": addresses}) Models: class CartOrder(models.Model): user=models.ForeignKey(CustomUser,on_delete=models.CASCADE) sku=ShortUUIDField(length=10,max_length=100,prefix="sku",alphabet="1234567890") oid=ShortUUIDField(length=10,max_length=100,prefix="oid",alphabet="1234567890") full_name=models.CharField(max_length=100,null=True,blank=True) email=models.CharField(max_length=100,null=True,blank=True) mobile=models.CharField(max_length=100,null=True,blank=True) address=models.CharField(max_length=100,null=True,blank=True) … -
Django failes to understand what the term "redirect" is
I could literally scream right now. If its not one issues, it's another. What is so difficult for Python to work out what the function redirect is? Why is it not redirector despite the ace that I have told it to redirect? What part of redirect does Python not understand? Why does it just refresh the page with the form no longer present? If I wanted it to refresh the page on form submission, I would have told it to refresh the page on form submission. However, I have told it to redirect to a success page n form submission, so why is it not redirecting to a success page n form submission. I mean, come on. this is simple basic stuff that a human can understand, why can't Python understand this? MRE #support.views def raise_support_ticket(request): '''**DEMO** This is a demo function, in development. ''' from legal.forms import LegalDocumentsFeedback if request.method == 'POST': form = LegalDocumentsFeedback(request.POST) if form.is_valid(): # Extract data from the form name = form.cleaned_data['name'] subject = form.cleaned_data['subject'] description = form.cleaned_data['description'] email = form.cleaned_data['email'] try: # Call a function to handle form data result = handle_ticket_creation(name, subject, description, email) if result: print("Your ticket has been successfully created and … -
Django jwt cannot customize authentication return message
enter image description here[[enter image description here](https://i.sstatic.net/oTr8Qx1A.png)](https://i.sstatic.net/yrSsiK30.png) Django jwt cannot customize authentication return message `{ "refresh": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTcyMjY3NzE5NCwiaWF0IjoxNzIyNTkwNzk0LCJqdGkiOiI2ZDJmMGMzYzg2MTc0MDhkODExMGZmZmMxZDUxYjIxOCIsInVzZXJfaWQiOjF9.lomSSwRHBLwzdfJgQUy4o-qxn9bb4_bF0ScNsRIDMWw", "access": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNzIyNTkxMDk0LCJpYXQiOjE3MjI1OTA3OTQsImp0aSI6ImYwZmI2MjI5ZGQ1YjRlZDhhMWNmZGY5MGE5ZDRkZWViIiwidXNlcl9pZCI6MX0.Va9l4cPqomfSeI3emtqjlczlho2fzkVvSerQ-_jWR0w" } ` 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema' -
Django form returning Validation errors for fields that have never existed
What is the valid reason behind why it's: failing to redirect to the appropriate error page if result if false telling me that the description field is apparently invalid when it isn't (upon testing the field with string content, telling me that there is a missing field named message and a missing field names subject despite the fact that I have never specified a field named message or subject in the first place This is my MRE #support.views def raise_support_ticket(request): '''**DEMO** This is a demo function, in development. ''' from legal.forms import LegalDocumentsFeedback if request.method == 'POST': form = LegalDocumentsFeedback(request.POST) if form.is_valid(): # Extract data from the form name = form.cleaned_data['name'] description = form.cleaned_data['description'] email = form.cleaned_data['email'] try: # Call a function to handle form data result = handle_ticket_creation(name, description, email) if result: return redirect('success') else: print("Invalid form submission") #Verification that its; thinking its an invalid firm submission print(form.errors) form.add_error(None, 'Failed to create ticket. Please try again.') return redirect('error.html') #Failing to redirect except Exception as ex: messages.error(f"Error in form validation. Error: {ex}") print(f"Exception Error: {ex}") return render(request, 'error.html') else: form = LegalDocumentsFeedback() return form def handle_ticket_creation(name, description, email): """ Function to handle ticket creation. This function could send data to … -
How to make a API in django which will take user as input and return longitude and latitude of the user?
I need to develop an API endpoint that, given a user model, returns the current longitude and latitude of the user. This API is intended for use in a project where you want to display the user's location on a map. The endpoint should take a user ID or similar identifier as input and respond with the geographical coordinates of the user. The location data should be fetched from a backend system where it is regularly updated. The API should be designed with proper security measures to ensure only authorized access to user location data. -
Django URL reset after authentication fail
if user is not None: login(request, user) return redirect('home') else: error_message = "Invalid username or password." return render(request, 'login.html', {'error_message': error_message}) Using the above code, if user enters wrong credentials, login.html shows up successfully with error message. But now the URL is http://localhost:8000/authentication_view/. Now if the user re-enters credentials, the URL will be http://localhost:8000/authentication_view/authentication_view/, and it creates Page Not Found error. If I use return redirect('login_view'), then the error message will not show. Could someone help me how to show login page with error message without adding Authentication View to the URL? I was expecting: if user provides wrong credentials, he gets error message and goes back to login page. Now he can re-enter credentials. But now login page is not usable because authentication view name is already added to the URL. New login attempt will add authentication view name twice the URL. -
Pytest doesn't found my settings directory
I tried to start pytest but the settings file cannot be found by pytest I'm in virtualenv with Python 3.11.9 and pytest 8.3.2 ImportError: No module named 'drf.settings' pytest-django could not find a Django project (no manage.py file could be found). You must explicitly add your Django project to the Python path to have it picked up. here the structure of my project ├── README.md ├── drf │ ├── drf │ │ ├── __init__.py │ │ ├── production_settings.py │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── manage.py │ └── tests │ ├── __pycache__ │ │ └── test_auth.cpython-311-pytest-8.3.2.pyc │ ├── factory_boy │ │ ├── __pycache__ │ │ │ └── factory_models.cpython-311.pyc │ │ └── factory_models.py │ └── test_auth.py ├── drf-uwsgi.ini ├── pytest.ini ├── requirements.in ├── requirements.txt and here the content of pytest.ini [pytest] DJANGO_SETTINGS_MODULE = drf.settings.py python_files = test_*.py What I have tried so far: I tried to add init.py to tests directory (seems not be recommended and didn't worked) deactivate and reactivate the virtualenv change drf.settings.py for drf.drf.settings but nothing run pytest as module with python -m pytest tests edit: if I cd drf and tried I get a little different error ImportError: No module … -
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 …