Markos Gogoulos
Markos Gogoulos

Reputation: 381

Styling forms and django form values

I'm trying to style a form with CSS. First of all I haven't seen a complete example, other than on the official documentation, so I would appreciate any blog entries, or articles.

Now on my form, a typical Charfield gets translated on html like this:

<input type="text" name="artists" id="id_artists" />

If my form contains errors on some field, the previous Charfield remembers the value and goes:

<input type="text" name="artists" value="Pink Floyd" id="id_artists"  />

How can I get this value (value="Pink Floyd") in django forms? Say my field is {{form.artists}}, I can use {{form.artists}} as the field, {{form.artists.label}} as label, {{form.artists.errors}} and {{form.artists.help_text}}, but how about this value?

Thanks in advance!

Upvotes: 2

Views: 1797

Answers (3)

Raj
Raj

Reputation: 3908

You can also add additional validation to the form class to do something with the form data. From djangobook.com:

from django import forms

class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    email = forms.EmailField(required=False)
    message = forms.CharField(widget=forms.Textarea)

    def clean_message(self):
        message = self.cleaned_data['message']
        num_words = len(message.split())
        if num_words < 4:
            raise forms.ValidationError("Not enough words!")
        return message

Inside of the clean_message method you can access a given field using the self.cleaned_data dictionary. This dictionary is available for any form that is validated.

Be sure to return the field, in this case message, or else None is returned.

Upvotes: 0

Gu&#240;mundur H
Gu&#240;mundur H

Reputation: 11988

You can get the current value of the field from the data property:

{{ form.artists.data }}

I can't see the Django documentation mentioning this, but it works...

Upvotes: 2

Steerpike
Steerpike

Reputation: 17554

Create the input field specifically, rather than relying on django to auto-create it.

Something like:

<input type="text" name="artists" id="id_artists" value="{{form.artists.title}}" />

should work

Upvotes: 4

Related Questions