How do you pass or share variables between django views? - django

I'm kind of lost as to how to do this:
I have some chained select boxes, with one select box per view. Each choice should be saved so that a query is built up. At the end, the query should be run.
But how do you share state in django? I can pass from view to template, but not template to view and not view to view. Or I'm truly not sure how to do this. Please help!

Put the values to hold into the session.

There are many ways... in the view to template... put the variables in hidden fields in the forms. So when you "submit" in the subsequent forms... the values are then contained in the following request.POST.get().
Of course you can also store the various data elements in a DB table (disk or ram) between views... using the session_id as the key into the datastore. (not recommended for load balanced systems).
And my least favorite is cookies. (see the APIs for how to store in cookies)
UPDATE: Sorry there are no code examples here... the docs are pretty easy to read. There is also a djangosnippets website that you use to look up example code.

You can store such information in session as Ignacio Vazquez-Abrams said or use django-flash - (django-flash usage)

Related

Saving all user input data in Django simply?

This is may be an obvious question to a Django expert, but is there a way that I can save all user inputs (clicks through content without having to explicitly save every entry in a table). If this is possible, then how do I access it later?
If I have to create models, like this I can:
#(within a view function)
UserInputs.objects.get_or_create(user=request.user,
selection1=request.POST.get('selection1'),
id=request.POST.get('id')),
thumbs_up=request.POST.get('thumbs_up'),
thumbs_down=request.POST.get('thumbs_down'),
comments=request.POST.get('comments')
)
Is there an easier way to get it done? Because I have lots and lots of different user click inputs and specifying every one like this will really slow down my application.
Is this data by chance saved in one of the sessions tables? Or can we create a custom sessions table to do this?

How to I combine Page-views for a URL when they have different query strings in Google Analytics?

