I’ve just starting fooling around with Django (a Python web framework), and was looking to produce a form. Bear in mind that Django doesn’t really do MVC, but follows the philosophy – separation of logic, representation and appearance:
class BookForm(forms.Form):
title = forms.CharField()
def BookView(request):
form = BookForm()
return render_to_response('book.html', {'form': form})
With boot.html containing (amongst other things):
<form action="" method="get">
{{ form.as_table }}
<input type="submit" value="Search" />
</form>
Which is great! MVC, separation of data, presentation and business logic. Now, how do you get a CSS class onto that title field? CSS, being the way of separating out the presentation part of a HTML page from the data that’s embedded in it? As above, but chuck it in as such:
class BookForm(forms.Form):
title = forms.CharField(
widget=forms.TextInput(attrs={'class':'title-field'}))
Seeing this crunched the gearbox in my mind. All that messy designer stuff, where they make things look nice, that’s worming it’s way into my business logic? Perhaps it’s not so wrong, as the business logic does indeed know that this is a title-field. But it doesn’t quite sit right with me. I’m not convinced it’s wrong, but if you were, you could instead do this in your CSS and HTML:
<style>
.title-field input {background:#ccC68f;}
</style>
<form action="" method="get">
<table>
<tr><td class="title-field"> {{ form.title }} </td></tr>
</table>
<input type="submit" value="Search" />
</form>
Which pretty much forces you to individually place fields — you get to specify the order of fields plus their individual CSS classes.
I’m not sure what the answer is here. Anyone care to enlighten this noob? Bear in mind that there’s a thing to magically tie a model to a form meaning you don’t even need to specify the fields in both the form and model, which you can’t use if you start tossing styles into each field.