How to fill data in a base html file Django - python

I have a base html file (for which code shouldn't be necessary) that requires some tags in the menu to be filled with id numbers (which are dynamic, and can't be hard coded). It seems to me that writing code to populate the tags for each view violates the DRY principle, and as such there should be some way to provide variables to a base html document. How does one do this, if it's possible?

You have two options:
Custom template tag
Custom context processor
Which way to use depends on your specific needs.

Yes. You need to use Context Processor. Google "django context procoessor" it'll come up with many results.

Related

Django - Managing page content in Django Admin

I'm new to working with Django and am developing for a client who wants to be able to change page content in the Django Admin. They need to be able to change the html of the index page without editing the files on the server.
I know about flatfiles but I'm not sure that's completely what I'm after as I can't display stuff such as Django forms for example.
EDIT: Kind of like how a CMS works but without the users/group stuff and be able to use Django View modules such as forms.
Any advice?
Thanks
Honestly, the scope of what you're looking for is too huge to cover in this format. There's a number of ways this could be done, but they're all going to require some work and customization based on the client's needs.
Flatpages could work if you allow HTML content and make sure the content is rendered as "safe" in the template. This really only covers the "content" area of the site, though. It wouldn't be wise to use flatpages for an entire site template, including header, sidebar, footer, etc.
You could create editable areas. So, you actually create models for things like headers, sidebars, footers, and modules within those areas, and then just pull them into the template as needed. Then, the client is only editing pieces of the template instead of responsible for the whole HTML document.
Forms are going to be a challenge, because they require backend-processing that requires a connected view. The client won't be able to just arbitrarily drop in some form code and have a form. But, you could use a third-party service form forms and just embed them in the available content regions. Or, there's a couple of django apps that try to implement a type of "form builder" in the admin. That might somehow let the client add a form via something like the shortcodes used in Wordpress, but you'd likely have to lay down some infrastructure to make that work.
At a certain point, stuff like this reaches a point of diminishing returns, though. The only way to allow total customization of the template is to drop down into the actual physical file and make changes there. You can make certain things easier for the client, but ultimately, they either need to scale back their customization needs or deal with the fact that they'll have to work with the filesystem.
I don't believe that is possible at this time. Of course you can edit your models but templates, I think not.
I would find out how much they need to change? If they plan a complete redesign every week then you're still looking for an answer. If they just need a dynamic front page then you can split it up into variables and let them edit sections of html. Much safer and less prone to breaking the html.

Cleanest design pattern for displaying form data and validation errors?

In real-life applications, if I use a form framework, I inevitably end up fighting it at some point.
I'm interested in best practice patterns for building forms in a website. Reference to implementations in any language would be a bonus (I usually work in Python). I'm particularly interested in the problem of creating / displaying the forms to the end user.
Here's how I see the subject. Most parts of the form workflow can be handled with relatively lightweight components that I can pull out of frameworks like formencode and formish. By "most parts" I mean decoding submitted form data into a sensible data structure (e.g. repeated fields in the form should become lists in Python); marshalling the values into the types that we want (e.g. an "age" field should become an integer); and validating the values (e.g. "age must not be blank").
The bit I end up fighting is making and displaying the forms themselves. Many frameworks (e.g. FormAlchemy) tightly couple their schemas, validation and models to some kind of form widget generation scheme, which I don't like.
The tasks involved in making a form are:
Making dynamic widgets (e.g. a select list with values from a database)
Looping over repeating fieldsets (e.g. a list of name, age pairs that each represent a person)
Embedding existing values in the form fields (from a data structure)
Displaying validation errors next to form fields or at the top of the page
The options I see for doing this are:
generate, based on widgets that are defined in the schema (e.g. Django)
post-process forms, by applying a data structure containing errors and values to an HTML template (e.g. htmlfill)
accept that for all but the simplest cases, you may as well start from the beginning by encoding the logic (loops, error display, etc) manually in each of your form templates
Are there any other patterns for handling the problem? What are the pros and cons of each?
The frameworks (Python) I've looked at / had pointed out so far are: flatland, formencode, FormAlchemy, formish, WTForms, Django forms, web2py, deform, FormConvert and web.py
Update: I've not really got very far with answering the question about best practise for building forms, but I've made the decision with my current project to go for deform / colander, which is a sane way of handling serialisation etc, but more importantly is well-documented and well-tested. I am going to avoid form generation at all for all but the simplest forms.
You can try django. It has forms module, that provides many useful mechanisms for web forms.
There's also web.py's Form class which you may find interesting. There are examples in its cookbook.
You might check out web2py, which provides several mechanisms for generating and processing forms (see also form-related Javascript and Ajax functionality). Its form objects (and other HTML helper objects) are server-side representations of the HTML DOM and can be manipulated prior to serialization into HTML (see ref1, ref2, ref3, ref4). If you have further questions about it, ask on the mailing list.
I have recently used flatland to handle a complex form and found it to be very flexible. There's no widgets library, but it has a powerful HTML generator/filter, and as pointed out in the documentation, it's quite simple to write your own widgets. Don't let the "0.0.2" version fool you, the library is quite mature and stable.
A panel featuring several form library authors was presented at PyCon 2010, which might be relevant to your question:
http://www.pycon.tv/video/184/
have you seen Bruno's django-floppyforms? It doesn't answer your question but it's worth being aware of it being done.

