winixxee
winixxee

Reputation: 564

how to change the name of the field displaying in my form

I've finished the project but I want to change the name of the field displaying in my forms.py. For example, in my form people can write something in a form named "name" but I want to change this "name" to "title". how do I achieve this?

currently in my forms.py

class PostForm(forms.ModelForm):

    name = forms.CharField(max_length=128, help_text="plz enter")

    url = forms.URLField(max_length=200,
                         help_text="Please enter the URL of the page.", required=False)
    views = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
    class Meta:
        model = Post
        widgets = {
            'category':Select2Widget,
        }
        exclude = ['pub_date', 'moderator', 'rank_score','slug', 'image', 'thumbnail']

and in my models.py

class Post(models.Model):
    category = models.ForeignKey(Category)

and url field as well.

and in my html file, I do

 {{ form|crispy }}

say, I want to change Category to Community, and name to Title, how should I do this? I was thinking to change these as localization since what I'm really trying to do is just to translate english to other language. But It's not working for some reason. is labeling in forms.py my only option?

Upvotes: 1

Views: 120

Answers (1)

Derek Kwok
Derek Kwok

Reputation: 13058

You should (as you said) generally use the label parameter on forms.py to change the label displayed to the user

from django.utils.translation import ugettext_lazy as _

class PostForm(forms.ModelForm):
    name = forms.CharField(
        label=_('Title'),
        ...
    )
    ....

In addition to using label on forms, you can use verbose_name on your model.

class Post(models.Model):
    category = models.ForeignKey(Category, verbose_name=_('Community'))

Note that changing a model field's verbose_name will affect how Django admin displays the field, and also the default label in any model forms that use this model.

For internationalization (i18n) - you should refer to the documentation. In short, you'll want to do the following for strings which should be translated:

from django.utils.translation import ugettext_lazy as _

# if the translation data exists
_('This string will be translated') 

Upvotes: 1

Related Questions