I turned debug to False in my settings.py file (note that before I turned it to false, everything was workign perfectly) and when I ran git push heroku master and went to my website, the home page was working but that wasn't the case for all of my pages: on some, I got an error saying Server Error (500)
Here is my settings.py code :
DEBUG = False
ALLOWED_HOSTS = ["hacka-labs.herokuapp.com"]
What I have noticed is that the urls where I pass an id aren't working
Please help me if you know the answer
I had a similar problem and it's hard to figure out when DEBUG is set to False. When I reconfigured it back to DEBUG = True everything worked fine again. So the problem was
You don't generally see this error in development because when DEBUG = True, ManifestStaticFilesStorage switches to non-hashed urls.
https://stackoverflow.com/a/51060143/7986808
The solution to the problem in your case may differ from mine. But you can find the problem by changing the logging method of your Django project, so you can see more info in the command line when running heroku logs -t -a <heroku-app> even in DEBUG = False mode.
Change your django logging settings in settings.py as follow:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': ('%(asctime)s [%(process)d] [%(levelname)s] '
'pathname=%(pathname)s lineno=%(lineno)s '
'funcname=%(funcName)s %(message)s'),
'datefmt': '%Y-%m-%d %H:%M:%S'
},
'simple': {
'format': '%(levelname)s %(message)s'
}
},
'handlers': {
'null': {
'level': 'DEBUG',
'class': 'logging.NullHandler',
},
'console': {
'level': 'INFO',
'class': 'logging.StreamHandler',
'formatter': 'verbose'
}
},
'loggers': {
'django': {
'handlers': ['console'],
'level': 'DEBUG',
'propagate': True,
},
'django.request': {
'handlers': ['console'],
'level': 'DEBUG',
'propagate': False,
},
}
}
Then run heroku logs -t -a <heroku-app> and open the url where you previously got 500 Error you will find out the problem in logs. Hope this will help you.
In case there are some static files missing just switch your static root in settings.py as follow STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles'). Running heroku run python manage.py collectstatic -a <heroku-app> creates staticfiles directory.
I had the same error.
I solved issue by removing import django heroku in settings.py
I had the same error while deploying react and django project on heroku.
I had been debugging for 2 days, doing all things like allowed host, staticfiles, json, whitenoise things but that still didn't solve the problem.
If your browswer throws error 500 then set DEBUG=True in settings.py. If it throws a TemplateDoesNotExist error at index.html then changing views.py may help solve that. Don't forget to setDEBUG=False before deploying.
I solved it by changing some code in views.py.
def index(request):
return render(request,'ur_app_name.html')
TO
def index(request):
some_variable_name=TemplateResponse(request,'ur_app_name.html',{})
return some_variable_name
Dont't forgot to import this on top of views.py
from django.template.response import TemplateResponse
I don't know what exact problem I was facing, I guess it's an httpResponse thing because server needs http request and our local machine does not need it.
Some key points points for this error:
Make sure you mention your domain name in ALLOWED_HOST in settings.py file
set STATIC_ROOT=os.path.join(BASE_DIR, 'staticfiles') in settings.py, this maybe needed when heroku throws a
collecticstatic error but I am not sure. If it still throws the
same error then disable collectstatic=1 on command (you can find
the exact command for this in the debug log) which does not create
any problem.
set whitenoise.middleware.WhiteNoiseMiddleware, in MIDDLEWARE in settings.py, this might help.
If your project uses react and django then choose python only on add build pack on heroku. Do not choose node.js.
This is the github repository where I upload my heroku project you can find the config files here which maybe helpful.
If your project uses react and django and above suggestions didn't help this may help:
check .gitignore files, install all requirement.txt files
and copy package.json file in root directory.
set "build": "cd <project folder name>&& react-scripts build", in scripts in package.json
My index.html and manifest.json is in the github repo mentioned above.
The 'staticfiles' directory was created in the root folder using '$ python manage.py collectstatic'. Try copying my index.html file if your project doesn't have one.
That's all.
The herokuapp link :https://sainterface.herokuapp.com/
Related
I am trying to make Django create and rotate new logs every 10 minutes using TimedRotatingFileHandler. My settings is as follows:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'file': {
'level': 'DEBUG',
'class':'logging.handlers.TimedRotatingFileHandler',
'filename': 'logs/site.log',
'backupCount': 10,
'when':'m',
'interval':10,
},
},
'loggers': {
'django': {
'handlers': ['file'],
'level': 'DEBUG',
'propagate': True,
},
},
}
The first log file is created successfully. But when it is time to rotate the log file, I get the following error:
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'F:\\logs\\site.log' -> 'F:\\logs\\site.log.2021-05-22_19-18'
How do I configure the logging so that the current log is copied to a timed log and new data written to the main log file?
Unfortunately, this file handler is not suitable for Windows, as any opened file cannot be moved or renamed. As it may work fine under some circumstances when using ./manage.py runserver, it will fail when trying to use it wit any production-ready wsgi or asgi server as those servers are spawning multiple processes that are not aware of other ones having the log file open.
Answering my own question. The solution that seems to work for me is including the flag --noreload when running the server.
This allows the logs to be rotated correctly although I don't know why.
I've created a project in Django and have deployed it to Heroku. Unfortunately, a number of things that were working locally, now don't work on Heroku. To troubleshoot I need to be able to write to the Heroku logs when my program runs so that I can troubleshoot better. So far I have not gotten it to work
My settings/staging.py file contains:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'loggers': {
'django': {
'handlers': ['console'],
'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'),
},
},
}
I have an app called accounts, so my accounts/views.py file contains:
import logging
log = logging.getLogger(__name__)
def auth_profile(request):
log.debug('TESTING THE DEBUGGER')
When auth_profile is accessed I want to see the text 'TESTING THE DEBUGGER' show up in the Heroku logs, but so far I get nothing.
How do I get this to work?
I think if you drop a log.error you would probably see something.
I had the same problem and it turns out heroku's settings tool breaks the pre-existing LOGGING setup. The logger you are using is not registered with django but is making its own way to the console using python's standard logging system.
Try doing:
django_heroku.settings(locals(), logging=False)
Or better yet, don't use it at all anymore since this package is no longer maintained anyway.
I have a form which takes data and is supposed to insert it into a database. When I am processing that form it gives me a value error, but when I go to the database and try to insert it manually it works fine.
In order to debug this situation, I want to see what query Django is generating which is failing. On the debug webpage I didn't see anything like SQL query.
How can I see the actual query generated by Django?
Please advise.
Thanks.
How about using logging?
you can add this in settings.py
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
},
},
'loggers': {
'django': {
'handlers': ['console'],
'level': 'DEBUG',
'propagate': True,
},
},
}
and you can add this in your any views.py
import logging
l = logging.getLogger('django.db.backends')
l.setLevel(logging.DEBUG)
l.addHandler(logging.StreamHandler())
In your console, you can check SQL query.
Another way
go shell
python manage.py shell
>>from yourmodel import Example
>>queryset = Example.objects.all()
>>print(queryset.query)
you can see raw query string.
If you happen to use PyCharm, running your application in the debugger gives you the full context. Set a breakpoint, and browse in your app to the point you are having the error and get a screen like (trivial example):
Running in this way has changed the way I troubleshoot when using Django. I suspect other IDE's may have similar features. Some further video documentation of the process from the vendor at:
https://www.youtube.com/watch?v=QJtWxm12Eo0
As Jayground suggested, logging is probably something you'll turn on eventually anyway; great suggestion.
According to django docs
connection.queries includes all SQL statements – INSERTs, UPDATES, SELECTs, etc. Each time your app hits the database, the query will be recorded.
So you can access these queries by running
from django.db import connection
print(connection.queries)
I have very good question which I would like an expert to comment on that for me please. (perhaps Graham Dumpleton)
So I have a Django web application (developed on ubuntu 16.04) which loges some failures as below on /var/log/apache2/APPNAME.log.
since all files in /var/log/apache2 have root:adm owner, I granted ownership of my log file the same way and I made sure www-data is a member of adm group. Then I granted rwx to adm group for owner group and I tested everything was working fine.
After 24hr the permission of the file and the parent folder has changed and I can see the write permission has been revoked from the log file and the parent directory causing permission denied error in error because the log file couldn't be written.
Here are my questions if you could kindly help:
1) where is the right place to put Django log files?
2) What process under what user permission writes the file?
3) Which process resets permissions in the /var/log/apache and why?
Thank you much in advance,
I hope this question help others too.
Cheers,
Mike
views.py
from django.shortcuts import render
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django import forms
from django.core.mail import send_mail, EmailMessage
from StudioHanel.forms import ContactForm
import traceback
import time
# import the logging library
import logging
import sys
# Get an instance of a logger
#logger = logging.getLogger('APPNAME')
def contact(request):
logger.debug('Contact Start!')
if request.method == 'POST':
etc...
settings.py
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
},
'applogfile': {
'level':'DEBUG',
'class':'logging.handlers.RotatingFileHandler',
'filename': os.path.join('/var/log/apache2', 'APPNAME.log'),
'maxBytes': 1024*1024*15, 15MB
'backupCount': 10,
},
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
'APPNAME': {
'handlers': ['applogfile',],
'level': 'DEBUG',
},
}
}
1) where is the right place to put Django log files?
Recently I initiated a discussion in the django-users mailing list about the directories to use for Django projects, and I concluded there is no standard practice. I've settled on using /var/log/django-project-name.
In any case, /var/log/apache2 is the wrong place because of the problem you identified, that logrotate will interfere. More on that below.
2) What process under what user permission writes the file?
If you use Gunicorn, it's the gunicorn process, and if you use uWSGI, it's uwsgi. Judging from your reference to Graham Dumpleton, you are using mod_wsgi. So the process is the mod_wsgi daemon.
The user as which these processes are writing to the file is the user as which the process runs. For mod_wsgi, you can specify a user option to the WSGIDaemonProcess directive. According to its documentation, "If this option is not supplied the daemon processes will be run as the same user that Apache would run child processes and as defined by the User directive." In Ubuntu, this is www-data. I think it's a good idea to use the user option and run the daemon as a different dedicated user.
You should not add www-data to the adm group. The adm group is people who have permission to read the log files. www-data should not have such permission. (Reading and writing its own log files is fine, but you wouldn't want it to have permission to read /var/log/syslog.)
3) Which process resets permissions in the /var/log/apache and why?
It's logrotate, which is run by cron; see /etc/cron.daily/logrotate. The configuration at /etc/logrotate.d/apache2 manipulates all files matching /var/log/apache2/*.log. The primary purpose of logrotate is to, well, rotate logs. That is, it creates a new log file every day, yesterday's is named access.log.1, before yesterday's access.log.2.gz, and so on, and logs older than some days are deleted. This is done to save space and to keep the logs manageable. logrotate will also fix the permissions of the files if they are wrong.
In theory you should configure logrotate to also rotate your Django project's logs, otherwise they might eventually fill the disk.
For mod_wsgi you are better to direct Python logging to stderr or stdout so that it is captured in the Apache error log. Don't create a separate log file as by using Apache log file, things like log file rotation will be handled for you automatically. For an example see under 'Logging of Python exceptions' in:
http://blog.dscpl.com.au/2015/04/integrating-modwsgi-express-as-django.html
Do ensure though that you configure a separate error log for Apache for the VirtualHost so that your logging for site is saved away separately to main Apache error log.
I'm looking for a way to write to console only when Django tests are run with high verbosity level.
For example - when I run
python manage.py test -v 3
It would log my messages to console, but, when I run
python manage.py test -v 0
It would not log my messages.
I tried to use logger.info() in the code but the messages do not show up at all.
Any suggestions?
-v controls the verbosity of the test runner itself (eg: DB creation, etc), not the verbosity of your app's logging.
What you actually want, is to change the logging level of the django app itself, as described in the logging documentation.
You may want to simply override the logging settings just for tests, or you can use --debug-mode to set settings.DEBUG to True, and include a DEBUG-specific configuration in your settings.py (this is rather common since it also helps when developing).
This is a basic example of how to achieve the latter:
'loggers': {
'': {
'handlers': ['console', 'sentry'],
'level': 'INFO',
},
'myapp': {
'level': 'DEBUG' if DEBUG else 'INFO',
'propagate': True,
},
}