Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Boolean Field is False when I check it
Models.py : class DriverInfo(models.Model): name = models.CharField(max_length=16, blank=True, null=True) yn = models.BooleanField(default=0) Forms.py : class DriverForm(forms.ModelForm): name = forms.CharField(label='', widget=forms.TextInput(attrs={'class':'form-control','placeholder':""})) yn = forms.BooleanField(required=False) This is my model and form. When I submit form, The BooleanField is false when it is checked or nothing when it is not checked. (I found this problem when I raise a ValueError.) I want to make it True when it is checked, False when it is not checked. What should i do? -
Can't get two Python loggers to work at the same time
Related to a previous question I asked, Airbrake logger in Django still sending notifications even though its level is set to 'CRITICAL'?, I'm working on a Django project with multiple versions of settings.py: settings/base.py, settings/staging.py, etc. There is also a kind of settings 'mixin', settings/staging_development.py, which contains the following LOGGING configuration: # Auxiliary variable used in LOGGING _AIRBRAKE_LOGGER = { 'handlers': ['airbrake'], 'level': 'ERROR', 'propagate': True, } # Airbrake logging integration (cf. https://github.com/airbrake/pybrake#django-integration) # In our case, 'app' is replaced by three apps, 'lucy_web', 'api', and 'activation'. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'airbrake': { 'level': 'ERROR', 'class': 'pybrake.LoggingHandler', }, }, 'loggers': { 'lucy_web': _AIRBRAKE_LOGGER, 'api': _AIRBRAKE_LOGGER, 'activation': _AIRBRAKE_LOGGER, }, } This is imported in settings/staging.py in which LOGGING is further .update()d as follows: from lucy.settings.staging_production import * # LOGGING = { # 'version': 1, # 'disable_existing_loggers': False, # 'handlers': { # 'console': { # 'class': 'logging.StreamHandler', # }, # }, # 'loggers': { # 'django': { # 'handlers': ['console'], # 'level': os.getenv('LOG_LEVEL', 'INFO'), # }, # }, # } LOGGING['handlers'].update(console={ 'class': 'logging.StreamHandler' }) LOGGING['loggers'].update(django={ 'handlers': ['console'], 'level': os.getenv('LOG_LEVEL', 'INFO'), }) What I'd like to achieve is to log to Airbrake as well as to the console. … -
Cannot import behave.given in pydev for django
I have a Django project for which I am incorporating BDD using behave. I am using PyDev as my development environment. I have installed behave_dhango and behave using pip within the conda environment and I can see that the folders have been created in the site-packages folder within the right conda 'env'. For some reason, I am not able to import the 'given, when and then' decorators from behave as thus: from behave import given, when, then It says "Unresolved import given... when... and then..." I have not found any naming conflicts and cannot understand the reason why the above code isn't working. Python 2.7 Django 1.11 behave 1.2.6 -
Flask CPU and RAM usage with concurrent user sessions?
I'm thinking about making a website of mine using the Flask framework just because the underlying logic would be easier to program with the python modules I have available. But before I begin just so I can consider scalability, say a user visits the site and does X actions which trigger X definitions and logic in the flask website via python, would each user session effectively be creating a python object adding to memory consumption and using the server side CPU to carry out the logic? Meaning once concurrent users were added the usage of the server would get incredibly high? Versus running similar logic using a REST api to fetch data and client-side javascript on the site? Or am I not understanding this correctly? -
How To Keep My File Paths Congruent for My Django/Python Application
I am developing a Django app on my Personal Computer. I have my files uploaded to a private repository on GitHub and I am using that to pull them down to my production server. My question is this I have file paths set inside of my application on my PC to file locations that are on my PC. But I also have those same files being uploaded and pulled onto my Production Server, but then needing to change the file path on my Production Server side application files in order to match the actual location on my Production Server I have searched far and wide and cannot seem to find a proper solution to this. Is there some type of way I can write out the paths so that when I use an sys.path.append I don't have to give out the complete path, but rather a local one, so that it matches on both servers? -
django, python, postgres and web deployment
This error has been haunting me. I have actually developed fixes and I document it and I successfully run the server on the below IP address. I try to reproduce my success after reinstalling the Ubuntu OS... with the same errors the same fixes won't do it anymore... now I need outside help. I have combed the internet for solutions. I try to add django to the PYTHONPATH and it IS added but when I exit the python interpreter the appended django path disappears! Another item of detail that may help is that my website www.doman.com/admin is directed to the django admin login screen. I tried to log in using username and password but it fails which makes me think django is not working properly. $ sudo python3 manage.py runserver 192.165.4.3:80 I get the error: Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 14, in <module> ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to … -
CSS3 background property and django framework
I have background: url('../images/matin.jpg') no-repeat center center fixed; as one of my CSS property in a Django application, I run collectstatic with no problems, but the image is not displaying, when I inspect the page/element targeted, it shows the image is being reached, what am I missing here? -
No name 'path' issue, unable to start project in django, lubuntu
So I recently downloaded python3 and django-2 but I realised my computer has already python 2 and django 1.11, so I managed to create project with django 3 using python3 django -m startproject or something like this, even I managed to create a django 2 project, this time at the urls.py, it says "No name 'path' in module 'django.urls'. Can you help me with how to create a project using django2 and python3 in lubuntu and this error. -
How can how to link submit button with javascript function in django?
I want to display the script code by clicking on the button, but when I click nothing happens the model fields : PointDeCollecte (nom , latitude , longitude ) normally by clicking on the button it returns the data of select (#id vehicle) and (#id PointDeCollecte) vehicules:list of selected vehicles demandes : list of selected ({{PointDeCollecte.latitude}},{{PointDeCollecte.longitude}}) """" <form> <div class="form-row"> <div class="form-group col-md-6"> <label for="pt_collecte">Les destinations a visités </label> <select multiple class="form-control" id="pt_collecte"> {% for PointDeCollecte in pt_collectes%} <option value="{{ PointDeCollecte.id }}">{{ PointDeCollecte.Nom }} </option> {% endfor %} </select> </div> <div class="form-group col-md-6"> <label for="vehicule_sel">Les véhicules a utilisés </label> <select multiple class="form-control" id="vehicule_sel"> {% for vehicule in vehicules %} <option value="{{ vehicule.id }}">{{ vehicule.Matricule }}</option> {% endfor %} </select> </div> </div> <div class="form-group col-md-4"> <button id="resoudre" class="btn btn-primary my-1">valider </button> </div> </form> <div class="card card-map"> <div class="map"> <div id="map"></div> </div> </div> </div> <script> $(document).ready(function() { $("#resoudre").click(function(){ var strVehicules = $('#vehicule_sel')[0].value.innerText; var vehicules = strVehicules.split(" "); var idDemandes = $('#pt_collecte')[0].value; p = PointCollecte.objects.get(id=idDemandes); var strDemandes = (p.Latitude,p.Longitude); var demandes = strDemandes.split(" "); myMap(vehicules,demandes); }); function myMap(vehicules,demandes){ initMap(vehicules,demandes); } function initMap(vehicules,demandes){ var map = new google.maps.Map(document.getElementById('map'), { zoom: 15, center: {lat: 33.589886, lng: -7.603869} }); if(vehicules.length > 1 && vehicules.length <= demandes.length){ … -
How can i send a post request using vue to django without getting a 403 error?
Im trying to send information using a post request of Vue, but every time i try i get an error 403 58 my django service is ok , i think that the problem is for the csrf token but i dont know how to send it with vue var vue = new Vue({ el:"#app", data: { nombre:"", apellido:"", password:"" }, methods:{ enviar:function () { data = { "nombre":this.nombre, "apelldio":this.apelldio, "password":this.password }; this.$http.post("http://localhost:8000/usuarios\\",data).then(function (data, status, request) { if(status ==200){ console.log(data); } },function () { console.log("Error"); }); } } }); <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="https://bootswatch.com/4/flatly/bootstrap.min.css"> </head> <body> <h1>Insertar un nuevo usuario </h1> <table id = "app"> <tr><td>Nombre:</td><td><input type="texte" class="form-control" v-model="nombre"></td></tr> <tr><td>Apellido:</td><td><input type="texte" class="form-control" v-model = "apellido"></td></tr> <tr><td>Password:</td><td><input type="texte" class="form-control" v-model="password"></td></tr> <tr> <td> <button type="button" id = "enviar" class="btn btn-info" @click="enviar">Enviar</button></td></tr> </table> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/0.1.13/vue-resource.min.js"></script> {% csrf_token %} <!-- here goes the scripts of vue and vue resource!> -
How to return a single object with Django-Rest-Framework
I'm trying to return a single object with profile information but am stuck getting an array in return. How do I just return a single object. Current output: [{"id":1,"username":"someusername"}] Desired output: {"id":1,"username":"someusername"} serializers.py from rest_framework import serializers from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username') views.py # from django.shortcuts import render from django.contrib.auth.models import User from profiles.serializers import UserSerializer from rest_framework import viewsets # Create your views here. class CurrentUserViewSet(viewsets.ReadOnlyModelViewSet): """ Lists information related to the current user. """ serializer_class = UserSerializer def get_queryset(self): user = self.request.user.id return User.objects.filter(id=user) -
How can I create delete button in Django?
I just started to learn Django and I was wondering how I can create just delete button without having route page. Basically what I want to do is delete an entry when user push the button. On home page there are a bunch of posts and users can delete a specific post without jumping into a specific post's page. But I don't know how I can do it. My current code is like this def delete(request, entry_id): '''Delete entry.''' if :#I'm not sure about efficient way to connect this to button. entry = get_object_or_404(Entry, entry_id=entry_id) entry.delete() return HttpResponseRedirect('/') html is this <button class="btn btn-danger">Delete</button> -
Django: How to use UpdateView to do two diferent things things
I have a list of items that i want to discount or increment a quantity using an UpdateView . I have named my 2 views differently and crated 2 links to each view on my urls but keep getting the same field. Models.py class Items(models.Model): nombre = models.CharField(max_length=250) descripcion = models.CharField(max_length=250) codigo_proveedor = models.CharField(max_length=250) categoria = models.ForeignKey('Categorias', on_delete=models.CASCADE) c_minima = models.PositiveIntegerField() c_actual = models.PositiveIntegerField() c_descuento = models.PositiveIntegerField(blank=True) c_incremento = models.PositiveIntegerField(blank=True) proveedor = models.ForeignKey('Proveedores', on_delete=models.CASCADE) carrito = models.ForeignKey('Carrito', on_delete=models.CASCADE, null=True ) p_unitario = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True ) total = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) material = models.ForeignKey(Materiales, null=True, blank=True) tipo = models.ForeignKey(Tipo, null=True, blank=True) active = models.BooleanField() def save(self, *args, **kwargs): self.c_actual = self.c_actual - self.c_descuento self.c_actual =self.c_actual + self.c_incremento self.total = self.c_actual * self.p_unitario super(Items, self).save(*args, **kwargs) def __str__(self): return '%s %s %s %s' % (self.nombre, str(self.categoria), str(self.c_actual), str(self.total)) urls.py #HACE EL DESCUENTO DE LAS CANTIDADES EXISTENTES url(r'^item_update/(?P<pk>[-\w]+)/$', views.CatItemUpdateDesc.as_view(), name='CatItemUpdateDesc'), #HACE EL DESCUENTO DE LAS CANTIDADES EXISTENTES url(r'^item_update/(?P<pk>[-\w]+)/$', views.CatItemUpdateInc.as_view(), name='CatItemUpdateInc'), views.py # DESCUENTA ARTICULOS DE LA LISTA DE ELEMENTOS class CatItemUpdateDesc(UpdateView): model = Items fields = ['c_descuento'] template_name_suffix= '_update_form' context_object_name = 'items' success_url = reverse_lazy('inventory:cat-list') def get_context_data(self, **kwargs): context = super(CatItemUpdateDesc, self).get_context_data(**kwargs) context['categoria'] = Items.objects.all() return context # INCREMENTA ARTICULOS … -
How to pass variable from CLI program to Python Views to Update Django UI?
I have a Django app which calls a CLI app by function call and then CLI app performs action and delivers output. The CLI version has a loading bar which displays the progress of the process, My plan is to integrate it with GUI. The project is huge so I simplied it to a shorter project to make it clear for ya'll to understand. The real app has more nuanced and complex than this demo app So, I created a tiny demo project to simplify the question for you all. Project Structure is │ db.sqlite3 │ manage.py │ ├───testapp │ │ admin.py │ │ apps.py │ │ models.py │ │ tests.py │ │ views.py │ │ views.pyc │ │ __init__.py │ │ __init__.pyc │ │ │ ├───cliprog │ │ cliprogram.py │ │ cliprogram.pyc │ │ main.py │ │ │ └───migrations │ __init__.py │ └───testproject settings.py settings.pyc urls.py urls.pyc wsgi.py wsgi.pyc __init__.py __init__.pyc views.py from django.shortcuts import render from django.http import HttpResponse from django.conf import settings from cliprog.main import view_helper def index(request): view_helper() return HttpResponse('It works but CLI') cliprog/main.py from cliprogram import nice def view_helper(): # So, that I can call this function and run my cli code # do something … -
Django - Can't login to superuser after creating from terminal
Not sure why this is happening, I've searched stack and can't seem to find out why this is acting up. When i run superuser in terminal, I'm able to create and set the password. It shows me that the superuser has been created. Once I head over to /admin, I can't sign in and it tells me, Please enter the correct email and password for a staff account. Note that both fields may be case-sensitive. Here's the code: Models.py class UserManager(BaseUserManager): def create_user(self, email, password=None, first_name=None, last_name=None, is_admin=False, is_staff=False, is_active=False): # Creates a basic user and saves the email and password if not email: raise ValueError("Email is required.") if not password: raise ValueError("Password is required") user = self.model( email=self.normalize_email(email), first_name = first_name, last_name = last_name ) user.set_password(password) #Can also be used to change password user.staff = is_staff user.admin = is_admin user.is_active = is_active user.save(using=self._db) return user def create_staffuser(self, email, password=None, first_name=None, last_name=None): user = self.create_user( email = email, first_name = first_name, last_name = last_name, password = password ) user.staff = True user.save() return user def create_superuser(self, email, password=None,first_name=None,last_name=None): user = self.create_user( email = email, first_name = first_name, last_name = last_name, password = password ) user.staff = True user.admin = True … -
Airbrake logger in Django still sending notifications even though its level is set to 'CRITICAL'?
I have a Django project with multiple settings; there is a settings/base.py similar to # Airbrake (pybrake) settings AIRBRAKE = dict( project_id=os.getenv('AIRBRAKE_PROJECT_ID'), project_key=os.getenv('AIRBRAKE_PROJECT_KEY'), environment=os.getenv('AIRBRAKE_ENVIRONMENT', default='production'), root_directory=os.path.dirname(os.path.dirname(BASE_DIR))) # Auxiliary variable used in LOGGING _AIRBRAKE_LOGGER = { 'handlers': ['airbrake'], 'level': 'ERROR', 'propagate': True, } # Airbrake logging integration (cf. https://github.com/airbrake/pybrake#django-integration) # In our case, 'app' is replaced by three apps, 'lucy_web', 'api', and 'activation'. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'airbrake': { 'level': 'ERROR', 'class': 'pybrake.LoggingHandler', }, }, 'loggers': { 'lucy_web': _AIRBRAKE_LOGGER, 'api': _AIRBRAKE_LOGGER, 'activation': _AIRBRAKE_LOGGER, }, } and a settings/development.py containing import os import anyconfig from lucy.settings.base import * # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True # Set the Airbrake environment to 'development' AIRBRAKE.update(environment='development') # Log database errors to sys.stderr ADDITIONAL_LOGGING = { 'filters': { 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', } }, 'handlers': { 'console': { 'level': os.getenv('LOG_LEVEL', 'ERROR'), 'filters': ['require_debug_true'], 'class': 'logging.StreamHandler', }, }, 'loggers': { 'django.db.backends': { 'level': os.getenv('LOG_LEVEL', 'ERROR'), 'handlers': ['console'], }, # Disable Airbrake logging in development # (cf. https://github.com/airbrake/pybrake#disabling-pybrake-logs) 'lucy_web': {'level': 'CRITICAL'}, 'api': {'level': 'CRITICAL'}, 'activation': {'level': 'CRITICAL'}, } } # Update the default Airbrake logging with logging to the console anyconfig.merge(self=LOGGING, other=ADDITIONAL_LOGGING) where I've used anyconfig … -
500 error in Heroku, when Debug=False
I know that this questions has been asked numerous times but after going through pretty much every thread I could find, I am still struggling to make sense of my problem. I have a django project on heroku which works perfectly fine as long as I set the setting variable debug=True. https://dry-depths-69493.herokuapp.com/ However, once I have set it to False, I get a 500 error. I have checked the settings.py which has: ALLOWED_HOSTS = ['dry-depths-69493.herokuapp.com','127.0.0.1',"localhost", "0.0.0.0", ".herokuapp.com"] I have set unset all unnecessary env variables in Django and only added COLLECTSTATIC: 1 And I also have included Whitenoise and added dj_database_url. Does anyone have another idea, what could be the reason for these issues? Unfortunately the logs just say that it is a 500 error but give no specifics. Here is the github-link: https://github.com/Datenrausch/heroku -
An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block
Have read multiple sources for solutions such as Guaravs post, and Alexander, to name a few, but still not able to fix the issue. The error comes when creating a database entry. Using django 1.11.3 and MySQL 14.14 views.py . **only partial code since the function is over 600 lines long. try: item_to_group_keys = [] promo_key = 'promo:' + str(request.user.id) with connection.cursor() as cursor: with transaction.atomic(): oi_tax = models.OrderItemTax.objects.create(amount=tax_amount, rate=rate, order_item_id=order_item.id) oi_tax.save() except IntegrityError: return HttpResponse("<strong>CODE #700: Fatal Transaction Error! Please contact customer service.</strong>") -
How to configure nginx to find landing page / index page
I had most of the settings set up under the first server block (port 80) and the landing page "index.html" was working. When I moved the settings to the second server block for https, the landing page is 'not found'. I tried to direct nginx to it using 'root' and 'index', as shown, but unsuccessfully. 1. Is there anything I can add/revise to the following code? 2. Do you think it is another configuration issue somewhere else? Please advise. (Ubuntu 18.04 LTS) upstream project1_server { server unix:/home/user1/venv/run/gunicorn.sock fail_timeout=0; } server { listen 80; server_name www.domain.com; # Redirect all HTTP requests to HTTPS with a 301 Moved Permanently response. return 301 https://$host$request_uri; } server { listen 443 ssl http2; listen [::]:443 ssl http2; server_name www.domain.com; root /usr/share/nginx/html; index index.html; client_max_body_size 4G; access_log /home/user1/project1/logs/nginx-access.log; error_log /home/user1/project1/logs/nginx-error.log; location /static/ { alias /home/user1/project1/static/; } location /media/ { alias /home/user1/project1/media/; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://project1_server; break; } } error_page 500 502 503 504 /500.html; location = /500.html { root /home/user1/project1/static/; } ssl_certificate ssl_certificate /etc/letsencrypt/live/www.domain.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/www.domain.com/privkey.pem; ssl_session_timeout 1d; ssl_session_cache shared:SSL:50m; ssl_session_tickets off; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers 'ECDHE-...; ssl_prefer_server_ciphers on; add_header Strict-Transport-Security … -
Using Django Rest API, How do I submit post request for the builtin django user class
I am trying to submit post to my django rest api, but I am getting a misleading 400 Bad Request. When I look at django rest api documentations http://www.django-rest-framework.org/api-guide/relations/, it seem like they would not allow the model would not allow for a Post request to submit the foreign key. However, I the snapcapsule model to post what user it is link to. I tried submitting the link the user like successful User Post request. I am also have an error with in UserSerializing in making a relatedHyperLink field Snapcapsule. The error says, "User object does not have attribute snapcapsule." Again, referencing the earlier documentation link, Album does not have attribute of Track. models.py from django.db import models from django.contrib.auth.models import User # Create your models here. def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return 'images/user_{0}/{1}'.format(instance.user.id, filename) class SnapCapsule(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) dateToPost = models.DateTimeField() image = models.FileField(upload_to=user_directory_path) def delete(self, *args, **kwargs): # You have to prepare what you need before delete the model storage, path = self.song.storage, self.song.path # Delete the model before the file super(SnapCapsule, self).delete(*args, **kwargs) # Delete the file after the model storage.delete(path) Serializers.py class UserSerializer(serializers.HyperlinkedModelSerializer): snapcapsules = serializers.HyperlinkedRelatedField( many=True, read_only=True, view_name='snapcapsules-detail' … -
All my static files in Django are not found, but findstatic finds them
I am developing a Django site on an Ubuntu 16.04 LVM using Apache and mod_wgsi. When I try to load one of my pages, all the static files give a 404 not found error. I believe I have my settings set correctly because python3 manage.py findstatic is able to find the files and running the development server with DEBUG=off and the --insecure flag, It still works correctly. Does this mean it is an issue with apache? Here are my static file settings: STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), #'/home/matt/jukebox/bin/jukebox/static/' ) Does anybody know what could be wrong? The files were being served previously, but after updating my server and the code for the site, it stopped serving. Thank You -
Page not found (404) Request Method: GET Request URL: http://localhost:9090/mm.html
Page not found (404) Request Method: GET Request URL: http://localhost:9090/mm.html Using the URLconf defined in ABV.urls, Django tried these URL patterns, in this order: ^admin/ ^get_wfs/ ^get_turbines/ ^get_prods/ ^get_mtbts/ ^my_view/ ^get_tbas/ ^get_rbts/ ^get_pbas/ ^get_lps/ ^get_capfactors/ The current path, main.html, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. -
Docker setup for a development environment?
I'm trying to find out how to setup my current docker compose yaml file to run my dev env. I'm new to docker but I was given a project that uses it. version: '3' services: database: image: someinfo:9.5 environment: - POSTGRES_USER=user - POSTGRES_PASSWORD=pass volumes: - db-data:/var/lib/postgresql/data backend: build: . command: bash /somepath/server/django_devserver.sh volumes: - .:/volumeinfo links: - database ports: - "8000:8000" environment: DJANGO_SETTINGS_MODULE: projectname.settings.production SCHEMA: https DB_HOST: database PYTHONUNBUFFERED: 1 volumes: db-data: Currently this is running the Django production settings in my dev env. I want to keep that there but I also want to tell docker to run my dev settings when in the dev server. How can I do that? Would I create a new container called dev-backend with the dev vars? Then would I run docker-compose up dev-backend or something like that? Forgive my ignorance, today is my first day with Docker. -
Django Forms - ModelForms
I am joe, I come from RoR background, I am recently started learning Django and I came across some issues, well, it's not an actually issue, but more like a personal question, OK!I will be honest with you, I am having a hard learning Django forms, I mean, there are just kind of forms, and I am kinda lost, so, why should I used modelforms instead of using just forms. Please, tell me which one is more suitable for production. Should I stick with Model forms or just forms. -
Not receiving emails from Django's AdminEmailHandler?
I'm working on configuring the error notifications for a Django project. For redundancy, I'd like to use both Django's AdminEmailHandler as well as Airbrake (with pybrake). The problem is that although I'm receiving Airbrake notifications, I'm not receiving the Django error emails, which should contain the full traceback. The project has multiple settings which inherit from settings/base.py, which contains ANYMAIL = { "MAILGUN_API_KEY": os.getenv('MAILGUN_API_KEY'), "MAILGUN_SENDER_DOMAIN": 'mg.startwithlucy.com', } EMAIL_BACKEND = "anymail.backends.mailgun.EmailBackend" # Airbrake (pybrake) settings AIRBRAKE = dict( project_id=os.getenv('AIRBRAKE_PROJECT_ID'), project_key=os.getenv('AIRBRAKE_PROJECT_KEY'), environment=os.getenv('AIRBRAKE_ENVIRONMENT', default='production'), root_directory=os.path.dirname(os.path.dirname(BASE_DIR))) # Auxiliary variable used in LOGGING _LOGGER = { 'handlers': ['airbrake', 'mail_admins'], 'level': 'ERROR', 'propagate': True, } # Airbrake logging integration (cf. https://github.com/airbrake/pybrake#django-integration) # In our case, 'app' is replaced by three apps, 'lucy_web', 'api', and 'activation'. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'airbrake': { 'level': 'ERROR', 'class': 'pybrake.LoggingHandler', }, 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler', 'include_html': True, } }, 'loggers': { 'lucy_web': _LOGGER, 'api': _LOGGER, 'activation': _LOGGER, }, } The settings which I'm currently trying, settings/staging.py, contain import os import anyconfig from lucy.settings.base import * DEBUG = False # Set the Airbrake environment to 'staging' AIRBRAKE.update(environment='staging') ADDITIONAL_LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'loggers': { # …