How to test Django error reporting - django

In my settings I have this...
ADMINS = (
('Me', 'me#me.com'),
)
MANAGERS = ADMINS
DEBUG = False
ALLOWED_HOSTS = ['*']
and then in my views/urls I have these...
url(r'^test/$', 'main.views.test', name='page'),
def test(request):
return render(request, '500.html', status=500)
I have the email settings configured and I know they work because I have emails working from that server in other parts of my site. I have everything that is said to be required in the docs, but it is still not working and IDK where to go from here. I have tried it in my live environment too with no luck...

It turns out that my email settings were correct, but there was a new setting added for error reporting titled 'SERVER_EMAIL' that was supposed to be the default from email. I had a nonexistant email address in there and that is what was causing the emails to not be sent.

Related

How to employ an error alert system in a deployed Django Site

I am deploying my django site soon!! In debug=True mode, there is an error page that comes up when there is some bug in the code.
When in debug=False mode, after I deploy, I want to set up something so that I am alerted whenever anyone on the prod site reaches this page. Is there any way to do this? Thanks!
This setup would send an email after someone make a request. Here is the documention on sending emails through Django. https://docs.djangoproject.com/en/3.0/topics/email/
def home_page(request):
send_mail(
'Site Visitor',
'someone visted the site.',
'from#example.com',
['to#example.com'],
fail_silently=False,
)
return render(request, 'template')
For an "error alert system," you can look into Sentry. https://sentry.io/for/django/

Server Error (500) after deploy Django app on heroku

After deploy my django site on heroku all pages works fine except one page which is (view page) and that shows server error(500) on it.
Code in settings:
DEBUG = False
ALLOWED_HOSTS = ['.herokuapp.com', '127.0.0.1']
Code in View page:
# Create your views here.
#login_required(login_url='login')
#admin_only
def dashboard(request):
all_orders=Order.objects.all()
all_customers=customer.objects.all()
order_pending=Order.objects.filter(status='PENDING')
order_out = Order.objects.filter(status='OUT-FOR-DELIEVERY')
order_delievered = Order.objects.filter(status='DELIEVERED')
total_orders=all_orders.count()
total_orders_pending=order_pending.count()
total_orders_out=order_out.count()
total_orders_delievered=order_delievered.count()
context={'orders':all_orders, 'customers':all_customers, 'total_orders':total_orders,
'total_orders_pending':total_orders_pending, 'total_orders_out':total_orders_out,
'total_orders_delievered':total_orders_delievered}
return render(request, 'cms_app/Dashboard.html', context)
#login_required(login_url='login')
#allowed_user(allowed_roles=['admin'])
def product(request):
all_products=Product.objects.all()
context={'all_products':all_products}
return render(request, 'cms_app/Products.html',context)
#login_required(login_url='login')
#allowed_user(allowed_roles=['admin'])
def customer_data(request, id):
customers=customer.objects.get(id=id)
orders=customers.order_set.all()
all_orders=orders.count()
my_filters=OrderFilter(request.GET, queryset=orders)
orders=my_filters.qs
context={'customer_data':customers, 'all_orders':all_orders, 'orders':orders, 'my_filters':my_filters}
return render(request, 'cms_app/customer_Data.html',context)
If anyone knows this error. Kindly let me know
If anyone is also having this problem and no other solution seems to be fixing it, then try this.
Run locally with DEBUG=False, and you might see a "StopIteration" on a URL in one of your templates. Check and make sure you use forward slashes there, and not backslashes. This was causing the Server 500 error both locally & remotely with DEBUG=False, while it works locally and remotely with DEBUG=True.
See this post on the Django forums for more info on that: Django forum post.
I would normally use forward slashes, however a BootstrapStudio to Django template export script is generating backslashes. I just have to patch the export script code (a Python script).

Disable django allauth confirm email during social login

