Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'Expected a value of type List<dynamic> but got one type _JsonMap'
The code below is displays my List<dynamic> casting method, yet when I preview my code, the info displayed is that 'Expected a value of type List<dynamic> but got one type _JsonMap'. My data is being retrieved from a django rest framework into a json format. I run server whenever I start the flutter app. // ignore_for_file: dead_code, prefer_const_constructors, prefer_const_literals_to_create_immutables, deprecated_member_use, avoid_print, non_constant_identifier_names import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'dart:async'; Future<List<Data>> fetchData() async { var url = Uri.parse('http://127.0.0.1:8000/api/?format=json'); final response = await http.get(url); if (response.statusCode == 200) { // final jSon = "[${response.body}]"; List jsonResponse = (json.decode(response.body) as List<dynamic>); return jsonResponse.map((data) => Data.fromJson(data)).toList(); } else { throw Exception('Unexpected error occured!'); } } class Data { final int ID; final String visitor_name; final String visit_date; final String time_in; final String time_out; final String department; final String visitee_name; final String address; final String phone; final String purpose_of_visit; Data({required this.ID, required this.visitor_name, required this.visit_date, required this.time_in, required this.time_out, required this.department, required this.visitee_name, required this.address, required this.phone, required this.purpose_of_visit}); factory Data.fromJson(Map<String, dynamic> json) { return Data( ID: json['ID'], visitor_name: json['visitor_name'], visit_date: json['visit_date'], time_in: json['time_in'], time_out: json['time_out'], department: json['department'], visitee_name: json['visitee_name'], address: json['address'], phone: json['phone'], purpose_of_visit: json['purpose_of_visit'], ); } } class ViewRecord extends … -
Django: update one table based on another
I have two tables Table1 and Table2 with the same field hash_str. from django.db import models class Table1: data = JSONField(...) hash_str = CharField(...) class Table2: name = CharField(...) parsed = DateTimeField(...) hash_str = CharField(...) is_updated = BooleanField(...) # ... Sometimes i need to update Table2 instances based on Table1 instances with the same hash. But i want to use Table2.objects.bulk_update(...) for it. Because there is too much instances to update them one by one like this: # ... for t2_obj in Table2.objects.filter(is_updated=False): t1_obj = Table1.objects.get(hash_str=t2_obj.hash_str) t2_obj.name = t1_obj.data["name"] t2_obj.parsed = t1_obj.data["parsed"] t2_obj.is_updated = True t2_obj.save() # ... How can i do it properly? -
How to get realtime stdout from a celery task?
I have a Django project in which i'm running some background tasks with celery, one of my goal is to show real-time stdout of the running task so that the user can see the progress. the issue is that i get the stdout of the process only when it is finished executing (all is dumped at once). Views.py def run_script(request, file_type, file_id): run_features.delay(arguments) return Tasks.py @shared_task def run_features(arguments): process = subprocess.Popen(arguments, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) channel_layer = get_channel_layer() while True: output = process.stdout.readline() if output == '' and process.poll() is not None: break if output: print(output) async_to_sync(channel_layer.group_send)( 'output_group', { 'type': 'send_output', 'output': output.strip() } ) process.wait() return process.returncode Celery INFO -------------- celery@ritik v5.3.1 (emerald-rush) --- ***** ----- -- ******* ---- Linux-6.5.0-25-generic-x86_64-with-glibc2.35 2024-03-21 09:30:54 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: Automation:0x7e2bb4073280 - ** ---------- .> transport: redis://localhost:6379/0 - ** ---------- .> results: disabled:// - *** --- * --- .> concurrency: 8 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery Expectation - I get the stdout, line by line, while the task is running. Actual result - I … -
Invalid block tag on line 2: 'endblock'. Did you forget to register or load this tag?
{% extends "base.html" %} {% block title %} Home {% endblock %} {% block content %} {% endblock %} Seems correct to me, but it's showing this error. -
Update only specific fields in a models.Model vDjango
I have model in models.py: class SuperviserModel(models.Model): name = models.TextField(db_collation='C') family = models.TextField(db_collation='C') score = models.FloatField(db_column='score ', blank=True, null=True) # def __str__(self)-> str: return f' - {self.family} - {self.name}' class Meta: managed = False db_table = 'personnel' And in admin.py: @admin.register(SuperviserModel) class MySuperviserModelAdmin(admin.ModelAdmin): list_display = ['name','family','score'] sortable_by = ['name','family'] search_fields=['name', 'family'] I want when superviser user edit personnel just update score field, And cant update name and family field. How can I do? -
Image is not displayed/loaded in my django website which i deployed on Cpanel
details of my code, in my settings.py i have: BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') and this is how i tried to acces form the template: in very first page: % load static % to display image, <a class="navbar-brand" href="#"><img src="{% static 'images/main.png' %}" alt="imagetwo" width="100" height="50"></a> anyone who can help me please -
Having trouble configuring ssl for django apache2
I have two errors: 'AH00112: Warning: DocumentRoot [/etc/apache2/var/www/html] does not exist' while i runed this cmd: >>>> grep -r "DocumentRoot" /etc/apache2/ >>> /etc/apache2/sites-available/000-default.conf: DocumentRoot > var/www/html > >>> /etc/apache2/sites-available/amicom_com_vn.conf: DocumentRoot > /var/www/html > >>> /etc/apache2/sites-available/default-ssl.conf: DocumentRoot > /var/www/html when i run 'https://example.com' i see 'Apache2 Default Page' how can i fix this error, this is my config ssl <VirtualHost *:443> ServerAdmin webmaster@localhost ServerName example.com ServerAlias www.example.com DocumentRoot /var/www/html SSLEngine on SSLCertificateFile /etc/ssl/certs/ca-certificates.crt SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key </VirtualHost> -
python exclude non accessible image with requests
i've written a really simple function with requests, wich with a giver url checks if it gets a response and if this response is an image. It actually works, but is crazy slow at times. i'm too inexperienced to understand why is that. How can i improve it or achieve the same thing in a better and faster way? def is_image_url(url): try: response = requests.get(url) status = response.status_code print(status) if response.status_code == 200: content_type = response.headers.get('content-type') print(content_type) if content_type.startswith('image'): return True return False except Exception as e: print(e) return False i'm using that function to exclude images who are not acessible, like images from instagram, facebook etc. i thoughtit could work fine because i actually need to check only 10 images that i get from google custom search api. for now i've excluded the function from the application, and tried do a similar thing with checking the image height or width to assure that it existed and was accessible without much success. -
Python Django dj-rest-auth AttributeError
I was trying the demo project ( https://dj-rest-auth.readthedocs.io/en/latest/demo.html ) and when I tried to login I got the error: Django 4.2.5 django-allauth 0.61.1 dj-rest-auth 5.0.2 PyJWT 2.8.0 Internal Server Error: /api/v1/social/google/login/finish/ Traceback (most recent call last): File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 56, in wrapper_view return view_func(*args, **kwargs) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/django/views/generic/base.py", line 104, in view return self.dispatch(request, *args, **kwargs) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/django/utils/decorators.py", line 46, in _wrapper return bound_method(*args, **kwargs) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/django/views/decorators/debug.py", line 92, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/dj_rest_auth/views.py", line 48, in dispatch return super().dispatch(*args, **kwargs) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/dj_rest_auth/views.py", line 125, in post self.serializer.is_valid(raise_exception=True) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/rest_framework/serializers.py", line 227, in is_valid self._validated_data = self.run_validation(self.initial_data) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/rest_framework/serializers.py", line 429, in run_validation value = self.validate(value) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/dj_rest_auth/registration/serializers.py", line 160, in validate login = self.get_social_login(adapter, app, social_token, token) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/dj_rest_auth/registration/serializers.py", line 62, in get_social_login social_login = adapter.complete_login(request, app, token, response=response) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/allauth/socialaccount/providers/google/views.py", line 82, in complete_login id_token = response.get("id_token") AttributeError: 'str' object has … -
I am running elastic search on 0.5-1 vCPU (1 shared core) GCP but the server is not able to handle how to fix this?
I am running Elasticsearch on 0.5-1 vCPU (1 shared core) with 1.7 GB of memory (GCP). When I start the elastic search service the server is crashed. How do we fix this issue? I am running Django with Postgres and Elasticsearch. -
Django NameError: name 'include' is not defined in urls.py
I'm encountering a NameError in my Django project's urls.py file. When I try to use the include () function to include URLs from another app, I get the following error: NameError: name 'include' is not defined Here's the relevant portion of my urls.py file: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('hello/', include('hello.urls')) ] I've already imported include from django.urls, so I'm not sure why this error is occurring. Any insights on what might be causing this issue and how to resolve it would be greatly appreciated. Thank you! I attempted to include URLs from another Django app in my project's urls.py file using the include() function. I expected the include() function to work as intended and include the URLs from the specified app. However, when I tried to use the include() function, I encountered a NameError stating that 'include' is not defined, even though I had imported it from django.urls. -
WebSocket connection to 'ws://127.0.0.1:8000/ws/work/' failed:
I can't access the WebSocket while I follow this project : https://www.youtube.com/watch?v=SF1k_Twr9cg&t=2498s&ab_channel=CodeWithStein From 47:23 consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer from asgiref.sync import sync_to_async class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept async def disconnect(self): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) routing.py from django.urls import path from . import consumers websocket_urlpatterns = [ path('ws/<str:room_name>/', consumers.ChatConsumer.as_asgi()), ] asgi.py import os from django.core.asgi import get_asgi_application from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import room.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangochat.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( room.routing.websocket_urlpatterns ) ) }) room.html {% block scripts %} {{ room.slug|json_script:"json-roomname" }} <script> const roomName = JSON.parse(document.getElementById("json-roomname").textContent); const chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/' + roomName + '/' ); chatSocket.onmessage = function (e) { console.log("onmessage"); } chatSocket.onclose = function (e) { console.log("onclose"); } </script> {% endblock %} -
type object ...... has no attribute 'replace'
I'm using Django 4.2 application this is my model: from django.db import models from django.utils.translation import gettext_lazy as _ class Category(models.Model): parent = models.ForeignKey('self', verbose_name=_('parent'), blank=True, null = True, on_delete=models.CASCADE) title = models.CharField(_('title'), max_length = 50) description = models.TextField(_('description'), blank=True) avatar = models.ImageField(_('avatar'), upload_to='categories/') enable = models.BooleanField(_('enable'), default = True) created_time = models.DateTimeField(_('created time'), auto_now_add = True) updated_time = models.DateTimeField(_('updated time'), auto_now=True) class Meta: db_table = 'categories' verbose_name = _('Category') verbose_name_plural = _('categories') when I run the server I get this error: type object 'Category' has no attribute 'replace' I think that it's because of the translation cause when I checked where 'replace' was I found this: def gettext(message): """ Translate the 'message' string. It uses the current thread to find the translation object to use. If no current translation is activated, the message will be run through the default translation object. """ global _default eol_message = message.replace("\r\n", "\n").replace("\r", "\n") if eol_message: _default = _default or translation(settings.LANGUAGE_CODE) translation_object = getattr(_active, "value", _default) result = translation_object.gettext(eol_message) else: # Return an empty value of the corresponding type if an empty message # is given, instead of metadata, which is the default gettext behavior. result = type(message)("") if isinstance(message, SafeData): return mark_safe(result) return … -
Django models field not getting generated in database
I am creating a basic Django project. I am using the default db sqlite3. I have created an app product inside my main folder. So, my folder structure is like this: -project -djangoproject -products -models.py -manage.py I am adding my new product model in models.py but when I am running python3 manage.py makemigrations I am checking my migration file. The model is getting created and there is an id field also in it but no other field of my product is coming in my migrations file. I also ran the command python3 manage.py migrations and checked my database. Only id field is present in the product table. I am not able to understand the cause of this problem. Here is the look at my migration file and models.py file: from django.db import models class Product(models.Model): name: models.CharField(max_length=200) price: models.FloatField() stock: models.IntegerField() image_url: models.CharField(max_length=2083) # Generated by Django 5.0.3 on 2024-03-21 04:46 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ('products', '0004_delete_offer_delete_product'), ] operations = [ migrations.CreateModel( name='Product', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], ), ] Django version: 5 If anyone knows the reason then please comment or post your answer. It will be really … -
Configuring Alembic in Django Rest Framework with SQLAlchemy
I have a DRF project where I am using SQLAlchemy along with Django's built-in ORM. For configuring Alembic into my project I did this. Installed Alembic with pip install alembic Then I've run this command on my root project directory. alembic init alembic This command generated a folder called alembic and a file named alembic.ini in my root project directory. Inside that folder there are some files like (env.py, README, script.py.mako) and a folder named versions. Now, inside the alembic.ini file, I've added this line, sqlalchemy.url = sqlite3://db.sqlite3 This is how I configured. This is my models.py: from sqlalchemy import create_engine, Column, String, Integer, Float, ForeignKey from sqlalchemy.orm import declarative_base, sessionmaker, relationship from django.contrib.auth import models engine = create_engine('sqlite:///db.sqlite3') Base = declarative_base() class PlaceInfoModel(Base): __tablename__ = 'place_info' id = Column(Integer, primary_key=True, autoincrement=True) owner_id = Column(Integer,nullable=False) name = Column(String(60)) address = Column(String(300)) rating = Column(Float) type = Column(String(20)) image = Column(String) Base.metadata.create_all(engine) In my alembic/env.py I added these lines: from review.models import Base, PlaceInfoModel target_metadata = Base.metadata But, whenever I run this alembic revision --autogenerate -m "Created SQLAlchemy Model" I am getting this error. File "D:\SQLAlchemy Practice\env\Lib\site-packages\django\conf\__init__.py", line 69, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not … -
Stripe doesn't work after deploying on Heroku by Django
*English is not my mother language,so if my English is not correct,please ignore. At Local, Stripe has worked well on Django. But after deploying Heroku, Stripe(subscription Service) doesn't work. When I click "Pay",everytime showed " Internet Error 500".I checked Heroku logs,but connect and service looks like okay. I've tried deployed again and again, but everytime the results are same. Showing "Internet Error 500". This is logs by Heroku logs --tail 2024-03-19T08:03:27.576123+00:00 heroku[router]: at=info method=POST path="/checkout/" host=nagoyameshi-marina-32890ff7fdd2.herokuapp.com request_id=40d9d9e5-8ebf-436f-9254-2e862dcada7e fwd="126.15.11.7" dyno=web.1 connect=2ms service=19ms status=500 bytes=459 protocol=https 2024-03-19T08:03:27.576163+00:00 app[web.1]: 10.1.20.255 - - [19/Mar/2024:17:03:27 +0900] "POST /checkout/ HTTP/1.1" 500 145 "https://nagoyameshi-marina-32890ff7fdd2.herokuapp.com/terms_of_service/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36" These are my settings.py and CheckoutView from views.py I deployed on Heroku. if "STRIPE_PUBLISHABLE_KEY" in os.environ and "STRIPE_API_KEY" in os.environ and "STRIPE_PRICE_ID" in os.environ: STRIPE_PUBLISHABLE_KEY = os.environ["STRIPE_PUBLISHABLE_KEY"] STRIPE_API_KEY = os.environ["STRIPE_API_KEY"] STRIPE_PRICE_ID = os.environ["STRIPE_PRICE_ID"] - CheckoutView stripe.api_key = settings.STRIPE_API_KEY class CheckoutView(LoginRequiredMixin,View): def post(self, request, *args, **kwargs): checkout_session =stripe.checkout.Session.create( line_items=[ { 'price':settings.STRIPE_PRICE_ID, 'quantity':1, }, ], payment_method_types=['card'], mode='subscription', success_url=request.build_absolute_uri(reverse_lazy("nagoyameshi:success")) + '?session_id={CHECKOUT_SESSION_ID}', cancel_url=request.build_absolute_uri(reverse_lazy("nagoyameshi:index")), ) print( checkout_session["id"] ) return redirect(checkout_session.url) checkout = CheckoutView.as_view() DB is " Heroku Postgres". -
Django and Keystrokes dynamics as authentication
How do i capture and use keystrokes dynamics as my second factor authentication in Django web application project? I have implemented the normal username and password authentication in Django and fails to know how i can use keystrokes to add it for authentication. -
Django ConnectionRefusedError [Errno 111] Connection refused facing issue how to solve it
I'm facing issue when send mail on django [Errno 111] Connection refused my setting.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' # Replace with your preferred backend EMAIL_HOSTS = 'smtp.gmail.com' # Replace with your email host EMAIL_PORT = 587 # Replace with your email port EMAIL_USE_TLS = config('EMAIL_USE_TLS', cast=bool) # Set to False if your email server doesn't use TLS EMAIL_HOST_USER = config('EMAIL_HOST_USER') # Replace with your email username EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD') # Replace with your email password view.py current_url = get_current_site(request) mail_subject = "Please activate your account." message = render_to_string('base/pass/account_verify.html',{ 'user':user, 'domain':current_url, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token':default_token_generator.make_token(user), }) to_email = email send_mail = EmailMessage(mail_subject, message, to=[to_email]) send_mail.send() i have check all mail setting.py but can't solve this error on local it's work but when i am production and host while it's not working and get this error -
Total counts not displaying in template:
the app im building requires asset management section which would display the total assets, total fixed, total onsite and total booked, however the blocks shows but the amounts does not. while debugging the print statement within the views prints to console and if i attempt to load the asset management html it displays but when including it into my base html the amounts does not display. My views: def asset_dashboard(request): total_assets_count = Asset.objects.count() onsite_assets_count = Asset.objects.filter(status='onsite').count() fixed_assets_count = Asset.objects.filter(status='fixed').count() booked_assets_count = Asset.objects.filter(status='booked').count() print("Total Assets Count:", total_assets_count) print("Onsite Assets Count:", onsite_assets_count) print("Fixed Assets Count:", fixed_assets_count) print("Booked Assets Count:", booked_assets_count) context = { 'total_assets_count': total_assets_count, 'onsite_assets_count': onsite_assets_count, 'fixed_assets_count': fixed_assets_count, 'booked_assets_count': booked_assets_count, } return render(request, 'asset_dashboard.html', context) My base.HTML: <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>{% block title %}{% endblock %}</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous"> {% load static %} <link rel="stylesheet" href="{% static './css/main.css' %}"> <style> /* CSS to style the container */ .container { height: 200px; background-image: url('static/images/VOClogo.jpg'); background-size: contain; background-repeat: no-repeat; background-position: center; opacity: 0.2; color: white; font-size: 24px; text-align: center; padding-top: 10px; } </style> </head> <body> {% include 'navbar.html' %} <form class="d-flex" method="GET" action="{% url 'asset_search' %}"> <input class="form-control … -
Can I build a dynamic Web3 site using IPFS?
This is more of a general question. I would like to connect a dynamic site to a Web3 domain (.x) I have read that only static builds are possible using the IPFS protocol and Web3 platforms (such as Pinata, Fleek etc.). Just digging into Web3 development further. Appreciate any clarity, thoughts or pointers. And when I say dynamic, I mean full backend and frontend stack capabilities using frameworks such as Django. -
Redirect URI error with Google social login in dj-rest-auth
I try to add a google login button to my website, that runs django as the server. For social authentication I want use dj-rest-auth and tried to go according to it's guides to authenticate with google auth-code flow. On the client side I use the @react-oauth/google package. The setup on my django server is this: views.py class GoogleLogin(SocialLoginView): adapter_class = GoogleOAuth2Adapter callback_url = "http://127.0.0.1:8000/accounts/google/login/callback/" client_class = OAuth2Client urls.py path("auth/google/", GoogleLogin.as_view(), name="google_login"), The google credentials screen settings: Whenever I try to login with google I get an 400 error from the dj-rest-auth view, and when I debugged the code I looked at the response from google(https://oauth2.googleapis.com/token): I get the following error in the response text(also 400) { "error": "redirect_uri_mismatch", "error_description": "Bad Request" } It looks like my server send the correct redirect uri in the payload Any help or tips with this issue and social auth in general would be very appreciated, thank you. -
How to solve the image not displayed on Production using Django on Heroku
So the images are displayed on test or debug side but when I deployed into production it does not show the image , in fact it shows something else, like in the imagethe image is not fully displayed.I am using pillows and Whitenoise for the images . How can I solve this issue? I tried to make some changes on the script and settings.py -
DjangoJobStore Randomly Deletes Jobs
I have apscheduler running with a DjangoJobStore from a management command in django, but every so often some (not all) of the jobs will be deleted from the database. The scheduler still runs, still gets other jobs, but doesnt find the specific one in the code below. When i check the admin, its deleted. Restarting the command fixes it as it adds the job back for a random amount of time before deleting again. I added a listener for EVENT_JOB_REMOVED and it is never fired, and i added breakpoints in all the delete methods for DjangoJob and none of them ever hit. the function must_reply simply checks an email inbox and sends a reply back over smtp, nothing in there accesses the DjangoJob table, nor does anything in the rest of the code. must_reply is decorated with @close_old_connections removing DjangoJobStore as a job store fixes the problem, but obviously I would like to use it haha Has anyone experienced this? And what are some solutions or ideas to try for fixing this. It is truly strange. class Command(BaseCommand): help = "Runs APScheduler." def handle(self, *args, **options): executors = { 'default': ThreadPoolExecutor(max_workers=10) } job_defaults = { 'coalesce': True, 'misfire_grace_time': 10 } … -
Dockerized Django + Nginx startup & mounting issue
I want to create a enviroment for my personal project hovewer I'm strugling and can't resolve the issue. I had it working, made some reorganization in the project structure to structure it like i want (or think is best) and broke it trying to fix it :/ And to be honest i had simmilar issue in the past, I strugled with it ... i guess I did not learn anything and forgot how i fixed it (wasnt dockerized). The project is just basic default configuration to have it running as i want, so I have the comfort of the CI/CD jenkins deployement and can run and play across docker containers. I will share the relevant parts as well as the project structure. Project file structure: RaC/ ├── django/ │ ├── Dockerfile │ ├── .env │ ├── manage.py │ ├── files/ │ │ ├── media/ │ │ └── static/ │ └── rac_backend/ │ ├── __init__.py │ ├── asgi.py │ ├── requirements.txt │ ├── settings.py │ ├── urls.py │ ├── wsgi.py ├── jenkins/ ├── nginx/ ├── postgres/ ├── redis/ ├── templates/ ├── venv/ ├── manage.py └── docker-compose.yml docker-compose.yml version: '3.8' services: jenkins: build: context: ./jenkins ports: - "8080:8080" - "50000:50000" volumes: - … -
Issues with sending emails through Outlook using the Win32 library in Django
I'm using Win32 for sending emails on my website. In general, the emails are sent and reach the recipient, but the problem is that the recipient does not change. Initially, when I started this project, I used a single test email to use in different scenarios. This email was "email1@outlook.com". Later, I added another email for another user named User 2 with their own email "email2@outlook.com". The problem is that the recipient does not change. I specifically select that my recipient is "email2@outlook.com", but I always receive all emails at "email1@outlook.com". outlook = win32.Dispatch('Outlook.Application') mail = outlook.CreateItem(0) mail.SentOnBehalfOfName = 'xxxxxxxx@outlook.com' mail.To = email mail.Subject = 'NUEVA SOLICITUD DE PRUEBAS DE LABORATORIO' mail.BodyFormat = 2 html_body = f""" <html> <body style="font-family: 'Arial', sans-serif; background-color: #f4f4f4; margin: 0; padding: 0;"> <div style="max-width: 600px; margin: 20px auto; background-color: #ffffff; padding: 20px; border-radius: 5px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);"> <h1 style="color: #333; margin-bottom: 10px;">Nueva solicitud de pruebas de laboratorio de {full_name}</h1> <p style="color: #555; margin-bottom: 20px;">El usuario {full_name} ha creado una nueva solicitud de pruebas de laboratorio para el cliente {customer} con una fecha requerida para el {require_date}. A continuación, se detallan más información y enlaces:</p> <ul style="list-style-type: none; padding: 0;"> …