How can save the return path without HTTP_REFERRER? - django

I have a function based view that I only use to update a session:
def admin_privileges(request):
// toggle request.session['is_admin']
return
Typically I use this to toggle a session variable between True and False.
E.g. in a template:
Toggle admin privileges
How can I pass a variable and amend return in admin_privileges to return the user to the original view it was requested from?
I don't want to use anything on the front end, and I can't use HTTP_REFERRER as it's not always set.
I thought of passing something via the URL from the referring view?

There are 2 ways:
You can use request.META.get('HTTP_REFERER') in your view which will return previous page.
or (more safely, check this link to learn why)
You can pass the link (request.path for current page) as a parameter to admin_privileges link so:
Toggle admin privileges
In the view, you can get that parameter using request.GET and redirect using Django's redirect utilities.

Related

How do I check if a user has entered the URL from another website in Django?

I want an effect to be applied when a user is entering my website. So therefore I want to check for when a user is coming from outside my website so the effect isnt getting applied when the user is surfing through different urls inside the website, but only when the user is coming from outside my website
You can't really check for where a user has come from specifically. You can check if the user has just arrived on your site by setting a session variable when they load one of your pages. You can check for it before you set it, and if they don't have it, then they have just arrived and you can apply your effect. There's some good examples of how sessions work here: https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Sessions
There's a couple of ways to handle this. If you are using function based views, you can just create a separate util function and include it at the top of every page, eg,
utils.py
def first_visit(request):
"""returns the answer to the question 'first visit for session?'
make sure SESSION_EXPIRE_AT_BROWSER_CLOSE set to False in settings for persistance"""
if request.session['first_visit']:
#this is not the first session because the session variable is used.
return False
else:
#This is the first visit
...#do something
#set the session variable so you only do the above once
request.session[first_visit'] = True
return True
views.py
from utils.py import first_visit
def show_page(request):
first_visit = first_visit(request)
This approach gives you some control. For example, you may not want to run it on pages that require login, because you will already have run it on the login page.
Otherwise, the best approach depends on what will happen on the first visit. If you want just to update a template (eg, perhaps to show a message or run a script on th epage) you can use a context processor which gives you extra context for your templates. If you want to interrupt the request, perhaps to redirect it to a separate page, you can create a simple piece of middleware.
docs for middleware
docs for context processors
You may also be able to handle this entirely by javascript. This uses localStorage to store whether or not this is the user's first visit to the site and displays the loading area for 5 seconds if there is nothing in localStorage. You can include this in your base template so it runs on every page.
function showMain() {
document.getElementByID("loading").style.display = "none";
document.getElementByID("main").style.display = "block";
}
const secondVisit = localStorage.getItem("secondVisit");
if (!secondVisit) {
//show loading screen
document.getElementByID("loading").style.display = "block";
document.getElementByID("main").style.display = "none";
setTimeout(5000, showMain)
localStorage.setItem("secondVisit", "true" );
} else {
showMain()
}

Django Processing Form to other Form

I have a view that is an input form that people input their information in (name, address, that sort of thing). They will then click an "ok" button.
After people click "ok" I want them to be redirected to a page that has a table with their inputted information.
Any ideas on how to do this?
So far, I have the first view. When clicking OK all the information is stored in a database. I just don't know how to use it from there.
Note: ModelForms are used
If you look carefully the documentation : https://docs.djangoproject.com/en/dev/topics/forms/#processing-the-data-from-a-form
You could understand that, once you have treated (is_valid() - cleaned_data['']), you have to do a call to
render_to_response('template',{ 'name':name, 'last_name':last_name..}, context_instance=RequestContext(request))
And, in the template called, just make the data you need be shown, as usual..
you could try to pass your newly created object to the next view (which shows the new object) like this, the called view just has to accept your object as parameter.
# ... your form processing here
if form.is_valid():
# create and save your object code here
your_object.save()
return redirect('show_new_data_view', your_object=your_object)
Hope this helps.

Django want to use a variable from another view

I have a list of items in a view called client_items. I want to be able to use the variable items_list`which is another view called edit_order in client_items. So is there a way to call the variable from a different view? (Import a variable from another view and be able to use this variable in the other) I cannot just write it in client_items view because it needs an order_no augment.
Edit: here is my latest views. I have tried creating another views called items_in_edit_order. At this point I get `order_no not defined.
def items_in_edit_order(order_no):
order = models.Order.objects.get(pk = order_no)
return order
def client_items(request, client_id = 0):
client = models.Client.objects.get(pk = client_id)
items = client.storageitem_set.all()
order = items_in_edit_order(order_no)
return render_to_response('items.html', {'items':items, 'client':client, 'order':order}, context_instance = RequestContext(request))
Just adding, since no one has said this and it seems like you don't understand this yet:
Your client_items view must, somehow, have access to the order_no variable. If for some reason the value is not being passed along via the URL, it must get the value from somehwere. There are only three real locations where it could get this value:
Database: this will work if you are, for example, storing something like a cart which is directly linked to a user. So for example, you might be able to do something like order_no = Order.objects.filter(cart__user=request.user).order_no which would get the order associated with the user's current cart, then return the order_no value.
Session: you store the order_no in the session. This would assume you had an earlier view where the value for order_no was set, at which point you would save it using request.session['order_no']=order_no. Later, when you wanted to retrieve the value, you would simply use order_no=request.session['order_no'] in the view.
Cookie: not really recommended, but an option nonetheless. It's complicated because in the first view you'd have to create the response object (as in resp = render_to_response(template_name, locals(), RequestContext(request)) and then write a cookie to it resp.set_cookie("order_no", order_no). You retrieve it using request.COOKIES['order_no']
There are other, bizarre, places you could store the value: files, cache, other data storage formats, etc. Not at all recommended.
No. Write a function that returns the value you're interested in, and call it from both views.
What the guy said above is correct. You shouldn't attempt to "share" variables to different views.
However in the event you must or have a reason to then you could just store it in the session and then you have access to it in any view that has access to the "request".
Hope that helps.

Django, Pass QuerySet to url using redirect/redirect_to

How can I redirect from view to another url, passing my queryset to another view?
I tried this:
return simple.redirect_to(request, 'some_url', **{'queryset': results})
and this
return redirect('some_url', queryset=results )
but it does not work....
How can i do it?
Gabi.
How are you expecting this to work? Redirection happens by getting the browser to request another URL. Anything you want to pass as a parameter to the redirection must therefore go into the URL you're redirecting to. It simply doesn't make sense to put a queryset into a URL parameter.
Presumably you could pass whatever arguments you used to get the queryset in the first place, but that's a lot of extra work.
Do you really need to redirect at all? What about simply calling the new view from your original one, and returning its response?

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)