Saturday, February 5, 2011

Re: Pythonish approach to widgets

On Saturday, February 05, 2011 07:02:17 am Alex Polovjan wrote:

> Hi list,

>

>

> Django.forms have a great system of widgets. But customizing them can

> be a pain. Writing complex html in the python code is write-only and

> error-prone approach.

>

> I know that js files can be included in admin:

>

> class ModelAdmin(admin.ModelAdmin):

> class Media:

> css = {

> 'all':('/static/admin/mywidget.css', )

> }

> js = [

> "/static/admin/mywidget.js"

> ]

>

> What are best practices to separate html from python code?

you can use the Media class in your widgets also [1] or you can include the css/js in the html.

In the case of adding them to your html template:

# base.html

<html>

<head>

<link rel="stylesheet" type="text/css" href="sitewidestyles.css" >

{% block css %}{% endblock %}

<script type="text/javascript" src="/path/to/jquery.js" />

{% block javascript %}{% endblock %}

</head>

<body>

{% block main_content %}

{% endblock %}

</body>

</html>

# template with form

{% extends "base.html" %}

{% block css %}

<link rel"stylesheet" type="text/css" href="formstyles.css" >

{% endblock %}

{% block javascript %}

<script type="text/javascript" src="/path/to/forms.js" />

{% endblock %}

{% block main_content %}

<form action="" method="post">

{{ form.as_p }}

<input type="submit" value="Submit" />

</form>

{% endblock %}

### end of page.

I prefer this style as it completely decouples the form html and styles from the business logic of the forms. You can get even deeper with the form fields in the html[2]. This is just a simplistic idea to get you started.

[1] http://docs.djangoproject.com/en/1.2/topics/forms/media/

[2] http://docs.djangoproject.com/en/1.2/topics/forms/#displaying-a-form-using-a-template

--

"The jig's up, Elman."

"Which jig?"

-- Jeff Elman

No comments:

Post a Comment