Django - passing user related information to many views - python

I would like to view some user information on over half of my website's views.
This information should contain not only trivial username but also some fields from other tables of my project that are associated with current user.
I would also like to put this information into the template that my current view extends, just to keep it DRY.
I already did some research and coded some templatetags hoping that registering tags would help me achieve this but I have no idea how to get user information when there's no request like in views' functions.
Any tips on how to achieve this will be much appreciated. I just started django yesterday and am still a bit confused by it's philosophy.

You can use a context processor to add data to the template context in a DRY way.
In a nutshell, a context processor is simply a function that accepts a request as its first argument, does some additional processing that you add and augments the context with whatever values you want.
You can query an objects models, add the current datetime...pretty much anything you can do with Python or Django can go into a context processor.

Related

User defined template Django

Is there a way to enable application users to create their own template within the django app? One example would be how MailChimp enables users to create their own custom email template.
Currently i'm thinking of creating a model that captures information the user wants to display. that model can point to a template and populate it with the information the user wants to display. But is there a better way?
As stated in the docs:
Warning
The template system isn’t safe against untrusted template authors. For example, a site shouldn’t allow its users to provide their own templates, since template authors can do things like perform XSS attacks and access properties of template variables that may contain sensitive information.
Having a user define templates, even if the templates are stored in a model, can lead to xss vulnerabilities, and will be extremely difficult to implement safely.
Another answered noted a warning from the docs that included:
access properties of template variables that may contain sensitive information
This is a big concern. All Django tables are linked together, often in "magical" ways. The template system does not concern itself with permissions granted to authenticated users. If a template can be processed then it will process anything & everything that it can - i.e., if a link between tables exists, it will follow it. This means that something like a Customer record that is linked to a User record that is linked to Vendor records to Item records, etc. could allow any user (or at least, any user with permission to create a template) to view almost any data in the system. They would not, at least with the standard User package, be able to see User passwords. But they could get to almost anything else. For example, they might be able to figure out who else is using the system, how much people are paying, names of administrators (very useful for phishing!), etc.
So while it would be relatively easy to create a user-defined Django template system, it is not a good idea, at least not on any publicly accessible system.

Django pure controller functions

I am wondering on how to implement pure controller functions in a Django's' "biased" MVC scheme. Let me explain it on an example.
Let's say I have a model of an Invoice, which has some attributes (say net, gross etc.). I can present it to the user using a view + template. And that's fine and easy.
But now, I want to send this invoice to a client. This is a more complicated thing, inluding more models (i.e. create an addressed Package model, get a number and let's say few other thing including creating and modifying not only Invoice model itself, but also creating and updating few other model types and instances.
I want this "action" to be available in multiple places of my web application, so going by the book I need to create a view with those actions implemented and bind it to some URL. Probably it should be implemented in POST action.
My questions are:
What kind of generic view should it be (just View? DetailView? other?).
Where should this View redirect after succesfull "send"? The simplest answer would be to redirect to the same referring page, but is this a correct way?
What if I want this "action" to be ran in background (say, send all unsend invoices at midnight) using celery or such? Of course I can make this a celery task and call it in a view. But is this clean django'ish solution? Where do you store such pure business methods in an app/project?

Django modelform: Create new related object

I've been searching stack overflow and google for a solution for over an hour now, and I can't seem to find something that, in my opinion, should be easy to obtain (as it's a common use case).
I've checked this thread, and a few others, but I haven't been able to find a real, easy solution:
Django modelform: is inline adding related model possible?
Anyway, say I have a model with three related entities, two foreign keys and a many-to-many related class. Now, I have a ModelForm which displays these in comboboxes and lists, but what I need is that "+" button next to these elements (as seen in the admin interface).
I want the plus to take me to a new form, for that particular entity, allow me to submit the new information, create the database entry, take me back to my original form and have the newly added entity selected in the combobox. I'm really hoping the django ModelForm Meta class has an attribute that I can't seem to find which enables exactly this.
This isn't really a django question.
This has to do with presentation of a particular widget in an html document, and that is governed by either the HTML markup, CSS, or javascript.
Django is a server side application and is primarily responsible for creating a valid http response and receiving a valid http request (of course, there is a lot that happens in the interim and that is why django is so big) but it's not a "one toolkit to kill them all" app.
I think you want to look at bootstrap: http://getbootstrap.com/
Jquery UI: http://jqueryui.com/
Or some combination of the two.
You can also just mark up the document yourself with a stock img or something.
However, if you want to do it exactly how the admin does it, just go into django.contrib.admin and examin the code to figure out how the django developers did it. I believe they are just using Jquery UI and some manual markup to accomplish that.

Python - Django - How to handle a multiple page form correctly

I have an application that is used to store vehicle information. I created a Vehicle Model which has many foreign keys including a Consumption Model, Capacity Model, Tires Model, Fuel Model etc.
Multiple Page Form:
When a user wants to add a vehicle to the inventory I wanted to use a multiple page form to break up the steps. So, for example, the first step would be the Vehicle modelform and the second step would be the Fuel modelform. The problem I am running into is storing modelforms over multiple pages without using formwizard.
My Thoughts:
There seems to be no information on how to do this, am I the only one who wants to do this or is the solution blatantly obvious? In other languages I would have stored all the forms in a session and saved them at the end of the process. It seems you can't store a modelform in a session because I get a pickling error (unless I serialize it perhaps?) so I assume that is a no-no. I could save the modelform of a given page to the database before going to the next step but that has multiple issues. i.e. what if the user stops halfway through?
Any explanation on the normal way this is done, or if it is ok to serialize modelforms would be greatly appreciated.
You are looking for the form wizard:
Django comes with an optional “form wizard” application that splits forms across multiple Web pages. It maintains state in hashed HTML fields so that the full server-side processing can be delayed until the submission of the final form.
You might want to use this if you have
a lengthy form that would be too
unwieldy for display on a single page.
The first page might ask the user for
core information, the second page
might ask for less important
information, etc.
More details in the docs.

Rendering common session information in every view

I'd like to output some information that depends on session data in Django. Let's take a "Login" / "Logged in as | Logout" fragment for example. It depends on my request.session['user'].
Of course I can put a user object in the context every time I render a page and then switch on {% if user %}, but that seems to break DRY idea - I would have to add user to every context in every view.
How can I extract a fragment like that and make it more common?
Use template inheritance to derive all of your templates from a common base that suitably uses the common parts of the context, and make all your contexts with a factory function that ensures the insertion in them of those common parts.
Are you trying to make certain areas of your site only accessible when logged on? Or certain areas of a particular page?
If you want to block off access to a whole URL you can use the #login_required decorator in your functions in your view to block certain access. Also, you can use includes to keep the common parts of your site that require user login in a separate html that gets included, that way you're only writing your if statements once.
You may want to use a context processor that includes logic and place it into a variable you can use in any of your pages without adding it to each call.
See more info at How to pass common dictionary data to every page in django

Categories

Resources