user2563044
user2563044

Reputation:

Django: Remove/Change Field Text in HTML Django Forms

I have a Django form:

from django import forms
from hello.models import Whisper

class WhisperForm(forms.ModelForm):

    class Meta:
        model = Whisper
        fields = '__all__' 

I'm showing it in an HTML page like such:

<form action="Whisper" method="post">{% csrf_token %}
    <div class="form-group">
        <p>
            {{form}}
        <p>
        <input type="submit" name="submit" value="Submit Whisper">
    </div>
</form>

The form shows up correctly, but shows the model name in a rather ugly manner, like:

Whisper:[*This is the text field]

Is there any way I can remove the Model from sticking to the text field or at least change what it displays?

Upvotes: 0

Views: 1301

Answers (2)

Joey Wilhelm
Joey Wilhelm

Reputation: 5819

The recommended method, as described in the Django docs, is through the labels variable in the form's Meta class.

class WhisperForm(forms.ModelForm):

    class Meta:
        model = Whisper
        fields = '__all__'
        labels = {'whisper': 'Custom label text here'}

Upvotes: 2

Adrian Ghiuta
Adrian Ghiuta

Reputation: 1619

You can override the default labels for the form in it's __init__, like this:

class WhisperForm(forms.ModelForm):

    class Meta:
        model = Whisper
        fields = '__all__' 

    def __init__(self, *args, **kwargs):
        super(WhisperForm, self).__init__(*args, **kwargs)
        self.fields['whisper'].label = 'Whisper'

Upvotes: 1

Related Questions