Django passing parameter from views hangs server - django

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.

Related

How to redirect users to a mobile app in Django view?

I have a Django web application and I'm trying to redirect users to my mobile app in one of the views.
def magic_link(request, token):
return redirect(f"{settings.FRONTEND_URL}/magic_link/{token}")
This redirect link is like: appname://magic_link/token. However, I'm getting the following error.
DisallowedRedirect at /magic_link/{token}/
Unsafe redirect to URL with protocol 'appname'
How can I fix this issue and redirect users to the mobile app in Django view?
You should create your own HttpResponsePermanentRedirect which inherits from HttpResponsePermanentRedirect by django. In your own class, you add your app scheme to the allow_schemes (something relevant, i can't remember so well)
to let django know your app scheme is valid.
Example:
class HttpResponsePermanentRedirect(HttpResponsePermanentRedirect by django):
allow_schemes=['your_app_scheme',...]

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

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

How to authenticate a Django session using captcha?

I have built a website, and a captcha. The captcha is generated by models and displayed on a template.
Views
from resumesite.models import Chess_board
import json
def home(request):
return render(request, 'home.html', {})
def chess(request):
board = Chess_board()
data = mark_safe(json.dumps(board.rep))
return render(request, 'captcha_original.html',{'board': data})
I would like to redirect all requests to the captcha, and on completion of the captcha redirect to website and allow full access for duration of the session (i.e. for period of 20 minutes). How would you suggest going about this?
Options
Middleware/decorator authenticating by ip address (I have read this won't work if user is using a proxy)
Custom login form, with decorator #login_required(login_url="/chess/")
Integrating with REST and using token authentication
You would have to use a server-side session to handle the access. By using the server-side session you can set an expiry. In the session store, a variable called access=True, which you can check in the other function if it exists and serve pages. After the expiry time hits, this session is deleted and function will see a None value.
For more information read following docs
https://docs.djangoproject.com/en/3.0/topics/http/sessions/#configuring-the-session-engine

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!