Can a python view template be made to be 'safe/secure' if I make it user editable?

Say I need to have a templating system where a user can edit it online using an online editor.
So they can put if tags, looping tags etc., but ONLY for specific objects that I want to inject into the template.
Can this be made to be safe from security issues?
i.e. them somehow outputing sql connection string information or scripting things outside of the allowable tags and injected objects.
Yes, use a template engine that has sandboxing features, like jinja2

How to implement Symfony Partials or Components in Django?

I've been developing in the Symfony framework for quite a time, but now I have to work with Django and I'm having problems with doing something like a "component" or "partial" in Symfony.
That said, here is my goal:
I have a webpage with lots of small widgets, all these need their logic - located in a "views.py" I guess. But, how do I tell Django to call all this logic and render it all as one webpage?
It sounds like what you're looking for is something like custom template tags...
You can write your own set of tags that process custom logic and return template chunks that are reusable in a very widget-like way.
Assuming you are going to be using the components in different places on different pages I would suggest trying {% include "foo.html" %}. One of the (several) downsides of the Django templating language is that there is no concept of macros, so you need to be very consistent in the names of values in the context you pass to your main template so that the included template finds things it's looking for.
Alternatively, in the view you can invoke the template engine for each component and save the result in a value passed in the context. Then in the main template simply use the value in the context.
I'm not fond of either of these approaches. The more complex your template needs become the more you may want to look at Jinja2. (And, no, I don't buy the Django Party Line about 'template designers' -- never saw one in my life.)

cascading forms in Django/else using any Pythonic framework

Can anyone point to an example written in Python (django preferred) with ajax for cascading forms? Cascading Forms is basically forms whose field values change if and when another field value changes. Example Choose Country, and then States will change...
This is (mostly) front-end stuff.
As you may have noticed Django attempts to leave all the AJAX stuff up to you, so I don't think you'll find anything built in to do this.
However, using JS (which is what you'll have to do in order to do this without submitting a billion forms manually), you could easily have a django-base view your JS could communicate with:
def get_states(request, country):
# work out which states are available
#import simplesjon as sj
return sj....
Then bind your AJAX request to the onchange event of the select (I can't remember if that's right for select boxes) and populate the next field based on the return of the JSON query.
10 minute job with jquery and simplejson.
I would also suggest considering getting a mapping of all data once instead of requesting subfield values one by one. Unless the subfield choices change frequently (states/cities change?) or huge in numbers (>1000) this should offer best performance and it is less complex.
You don't even need to create a seperate view, just include a chunk of JavaScript (a JSON mapping more precisely) with your response containing the form.

Categories