rahmatnazali
rahmatnazali

Reputation: 180

Django make a custom field name

I know that I can have verbose_name on each model's field like so

form_name = models.CharField('Form Name', max_length = 100)

How if I want to change a specific field's name just for a specific view/case?

For example, on a certain case I want it to be "Your Form Name", and on another case I want it to be "His Form Name", etc.

Thanks in advance.

Upvotes: 1

Views: 3867

Answers (2)

Diego Vinícius
Diego Vinícius

Reputation: 2243

If you using Django Forms you can use what @Wiliem Van Onsem said, if you trying to change it at ListView in django admin you can use short_descriptions

def _new_first_name(obj):
    return obj.first_name
upper_case_name.short_description = 'Custom First Name'

class PersonAdmin(admin.ModelAdmin):
    list_display = (_new_first_name, first_name)

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477759

I think you are mixing up models and forms. A model is used to store and manipulate data. It also implements the semantical layer of your business logic.

A form is used to construct convenient ways for a user to enter data. A form can target a specific model. But this is not per se the case: some forms manipulate different model instances at once, or no models at all, or only parts of a specific model.

A model can be manipulated through different forms. For example one form can update a certain subset of a model instance whereas another form can update another subset. The idea is that usually a model has no knowledge of the forms that edit the model, whereas the forms that target a model require some knowledge about the model (at least a limited list of fields to edit).

To answer your question, you typically thus define a model like:

class SomeModel(models.Model):

    name = models.CharField(max_length = 100, verbose_name='Label 1')

Now by default ModelForms will take the verbose_name as the label, but you can override this. For example we can define two forms that both target SomeModel:

class SomeModelForm1(ModelForm):
    class Meta:
        model = SomeModel
        fields = ['name']

class SomeModelForm2(ModelForm):
    class Meta:
        model = SomeModel
        fields = ['name']
        labels = {'name': 'Label 2'}

The second form will thus use another label for the name field.

Upvotes: 5

Related Questions