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
Related
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
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!
All is in my title. I would like to get the current user information because i need it in my view to display action (delete/edit) depending of the user's rights.
I use the basic authentification make by Django (/login /logout), i didn't change anything. Is there a way to listen to this login/logout action and retrieve this information in the Angular context?
Pretty new in angular, i'm searching some informations that would help me to go in one or other direction.
Actually i don't have a REST API for authenticated my users.
I find some interesting article Best place/way to store 'global' data such as 'current logged in user' / How do I store a current user context in Angular? but for now as i said i don't have AuthService just the basic login/logout from Django.
I used Django Rest framework for some action on my project (like post/delete/read/update for some of my models) and it works fine with angularjs. But i'm happy with the basic authentification provided by Django, so i don't want to rewrite it. But i don't know how to listen on it and if it's possible.
I know that is a broad question and for now i dont't have code to show because afters hours of research i don't know where i need to begin.
If it's to broad i will remove it.
Thanks,
OK, you can do something like that
Example (someUrl is url to your function in view.py):
In angular controller add $http
$http({method: 'POST', url: '/someUrl'}).
success(function(data){
//process aswer
});
In djnago view.py:
from django.shortcuts import HttpResponse
import json
def check_login(request):
if request.user.is_authenticated():
return HttpResponse(json.dumps({'result': {'logged': True}, 'user': request.user.username}),
content_type="application/json")
else:
return HttpResponse(json.dumps({'result': {'logged': False}}),
content_type="application/json")
Thanks In Advance.
I am facing an Issue in one of my Django Website. Here an authenticated user can access the Registration Page. But the client raised it as an issue. So I have tried to rectify that Issue and ended up with the following Solution.
Is it a good solution? Or how can I make it good?
The Process should be like this, when a loginned user try to access the Registration Page, he should be automatically Logged Out from the Site and then redirected to the Registration Page.
My code is
def user_signup(request, template_name='profiles/profile_register_form.html'):
if request.user.is_authenticated():
return custom_logout(request, next_page = "/accounts/register/")
def custom_logout(request, next_page='/'):
try:
language = request.session['django_language']
except:
language = False
response = logout(request, next_page=next_page)
if language:
request.session['django_language'] = language
return response
if i understood your question then
why custom_logout
you can call directly django logout like
if request.user.is_authenticated():
logout(request)
return HttpResponseRedirect('/login/') # whatever you register page
Your method was correct. It will save the current language session and will do the exact process you need
I have a django server app that communicates with a gwt front-end using JSON. I want to introduce user authentication to the app and have started to incorporate the framework provided by django. At this point I have set up the server to respond with the user authentication form when necessary (using the #login_required decorator scheme described in the above link), but I'm not sure what to do with this in GWT.
If you are using GWT with django and have implemented user auth, it would be great to hear how you set things up.
Thanks.
The autotest project used gwt and django combination. Have a look at http://autotest.kernel.org/browser/trunk/frontend source code. To be specific I would modify http://autotest.kernel.org/browser/trunk/frontend/afe/json_rpc/serviceHandler.py and add something like below (which would filter login, logout and is__logged__in and for all other functions it would invoke request.user.is_authenticated() to make sure that all other json rpc are protected)
def invokeServiceEndpoint(self, meth, request, response, args):
if meth.func_name == "login" or meth.func_name == "logout" or meth.func_name == "is_loggedin":
return meth(request, *args)
else:
if request.user.is_authenticated():
return meth(request.user, *args)
else:
from studio.rpc_exceptions import AccessDeniedException
raise AccessDeniedException()
I never used Django, but you probably can set what will be returned when login is required.
You can, for instance, return a message so the client can prompt the user with the authentication form. Of course, you would need to account for this situation in every call, but then you could create a abstract request class to do this.