Server Error (500) after deploy Django app on heroku - django

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).

Related

Session variable in one route exists, and in other is None

Currently I'm working on a project where I'm using React as frontend and Django as backend. In react i created a login page, where I through axios send files to django, and in this route index i sent all the information from the login page, and define a session variable reqeuset.session['id']=150 in it. But when i call reqeust.session['id'] in a diffrent route, it says that it is type None.
This is the code:
#api_view(['POST'])
def index(request):
data=request.data.get('data')
korisnik = Korisnik.objects.filter(korisnicko_ime=data.get('user'),
if korisnik.exists():
korisnik_json=serializers.serialize('json',korisnik)
request.session['id']=150
print(request.session['id'])
# if not request.session.session_key:
# request.session.create()
return HttpResponse(korisnik_json)
else: return HttpResponse(status=404)
#api_view(['GET'])
def korisnik(request,id):
print(request.session.get('id'))
korisnik=Korisnik.objects.filter(pk=id)
korisnik_json=serializers.serialize('json',korisnik)
return HttpResponse(korisnik_json)
This is the output from python console
Image
Also note, I'm using django restframework. Did anyone, have this problem before, any help is appreciated.
I had faced a similar issue. Please check my answer here.
React Django REST framework session is not persisting/working

Get token from URL in Django. TDAmeritrade API Call

Ok,
I'm developing a website where I'm using Django. The website is for creating and keep track of stock portfolios. I have the database and the basics of the website set up but I would like to use the TDAmeritrade API in order to get the stock information. How it works is the user is redirected to TD where they enter there Login and Password they accept the terms and get transferred to a redirect page of the local host (until it goes live). Which looks a little like this
"https://127.0.0.1:8000/?code=" with a huge code after the equals sign.
Finally, how would one create the URL destination in Django url.py file and store the code for AUTH Token
I've tried something like this: path('?code=', test_view, name='test'),
but had no luck but that could be because of this error (You're accessing the development server over HTTPS, but it only supports HTTP.)
Thanks in advance!
Side note: I've tried looking up how Paypal does there send back confirmation but all I could find were packages Pre-build for Django
I figured out the solution with the help of Moha369 in the comments, So shout out to him/her!
def home_view(request):
context= {}
user = request.user
if user.is_authenticated:
token = request.GET.get('code')
print(token)
return render(request, "home.html", context)
Django Docs that helped

Django passing parameter from views hangs server

I try to make simple web site with django, Oracle DB and django web server. And when I make query to db in django shell:
mylist=person.objects.filter(name='Anon')
everything works fine. Same when I use in views simple render
def index(request):
return render(request, 'sos/index.html', {})
I get basic site. But when I try to pass parameters from query:
def index(request):
mylist=person.objects.filter(name='Anon')
return render(request, 'sos/index.html', {'mylist': mylist})
server hangs - no matter which browser I use, website is still connectig - only I can do is ctrl+C.

Django Session KeyError when key exists

The following code works locally when I use Django's development server, but I am running into intermittent bugs in production with Nginx and Gunicorn.
views.py
def first_view(request):
if request.method == "POST":
# not using a django form in the template, so need to parse the request POST
# create a dictionary with only strings as values
new_post = {key:val for key,val in request.POST.items() if key != 'csrfmiddlewaretoken'}
request.session['new_post'] = new_mappings # save for use within next view
# more logic here (nothing involving views)
return redirect('second_view')
def second_view(request):
if request.method == 'POST':
new_post = request.session['new_post']
# ... more code below
# render template with form that will eventually post to this view
I will sometimes receive a KeyError after posting to the second view. Based on the documentation on when sessions are saved, it seems like the session variable should be saved since it is modifying the session directly. Also, if I take the sessionid provided the error page's debug panel and access the session via Django's API, I can see the 'new_post' session variable
python manage.py shell
>>> from django.contrib.sessions.backends.db import SessionStore
>>> s = SessionStore(session_key='sessionid_from_debug_panel')
>>> s['new_post']
# dictionary with expected post items
Is there something I'm missing? Thanks in advance for your help!
Ok, I finally figured out the issue.
By default Django uses cached sessions when you create a new project using django-admin startproject project_name_here
In the documentation it warns that caching should only be used in production if using the Memcached cache backend since the local-memory cache backend is NOT multi-process safe. https://docs.djangoproject.com/en/1.11/topics/http/sessions/#using-cached-sessions
The documentation also cautions against local memory caching in the deployment checklist: https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/#caches
I changed the SESSION_ENGINE in settings.py to 'django.contrib.sessions.backends.db' and the error went away. https://docs.djangoproject.com/en/1.11/ref/settings/#session-engine
Hope this is helpful to someone else!

How to test Django error reporting

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.