Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Modal button click function not defined - Uncaught ReferenceError
Question Description: I have a modal that should open when clicking on a "Share!" button on my webpage. However, I'm encountering an "Uncaught ReferenceError: openShareModal is not defined" error. Below are the relevant parts of my code: Modal Code: {% load static %} <div id="shareModal" class="modal"> <!-- Modal content --> <div class="modal-content" id="{{ modal_id }}"> <span class="close">&times;</span> <p class="centered-text form-labels">Broadcast the {{ modal_card_title }} Card</p> <div class="social-media-button-container"> <!-- Social media buttons --> </div> <input type="text" value="https://www.example.com/system_page" id="shareLink" style="display: none;"> </div> </div> <script defer> var modal = document.getElementById("shareModal"); var span = document.getElementsByClassName("close")[0]; function openShareModal(event) { event.stopPropagation(); modal.style.display = "block"; } span.onclick = function() { modal.style.display = "none"; } window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } } function shareOnFacebook(shareUrl) { // Share on Facebook code } function shareOnX(shareUrl) { // Share on X code } function shareOnInstagram(shareUrl) { // Share on Instagram code } function shareOnLinkedIn(shareUrl) { // Share on LinkedIn code } </script> Individual Page Code: {% extends 'home1/base.html' %} {% load static %} {% block body %} <body id="background_image_mohadino"> <!-- Page content --> <div class="container-fluid text-center"> <!-- Content details --> <div class="container-fluid text-center"> <!-- Share button --> <button class="mohadino_button btn btn-custom btn-lg w-75" type="button" … -
In Django, Update a different table at the time of saving a record from one table
My tables are: models.py class Warehouse(models.Model): site_name = models.CharField(max_length=100) class Item(models.Model): item = models.CharField(max_length=100) class WarehouseStockStatus(models.Model): site_name = models.ForeignKey(Warehouse, on_delete=models.CASCADE) item = models.ForeignKey(Item,on_delete=models.CASCADE,editable = False) class Meta: unique_together = (("site_name", "item")) stock_opening_quantity = models.PositiveBigIntegerField( default = 0, editable = False ) stock_consumption_quantity = models.PositiveBigIntegerField( default = 0, editable = False ) current_inventory_level = models.PositiveBigIntegerField( default = 0, editable = False ) class InventoryOpenings(models.Model): site_name = models.ForeignKey(Warehouse, on_delete=models.CASCADE,related_name='openings') transaction_number = models.BigAutoField(primary_key = True, serialize = False) class InventoryOpeningsDetails(models.Model): transaction_number = models.ForeignKey(InventoryOpenings, on_delete=models.CASCADE) item = models.ForeignKey(Item,on_delete=models.CASCADE) opening_quantity = models.PositiveBigIntegerField( default = 0, editable = True ) There is one Warehouse table, with one to many records in WarehouseStockStatus. There is one products or Items table for inventory control. Then there InventoryOpenings and InventoryOpeningsDetails table, where we select the warehouse, and then an item, add the opening_quantity field. I want to update WarehouseStockStatus for this warehouse and item combination, updating the stock_opening_quantity and current_inventory_level fields in that table, with the opening value we are inputting for InventoryOpeningsDetails. I am trying to place the code for it in admin.py, in InventoryOpeningsAdmin. Need help. Tried this code in admin class InventoryOpeningsAdmin(admin.ModelAdmin): def after_saving_model_and_related_inlines(self, obj): mysite = InventoryOpenings.objects.values_list('site_name',flat=True)[0] myitem = InventoryOpeningsDetails.objects.values_list('item', flat=True)[0] try: warehouse_item = WarehouseStockStatus.objects.filter(Q(site_name=mysite, … -
Invalid HTTP_HOST on Django (EC2 Aws Ubuntu)
I'm having trouble deploying my Django application. I'm running it using nohup on port 8000 and using nginx with SSL certificate configuration, masking the domain to port 80. Here are my default Nginx settings: server { listen 80; listen 443 ssl; server_name fmartns.dev; ssl_certificate /etc/letsencrypt/live/fmartns.dev/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/fmartns.dev/privkey.pem; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/fmartns.dev; } location / { include proxy_params; proxy_pass http://3.82.145.23:8000; # Port where Django is running proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } Django's settings.py configuration: # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['fmartns.dev', '*'] SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_BROWSER_XSS_FILTER = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_SSL_REDIRECT = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') CSRF_TRUSTED_ORIGINS = ['http://fmartns.dev'] Error log: DisallowedHost at / Invalid HTTP_HOST header: 'fmartns.dev,fmartns.dev'. The domain name provided is not valid according to RFC 1034/1035. Any ideas on how I can resolve this? I've tried various tutorials and configurations both in my settings.py and in the default nginx settings. -
Running a Celery server and Django server individually on the same AWS EC2 instance?
I can successfully run a django server on my EC2 instance with Ubuntu on AWS, as well as the celery server. However, unlike in my Visual Studio Code editor where I can create multiple terminals and have each one run a different server without any issue, I can't seem to do it for my EC2 instance in AWS. I tried making different tabs connecting the same instance, and while one managed to connect to the Django server, when trying to make the other one connect to the Celery server, it all just freezes. This is the Django server running. This is the Celery server running on the same instance but i had to close the Django server just for it to be able to run. Basically, I ust want to run both at the same time on the same EC2 instance, if it's possible. I have read somewhere that using this code ssh -i your_key.pem ubuntu@your_ec2_public_ip could help but i'd have to launch another instance with a paired key. I wanted to make sure if this actually helps or if there another way to do it. -
django djfernet "TypeError: string argument without an encoding" [closed]
I am experiencing the error only in a few environments with the same version of the libraries, as follows: djfernet 0.8.1 django 4.2.11 Python 3.9.18 I'm reading data from a form in Django and I'm getting in the console: File ".../django/db/models/sql/compiler.py", line 1500, in apply_converters value = converter(value, expression, connection) File ".../fernet_fields/fields.py", line 79, in from_db_value value = bytes(value) TypeError: string argument without an encoding It seems to crash when trying to decrypt the data from the database. -
Custom primary keys break Django admin inlines logic
I have a model with self relation in models.py: from uuid import uuid4 from django.db import models class Example(models.Model): uid = models.UUIDField(primary_key=True, default=uuid4) title = models.CharField(max_length=128) parent = models.ForeignKey("self", related_name="subexamples", blank=True, null=True) and Django admin models: from .models import Example from django.contrib import admin class ExampleInline(admin.TabularInline): model = Example exclude = ("uid",) extra = 1 verbose_name = "Subexample" show_change_link = True class ExampleAdmin(admin.ModelAdmin): search_fields = ("title", ) exclude = ("uid",) inlines = [ExampleInline,] admin.site.register(Example, ExampleAdmin) On the admin site I can see the main model and inline like in any other cases. The problem start after adding first Inline object. After it's added I can no longer delete or change it. The only mistake I see is "Please correct the error below." without any problems below. Also no any problems in Django logs. I'm using Django==5.0.2 After reading about similar problems I found that customized PK breaks logic but actually didn't find any workarounds for this problem. -
Django/Heroku - Custom 500 template
I have a template defined and loaded on S3. The template has been granted public access. The template is referred in Heroku as variable ERROR_PAGE_URL and the S3 link is attached against this variable. Somehow the template is not displaying and I still get the basic 500 error generated: 500 Internal Server Error Exception inside application. Daphne I have (I think) applied the same approach as the custom maintenance template, which is rendered perfectly fine. Am I reading the documentation wrong? (https://devcenter.heroku.com/articles/error-pages) Am I using the correct variable? Or is it actually not somehting Heroku generates and I should code this in django? -
Exception Value: User matching query does not exist
DoesNotExist at /profile/username User matching query does not exist. Request Method: GET Request URL: http://127.0.0.1:8000/profile/username Django Version: 5.0.4 Exception Type: DoesNotExist Exception Value: User matching query does not exist. Exception Location: D:\Django projects\social media app\social_media_app_env\Lib\site-packages\django\db\models\query.py, line 649, in get Raised during: core.views.profile Python Executable: D:\Django projects\social media app\social_media_app_env\Scripts\python.exe Python Version: 3.11.9 Python Path: ['D:\Django projects\social media app\social_media', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2544.0_x64__qbz5n2kfra8p0\python311.zip', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2544.0_x64__qbz5n2kfra8p0\DLLs', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2544.0_x64__qbz5n2kfra8p0\Lib', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2544.0_x64__qbz5n2kfra8p0', 'D:\Django projects\social media app\social_media_app_env', 'D:\Django projects\social media ' 'app\social_media_app_env\Lib\site-packages'] Server time: Fri, 19 Apr 2024 10:53:11 +0000 -
Django populating a form on a modal
I have a problem with populating a form on a modal pop up. I can get a form added to the modal, but I want it to be based on the line a user clicks on. My view: class SalesQuotationDetailView(LoginRequiredMixin, View): template_name = 'Sales/quotation_details.html' def get(self, request, quoteid): quotation = Quotation.objects.get(id=quoteid) quotationlines = QuotationLine.objects.filter(quotation=quotation, deleted=False) company = quotation.customer quotationform = QuotationForm(initial=model_to_dict(quotation), companyid=company.id) newquotationlineform = NewQuotationLineForm() context = { 'quotation':quotation, 'quotationform':quotationform, 'quotationlines':quotationlines, 'new_quotation_line':newquotationlineform, 'table_title':"Quotation Lines", 'table_heading_1':"Article", 'table_heading_2':"Amount", 'table_heading_3':"Price per Piece", 'table_heading_4':"Lead Time", 'table_heading_5':"Line total" } return render(request, self.template_name, context) def post(self, request, quoteid): quotation = Quotation.objects.get(id=quoteid) quotationlines = QuotationLine.objects.filter(quotation=quotation, deleted=False) company = quotation.customer quotationform = QuotationForm(data=request.POST, files=request.FILES, instance=quotation, companyid=company.id) if quotationform.has_changed and quotationform.is_valid(): qform = quotationform.save(commit=False) qform.updated_by = request.user qform.updated_date = timezone.now() quotationform.save() messages.success(request, f'{quotation.number} has been saved correctly') return redirect('sales-quote-details', quoteid=quotation.id) else: messages.warning(request, f'{quotationform.errors}') newquotationlineform = NewQuotationLineForm(data=request.POST) if newquotationlineform.has_changed and newquotationlineform.is_valid(): newquotationline = newquotationlineform.save(commit=False) newquotationline.quotation = quotation newquotationline.total_line_price = newquotationline.amount * newquotationline.price newquotationline = newquotationlineform.save() messages.success(request, f'The new quotation line was added succesfully') return redirect('sales-quote-details', quoteid=quotation.id) context = { 'quotation':quotation, 'quotationform':quotationform, 'quotationlines':quotationlines, 'new_quotation_line':newquotationlineform, 'table_title':"Quotation Lines", 'table_heading_1':"Article", 'table_heading_2':"Amount", 'table_heading_3':"Price per Piece", 'table_heading_4':"Lead Time", 'table_heading_5':"Line total" } return redirect('sales-quotations') And my template: {% extends "start/parent.html" %} {% block body %} <!-- Content … -
HEROKU (Dockerfile that does not exist)
tried hosting my django website on Heroku, but keeps getting dockfile does not exist which is from the heroku.yml file Waiting on build... Waiting on build... (elapsed: 6s) Waiting on build... (elapsed: 9s) === Fetching app code =!= There were problems parsing your heroku.yml. We've detected the following issues: build.docker.web references a Dockerfile that does not exist below is a screenshoot of my vscode explorer and heroku.yml fileVScode Screenshot -
Two detail tabels with a foreign key to the same master table, how to limit a ManyToManyField to see only the subset of the other detail tabel
In Django I have an Order and Contact table that both have a foreignKeyField to the User table, in the Order table I want a ManyToManyField to see only the subset of Contact table records that belong to the same User, instead of the ManyToManyField seeing all of the records of the contact table. class Contact(models.Model): cnt_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=30, blank=False, null=True) class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='order_set') ref_code = models.CharField(max_length=20, blank=True, null=True) ### ManyToManyField should only see subset of contacts that have same user. contacts = models.ManyToManyField(Contact, blank=True, limit_choices_to={'cnt_user': user}) I cannot figure out how to set the limit_choices_to parameter or how to use a callable in this case. In this example ({'cnt_user': user}) django sees user as a "foreignKey object" not a "user object" this results in the following error: Field 'id' expected a number but got <django.db.models.fields.related.ForeignKey: user>. To me, "this problem" does not seem to be an uncommon scenario, I am hoping there is a straightforward solution. Can anybody show me an example of how to this, either by a callable or a Q object or any other way (proxy model maybe)? Thanks in advance. -
Django Project CORS error after deployment
I got Pyton Django project and my project work on local server but when i deploy on server i got this error.I used IIS Manager for deployment.Other DB connection must be work because i can reach other APIs.By the way my user is superuser. Access to XMLHttpRequest at 'https://website.websites.com:8000/integration/sync' from origin 'https://website.website.com' has been blocked by CORS policy: No 'Access-Control- Allow-Origin'header is present on the requested resource. And here is my API;POST https://website.website..com:8000/integration/sync net::ERR_FAILED 500 (Internal Server Error) By the way OTher API are working without problem I search about error and they suggest me to change setting.py but under below is my settings; ALLOWED_HOSTS = ['*'] CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', I use for deployment IIS may be its about it. So they said that its about Autontication IIS I tried every combination but it still doesnt work, -
I have a Category model and a subCategory model and a product model which has foreign key with category and sub category
I have a Category model and a subCategory model and a product model which has foreign key with category and sub category . Whenever a client will add a product then he will select a category and according to that the related subcategory should shown or change without submitting the form in django admin panel. Please tell me how to do this. The value should change on "onChange event" of the category. -
Django Channels on IIS using FASTCGI
I am deploying a Django app using an IIS server. In this Django app, I have implemented Django Channels to use websockets. Locally, everything is working fine with websocket connections, and I am able to send messages. However, the issue arises when I deploy the Django app. The HTTPS works perfectly fine, but the WSS (WebSocket Secure) is not working. I encounter a 404 not found error. the url in which I am trying is wss://my_domain/ws/start-quiz/ also note that i am using memurai instead of redis to use channel_layers CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6370)], }, }, } -
How to set default value of a model field to another field of same mode in django
I've created a Student model in django project with has a field named "enrollmentdate" and "paymentdate" now i need to save "paymentdate" as default value in "enrollmentdate" my model code is as under, > ``` class Student(models.Model): fname = models.CharField(max_length=100) lname = models.CharField(max_length=100) email = models.CharField(max_length=100) password=models.CharField(max_length=100) contactno = models.CharField(max_length=100) address = models.TextField() grade=models.CharField(max_length=100) enrollmentstartdate=models.DateField() enrollmentenddate=models.DateField() daysremaining=models.IntegerField() feespaid=models.DecimalField(max_digits=6, decimal_places=2) paymentdate=models.DateField() > ``` how can i do this? thanks in advance I have tried entrollmentdate=models.DateField(default=paymentdate) but not works -
How can I establish a connection between the front-end and a database?
I have created a website with Django that features a combined login and registration page. Now, I want the user data to be successfully saved in the database upon registration. How can I accomplish this? I expect that after a user registers successfully, they can log in successfully as well, and their data should be present in both the back-end management system and displayed within the database. I am building the front-end using HTML, CSS, and JS. -
Django serializer
this serializer class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'email', 'password'] extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): #user = super(RegisterSerializer, self).create(validated_data) user = User.objects.create_user(**validated_data) return user and Loginserializer : class LoginSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, data): username = data.get('username') password = data.get('password') if username and password: user = authenticate(username=username, password=password) if user and user.is_active: return user raise serializers.ValidationError("Invalid credentials!") I used this code and worked well but when I changed my Register serialzer class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'email', 'password'] extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = super(RegisterSerializer, self).create(validated_data) return user the code does not work well . when I want to test my endpoint in Postman the code creates user very well but for login endpoint I always take this response Invalid credentials I don't know what has happened when I changed my code first works well but when I add this line it did not work "user = super(RegisterSerializer, self).create(validated_data)" -
Data store multiple time in django admin panel
I am submitting the form once in the django admin panel, but the data are shown twice. here is my code: views.py: def checkout(request): if request.method == 'POST': country = request.POST['country'] fname = request.POST['fname'] lname = request.POST['lname'] C_address= request.POST['C_address'] state= request.POST['state'] zip = request.POST['zip'] emailADD = request.POST['emailADD'] phoneNO= request.POST['phoneNO'] y = checkoutitem(country=country,fname=fname,lname=lname,C_address=C_address,state=state,zip=zip,emailADD=emailADD,phoneNO=phoneNO) y.save() return render(request,'checkout.html') models.py: class checkoutitem(models.Model): country = models.CharField(max_length=100,default='') fname = models.CharField(max_length = 100,default='') lname = models.CharField(max_length =100,default='') C_address = models.CharField(max_length=255 , default='') state = models.CharField(max_length=100,default='') zip = models.CharField(max_length=100,default='') emailADD = models.EmailField(max_length = 100,default='') phoneNO = models.CharField(max_length =10,default='') urls.py: path('checkout/', views.checkout, name="checkout") I want to display a data only once not twice. So, give me solution. -
Django " [ was not closed " error in url routing
I'm new to python. Trying to understand and following the tutorials. One of the many tutorials that I follow, in django for url routing we are creating url.py and put our routing logic inside that file as below: urlpatterns = [ path=("",views.index), path=("/index",views.index) ] In every tutorial that syntax is working. But in my example it throws an error as below: I did not understand why it is showing me error and not for others. Also I have tried so assign path method into a variable and after that It worked. Am I missing syntax rule or someting? -
django string interpolation struggles
Hi so I am having a problem trying to concatenate in django. I have created a new templatetag and im trying to get the string interpolation right and im struggling a bit. {% button text="Reset" onclick="test('{{user.id}}')" colour="yellow" %} function test(user_id){ console.log('user id:', user_id) } the console log just gives back user id: {{user.id}} {% button text="Reset" onclick="test('"|add:user.id|stringformat:"s"|add:"')" colour="yellow" %} I have also tried this way but it just gives me a syntax error. any help on how to properly do this or even if its not possible any help would be great. (still new to django) -
Django: Generate random time in a within a specific day and insert multiple rows to database
I have a schedule for user in which it will generate randomly. For example I want to create and schedule for tomorrow, the admin will choose a day and N number of report a day. So the no_of_route is the # of rows to insert in database and also the # of generated hours and the # of route it will select from RoutePoints class. So, I really don't know to to generate hours. And this is where it should be. no_of_route = request.POST.get('no_of_route') date = request.POST.get('date') # generate hours, if no_of_route is 3, it would be 9AM, 1PM, 5PM hour = ... This is how I select random route id. items = list(RoutePoints.objects.all()) random_route = random.sample(items, no_of_route)[0] And this where I create multiple of rows. I'm not really sure how to do it. Schedule.objects.bulk_create(route=items.id, time=hour, date=date) Hope someone see this. Thank you in advance! -
Hosting a Django application on azure app service
After following the official host python with postgres tutorial, and making modifications in my gh actions file because my django apps isn't present in the root on the repo, I get a 404 error when trying to access it. Here is my settings.py """ Django settings for server project. Generated by 'django-admin startproject' using Django 5.0.3. For more information on this file, see https://docs.djangoproject.com/en/5.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/5.0/ref/settings/ """ from decouple import config from os import environ from google.oauth2 import service_account from pathlib import Path from django.conf import global_settings # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config( "SECRET_KEY", default="django-insecure-g8khpcexyyb0q@p40^d5#r_j#ezf%(-90r-y^2@x1)2$wpch9+", ) # SECURITY WARNING: don't run with debug turned on in production! DEBUG = config("DEBUG", default=False, cast=bool) ALLOWED_HOSTS = ( [environ["WEBSITE_HOSTNAME"]] if "WEBSITE_HOSTNAME" in environ else config( "ALLOWED_HOSTS", cast=lambda v: [s.strip() for s in v.split(",")], default=[] ) ) CORS_ALLOWED_ORIGINS = config( "CORS_ALLOWED_ORIGINS", cast=lambda v: [s.strip() for s in v.split(",")], default="http://localhost:5173,http://127.0.0.1:5173", ) # Application definition INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", … -
Invalid block tag on line ...: 'endblock', expected 'endwith'. Did you forget to register or load this tag?
I have a problem with my project on Python Here is a code, that located in Django template {% extends "base.html" %} {% load django_bootstrap5 %} {% block content %} <form method="post"> {% csrf_token %} {% bootstrap_form form %} {% bootstrap_button button_type="submit" content="Отправить" %} </form> **{% with data=request.POST %}** {% endblock %} When i reloading the page i receive an error on screenshot. error screen After the deleting this string, everything fine. {% with data=request.POST %} I dont understand what wrong ??? Iam trying to delete the string, that leads to an error, it helps, but according to the conditions of the task this string is must to be in this block of code -
How to Enable DEBUG Logging in Django?
I'm currently working on implementing logging in my Django project, but I'm encountering an issue where calls to logger.debug('log') do not output anything. I suspect there might be something wrong with my logging configuration. Below is the LOGGING configuration from my settings.py: logger = logging.getLogger(__name__) logger.debug(f"debug from logger") DJANGO_LOG_LEVEL = "DEBUG" LOGGING = { 'version': 1, 'disable_existing_loggers': False, "formatters": { "verbose": { "format": "{levelname}: {message} ({process:d}:{thread:d}::{filename}:{lineno}::{asctime})", "style": "{", 'datefmt': '%Y-%m-%d %H:%M:%S', }, "simple": { "format": "{levelname}: {message} ({filename}:{lineno})", "style": "{", }, }, 'handlers': { 'stdout': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple', }, "file": { "level": "INFO", "class": "logging.FileHandler", "formatter": "simple", "filename": logs_path.joinpath(f"{STAGE}-django.log").as_posix(), }, "mail_admins": { "level": "INFO", "class": "django.utils.log.AdminEmailHandler", "include_html": True, }, }, 'loggers': { '': { 'handlers': ['stdout', 'file'], 'level': 'DEBUG', 'propagate': True, }, 'django': { 'handlers': ['stdout', 'file'], 'level': 'WARNING', 'propagate': True, }, "django.request": { "handlers": ["mail_admins"], "level": "ERROR", "propagate": False, }, }, } Some can help me to figure out what's wrong with my logging configuration? -
DJANGO [WinError 10061] email features
I'm working in a Django project that uses the mail features. When try to send the mail I got this error message: [WinError 10061] No connection could be made because the target machine actively refused it. I'm using an email with godaddy domain. This is my configuration: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtpout.secureserver.net' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = 'mymail' EMAIL_HOST_PASSWORD = 'mypassword' I have tried all the related questions like: How to fix ConnectionRefusedError: [WinError 10061] the target machine actively refused it? (Django e.mails) I checked the firewall and none of the ports like 587, 25, 465, etc. were blocked. I also tried to connect with office365 server and didn't work. I don't know if this worth, but I have errors connecting with some pages for example when I run pip install library, gives an error related to SSL certification and only works if I bypass with --trusted-host. Maybe in this case I need to use something similar.