I've setup django-allauth and for so far linkedin, facebook and twitter after oauth2 confirms and redirects back it brings a form asking you to confirm email.
I've tried ACCOUNT_EMAIL_VERIFICATION = False doesn't remove it.
Try:
ACCOUNT_EMAIL_VERIFICATION (=”optional”)
in settings.py
See documentation.
Well, in fact even when the mail is sent, and the user clicks the link, django shows the form unless ACCOUNT_CONFIRM_EMAIL_ON_GET is set to True in the settings file:
ACCOUNT_CONFIRM_EMAIL_ON_GET = True
See docs:
http://django-allauth.readthedocs.io/en/latest/configuration.html?highlight=ACCOUNT_CONFIRM_EMAIL_ON_GET
I know this is not 100% an answer on the question but it helps to avoid the form which is annoying indeed.
In settings.py you must have:
SOCIALACCOUNT_AUTO_SIGNUP = True
Note that the default value is True (django-allauth docs), so if you have it set to False just remove this setting.

Sending email on Heroku with the Django application Spirit

I'm setting up on a Django site the elegant forum application Spirit, but having just a bit of trouble getting it to send emails on the Heroku installation. This is undoubtedly because I'm a novice, a little unsteady about sending emails in Django, and not quite sure how to get the relevant debugging info. Some help would be much appreciated.
I installed the Postmark addon plus the Python-Postmark library. On the local installation, everything is perfectly fine: registration emails get delivered as they should when using the installation on my machine. The problem is only with the deployment version.
Also, when I enter
heroku run python
from django.config import settings
from django.core.mail import send_mail
send_mail('this is a test from the heroku server','body',settings.DEFAULT_FROM_EMAIL, ['the.robot#example.com'],fail_silently=False)
then the Postmark server sends the message and it is received. So... it seems like the Postmark installation, and the Django command send_mail at least sort of work on the Heroku server. It's just when I request e.g. a user activation message through the browser while using the forum application itself, on the Heroku server, that the mail is not sent.
Postmark is configured in the site's settings.py files like this.
EMAIL_BACKEND = 'postmark.django_backend.EmailBackend'
POSTMARK_API_KEY = os.environ['POSTMARK_API_KEY']
POSTMARK_SENDER = 'the.robot#example.com'
POSTMARK_TEST_MODE = False
POSTMARK_TRACK_OPENS = False
DEFAULT_FROM_EMAIL = POSTMARK_SENDER
SERVER_EMAIL = POSTMARK_SENDER
Here is the (slightly modified) code which is supposed to be sending the email.
def sender(request, subject, template_name, context, to):
site = 'example.com'
context.update({'site_name': 'example',
'domain': 'example.com',
'protocol': 'https' if request.is_secure() else 'http'})
message = render_to_string(template_name, context)
from_email = "the.robot#example.com"
if len(to) > 1:
kwargs = {'bcc': to, }
else:
kwargs = {'to': to, }
email = EmailMessage(subject, message, from_email, **kwargs)
def send_activation_email(request, user):
subject = _("User activation")
template_name = 'spirit/user/activation_email.html'
token = UserActivationTokenGenerator().generate(user)
context = {'user_id': user.pk, 'token': token}
sender(request, subject, template_name, context, [user.email, ])
I also tried using gmail as a mail server, as suggested in this answer, and the same problem recurred. That is, mail gets sent perfectly fine from the local installation, but is apparently not sent by the Heroku version. Likewise, the command send_mail then still works on Heroku.

Django Login/Session Not Sticking Over HTTPS