I am trying to do some reporting on page views on a site and the results are being listed like the following:
www.example.com/directory/ - 100 views
www.example.com/directory/?id=123456 - 10 views
www.example.com/directory/?id=987654 - 5 views
What filter do I need to create to views the results as:
www.example.com/directory/ - 100 views
www.example.com/directory/?id=* - 15 views
Thanks in advance
Yes, getting historical grouped together is going to mean using something like Google Docs, Excel, Tableau Software, Analytics Canvas, etc.
Moving forward...
One of the simplest ways of keeping things grouped in GA is to set up an advanced profile filter. You'll want to use this with a new profile; keeping a "raw" or "empty" profile is highly advisable for when you actually want to look at those individual URLs.
That said, here's a filter pattern that should work for you:
Go to Admin > Filters (under the View Column)
+ New Filter > Create new Filter > Name it
Filter Type = Custom filter > Advanced
Here's the pattern:
Field A: www\.example\.com\/directory\/\?id=.+
Output To: www\.example\.com\/directory\/\?id=\*
Another way to aggregate the same URI with multiple query strings is to change the primary dimension to 'Page Title' under Behavior > Site Content > All Pages.
The best way to do this for your historical data is unfortunately in an excel pivot table. You can get in in the UI, but only by creating a custom report and searching for very specific directories.
Check out the documentation on excluding query strings in your GA profile. Maybe create a new profile and write an advanced rule to rewrite all "id" pages to "/directory/product-page".
A totally different approach is to use custom variables or custom dimensions and to stop looking in the normal "Behavior" reports section (used to be called "Content" in GA) – custom dims are available using Google Analytics Universal Analytics only, which means starting a new web property and possibly running both code snippets concurrently (totally safe to do).
Personally I find custom dimensions a bit easier to work with than custom variables, and I generally think that it's a good idea to start exploring the new Google Analytics.
The nice thing about either of these approaches is that you can still keep the full page path date in the same profile as your custom dimension / variables information; it'll stay in the Behavior section where it belongs with all the other page paths.
Where I'm going with this...
You can create a new dimension such as "page type" and then call it "products", "posts", "articles", or whatever these id #s represent in this /directory/; then you can look at metrics across the dimension like pageviews, time on page, etc. by page type.
You can even create other dimensions to help describe them in more detail, such as breaking down blog posts or products into their different categories; i.e. hierarchical dimensions. Once you start using this kind of thing you may wonder what you ever did without it!
I think it's fair that I stop this answer now since it's not about how to set up custom variables or custom dimensions; those links should get you started (it's really not difficult).
Note: You can use php to fill in the dimension information in the GA tracking snippet dynamically based on the page that is being viewed (again, that's another question).

Django Registration and content from other views

My situation is as follows.
I have a django app that is a CMS, and this one app generates page content and menus.
There is 'default' view that generates all the page content. One of the fields of the main model is designed to limit the visibility of pages depending on the setting:
'internal' (limited to users on our network),
'worldwide' (viewable by the www) and now, I would like to add an extra value
'secure', which would limit viewing only to those who are logged in to the site.
I dont think #login_required would work, as it only works on whole functions.
We want the author or editor to be able to set this flag, rather than code a special function; and there will be instances where a page migrates from 'internal' to 'secure' then to 'worldwide' - so ideally the urls should stay the same.
What is the best way to go about this?
thanks in advance... patrick
As you want the flag set on your object, I'm assuming that flag can't be read until you're already within the view (i.e. you won't be storing it in something accessible by the request object, like a session), so that precludes custom decorators. You could choose to go with something a bit crude but workable like this:
if (val=="internal" and inrange(request.META['REMOTE_ADDR'])) or (val=="secure" and request.user.is_authenticated()) or val=="worldwide":
return render_to_response .... etc.
else:
return HttpResponseForbidden()
Substituting your model values, and writing the inrange function, naturally.
The more sophisticated approach, though, would be to write custom middleware and use the process_view() function. See the docs for more details.

Django: calling DB queries from a template

I've got a Django site that has a sidebar with a variety of different boxes that could go in it depending on the page. For example, "Most recent comments" or "Latest tweets" or "Featured story." These boxes all require database queries to run.
I could simply add a most_recent_comments and whatever other variable are needed to the View for each page. But this feels brittle. I'd like to be able to move and change boxes just by editing the templates.
So my other thought was I could add all the variables that all the boxes might need to every page with a Context Processor, but is the ORM smart enough to only run the queries for pages that actually use those variables? Or is it going to hit the database even if I have no boxes on a page?
So what I think I want is some kind of custom tag where I could just say {% most_recent_comments_box %} and it would be smart enough to load whatever variables it needs from the database and then call a little template file. Is this the right approach? How do I accomplish that?
This is the use case for custom template tags. Read this article (written by one of the people behind Django).
One addition to Django since that article was written is the inclusion tag shortcut, which implements the "call a little template file" approach you mention.
So my other thought was I could add all the variables that all the boxes might need to every page with a Context Processor, but is the ORM smart enough to only run the queries for pages that actually use those variables? Or is it going to hit the database even if I have no boxes on a page?
Yes, the ORM will be smart enough to do that. Django QuerySets are lazy: https://docs.djangoproject.com/en/dev/topics/db/queries/#querysets-are-lazy

How to select from a large number of options when completing a form

I am building a web app that allows our field staff to create appointments. This involves creating a record that contains many foreign keys, of which some come from very large tables. For example, the staff will need to select one of potentially thousands of customers.
What's the best way of doing this in Django?
A pop-up box that allows the users to search for customers, gives them the results, the user selects the results, then fills out the main appointment form and then
disappears?
Changing the appointments form to a customer selection page that
then reloads the appointments page with the data in a hidden form? Or
holding the data in some session variables?
Some from of Ajax approach.
A wizard where the flow is: a customer search page, a list of results and they select from results, then a search page for the next option (for example product selection), etc etc
(I'd like to keep it as simple as possible. This is my first Django
project and my first web project for more years than I care to
remember)
ALJ
Imho you should consider some kind of autocomplete fields. I think this results in the best usability for the user. Unfortunately, this always involves Ajax. But if you think that all users have JS turned on this is no problem.
E.g.
django-autocomplete
or what is probably more powerful:
django-ajax-selects
If you do the wizard approach, it will take longer for the user to accomplish the task and makes it harder to change selections.
Edit:
Well with django-ajax-selects you can define how the results should look like. So you can e.g. add the address behind the name.
Quote:
Custom search channels can be written when you need to do a more complex search, check the user's permissions, format the results differently or customize the sort order of the results.
I have done this before by integrating a jQuery autocomplete plugin. But, seeing as this is your first project and your desire to keep it simple, I suppose you could go with the session data option. For instance, you could show a search page where users could search for and select a customer. You could then store the, say, ID of the selected customer object as session data, and use it to pre-populate the corresponding field in the form when displaying the form. That's what I think offhand.