how to use django object in session - django

I was wondering how i can check if a object is in session and depending on that, do something.
def login_character(request, character_name):
request.session['character'] = Character.objects.get(name=character_name)
return HttpResponseRedirect(reverse('index'))
some other function:
if request.session['character']:
print request.session['character'].name
else:
print "nothing to see here"
How i try it, i kepe getting back to a KeyError

session uses the standard Python dictionary interface, so you want either:
if 'character' in request.session:
print request.session['character'].name
else:
print "nothing to see here"
Or, in some cases, request.session.get('character') if you just want to have a default value if the key is not present.

Related

How to set the incoming object to true or false in Django

What I want to do is write "True" if there is data suitable for the filters made, otherwise "False"
if ChartSimilar.objects.get(chart=pk, year=year):
print('True')
else:
print('False')
charts.models.DoesNotExist: ChartSimilar matching query does not exist. I get an error
Here the got query does not exist because the object is not available with a particular id so it's an exception. You can handle it by using try, except block.
try:
ChartSimilar.objects.get(chart=pk, year=year)
print('True')
except:
print('False')

How to print out request.body data in django?

Just working through the Django tutorials and playing around with stuff. Was going through the HttpResponse and HttpRequest docs and I'm just trying to print out data to see how things work.
However, when I try to print to console the request.body I get nothing back.
def detail(request, question_id):
current_question_selected = Question.objects.get(pk=question_id)
choices_for_question = current_question_selected.choice_set.all()
context = {"choices_for_question":choices_for_question, "current_question_selected":current_question_selected}
#print(request.META["REMOTE_USER"])
print(request.body)
return render(request, 'polls/detailtext.html', context)
This is what gets pritned to the screen, the letter 'b' with an empty string
[28/Jun/2022 10:59:56] "GET /polls/1/ HTTP/1.1" 200 456
b''
Not sure what i'm missing
The print displays an empty string because GET does not accept a body. Taken directly from the Mozilla Web APIs docs:
Note that a request using the GET or HEAD method cannot have a body and null is return in these cases.
If you want to pass data in a GET request, you need to pass them as parameters instead. Then, you can access the parameters using request.GET (HttpRequest.GET) or access them individually with request.GET.get('key').

chnage value outside of function without returning a value - python

I have an attribute named session that is set to 1. In changeSession() I am trying to change its value to 2. In the last step session is printed and it is still 1. You can see the the code below. Doing the following would make us print the value 2:
session=changeSession()
let changeSession() return the new session value.
However, is it possible to get the value 2 printed without letting changeSession() return anything?
The code:
session=1
def set_session(s):
session=s
def changeSession():
set_session(2)
changeSession()
print session
To do that just use global session in set_session to indicate to python that you want to use the session that you defined outside of the function scope. If you want to document yourself about this behavior, it is called variable scope. Here is the fixed code :
session=1
def set_session(s):
global session
session=s
def changeSession():
set_session(2)
changeSession()
print session

Testing a session variable

I came across Django request.session; I know how to set and test it for a specific value.
request.session['name'] = "dummy"
and somewhere I check
if request.session['name'] == "dummy" :
#do something
But, now I have to check whether the session variable was even set in the first place? I mean how can I check whether there exists a value in the request.session['name'] is set?
Is there a way to check it?
Treat it as a Python dictionary:
if 'name' in request.session:
print request.session['name']
How to use sessions: Django documentation: How to use sessions
get will do all the work for you. Check if the key exists, if not then the value is None
if request.session.get('name', None) == "dummy":
print 'name is = dummy'
Another way of doing this is put it in try.
In this the third example code snippet
if you apply del operation in a session variable it which does not exist, so it throws KeyError.
so check it like this.
try:
print(request.session['name'])
except KeyError:
print('name variable is not set')

django redirect to calling view after processing function

I have written a function having the following signature:
def action_handler(request, model):
This action_handler is used from different views and handles the actions for this views. One example is deleting objects. In this example the user selectes some objects, selects the delete action and then the user is presented a page to check whether he/she wants to really delete the selected objects. This is done by the following code:
context = {
'action_name' : selected_action,
'object_list' : object_list,
}
return render_to_response("crm/object_delete_check.html", context,
context_instance=RequestContext(request))
For the case that something goes wrong I want to redirect the user to the view from where the user called the action.
Thus I want to ask here whether it is possible to get the calling view from the request object or somewhere else from.
If the def "def action_handler(request, model):" is called from the view "contacts(request):" then i want to redirect the user to the view "contacts(request):" .
But the clue is I do not want to hard-code it since the def action_handler is called from different views. Using a simple "return" is also not possible, since I want to recall the view completely.
if goback: #goback being whatever criteria means "something went wrong"
default_back_url = "someurl_in_case_the_meta_is_messed_up"
back = request.META.get('HTTP_REFERER',default_back_url) #yeah they spelled referrer wrong
if back:
return HttpResponseRedirect(back)
else:
return HttpResponseRedirect(default_back_url)
while META can be faked, it's harder to fake than GET query strings.
You can pass previous page url through GET parameter:
/object_delete_check/?previous=/contacts/
(see contrib.auth.decorators.login_required for example)