I'm working on a Django site hosted on an Apache server with mod_wsgi.
The site is only on https as we have Apache redirect any http requests to https.
The project I'm working on is called Skittle.
I have a custom user model called SkittleUser which inherits from AbstractBaseUser and is set as the AUTH_USER_MODEL in our settings.py file.
os.environ['HTTPS'] = "on" is set in the wsgi.py file.
SESSION_COOKIE_SECURE = True and CSRF_COOKIE_SECURE = True are both set in settings.py
The issue that we are having right now is that logging in as a user is unreliable.
When you go to the login page, some times it works while other times it doesn't.
Then while browsing the site, you will suddenly lose your session and be kicked down to an anonymous user.
We are currently running our test site here if anybody wants to take a look:
https://skittle.newlinetechnicalinnovations.com/discover/
Our production site is at www.dnaskittle.com but does not yet incorporate user logins as the feature doesn't work.
A test user:
email: test#dnaskittle.com
password: asdf
If the login does not work, you will see in the top right "Welcome, Login" in which case, just try clicking on Login again and use the same credentials.
It may take 5-6 times of doing that process before you will actually get logged in.
You will know it works when you see "Welcome Tester, Logout, My Genomes"
After you are logged in, it may stick for a while, but browsing around to other pages will eventually kick you back off.
There is no consistent amount of pages that you can go through before this happens, and it doesn't happen on any specific page.
Any insights on this would be greatly appreciated.
Also of note, going to the Django admin page (which is not our code, but base django code) has the same issue.
I've gotten this issue sorted out now.
Users can not login while on HTTPS using while using the listed setup.
What I did:
In settings.py add:
SESSION_SAVE_EVERY_REQUEST = True
SESSION_COOKIE_NAME = 'DNASkittle'
I also wiped the current django_sessions database in case that was causing issues with old lingering data.
I did not setup extra middleware or SSLRedirect, and everything is working all ship shape.
It's little longer and complex the SSL system. to handle the session/login properly with https you can set a configuration with the session_cookies.
settings.py:
ENABLE_SSL=False #in the debug mode in the production passed it to True
MIDDLEWARE_CLASSES = (
'commerce.SSLMiddleware.SSLRedirect', #)
# the session here is to use in your views when a user is connected
SESSION_COKIE_NAME='sessionid'
#the module to store sessions data
SESSION_ENGINE='django.contrib.sessions.backends.db'
#age of cookie in seconds (default: 2 weeks)
SESSION_COOKIE_AGE=7776000 # the number of seconds in 90 days
#whether a user's session cookie expires when the web browser is closed
SESSION_EXPIRE_AT_BROWSER_CLOSE=False
#whether the session cookie should be secure (https:// only)
SESSION_COOKIE_SECURE=False
SSLMiddleware is a file you going to define in your project like.
SSLMiddleware.py:
from django.conf import settings
from django.http import HttpResponseRedirect, HttpResponsePermanentRedirect
SSL='SSL'
class SSLRedirect:
def process_view(self,request,view_func,view_args,view_kwargs):
if SSL in view_kwargs:
secure =view_kwargs[SSL]
del view_kwargs[SSL]
else:
secure=False
if not secure == self._is_secure(request):
return self._redirect(request,secure)
def _is_secure(self,request):
if request.is_secure():
return True
if 'HTTP_X_FORWARD_SSL' in request.META:
return request.META['HTTP_X_FORWARD_SSL'] == 'on'
return False
def _redirect(self,request,secure):
protocol = secure and "https" or "http"
newurl ="%s://%s%s" % (protocol, request, request.get_full_path())
if settings.DEBUG and request.method=="POST":
raise RuntimeError, \
return HttpResponsePermanentRedirect(newurl)
Now in your urls which should handle your logins or connection add the line
urls.py:
from project import settings
urlpatterns += patterns('django.contrib.auth.views',
(r'^login/$','login',{'template_name':'registration/login.html','SSL':settings.ENABLE_SSL},'login'),
Try to adapt this to your code. and don't forget to turn ENABLE_SSL to True
For users login with HTTPS, you have to enable SSL and use code that matches your case to use it. For the user session you can use this:
First check if you have in settings.py:
INSTALLED_APPS= ('django.contrib.sessions',)
and use the request.sessions in your file.py:
request.session['id']='the_id_to_store_in_browser' or 'other_thing'
Here you use request.session like a special SessionStore class which is similar to python dictionary.
In your views.py for example before rendering a template or redirecting test the cookie with the code:
if :
# whatever you want
if request.session.test_cookie_worked():
request.session.delete_test_cookie()
return HttpResponseRedirect(up-to-you)
else:
# whatever you want
request.session.set_test_cookie()
return what-you-want
with this code, the user session will stick a wide, depending on your SESSION_COOKIE_AGE period.