How to add an additional description to the Django field that will be stored in the database?

I would like to provide context-sensitive help for the input fields in my forms ("Name": "Your name. Please enter all of them if you have several of them"). Instead of hard-coding them in the source code, I would like these help texts to be edited through the admin interface. My idea is to somehow expand the field class (include a new attribute similar to verbose_name), and save it in the database (perhaps the three-column table "Model, field, help" is enough).

However, I do not know if this is possible or has been done before. You? Could you tell me where to start if this is not so?

+3
source share
1 answer

Each field in the form already contains help_text, although it should be declared as a parameter in the field in the Form class.

For instance,

class SomeForm(forms.Form):
    some_field1 = forms.CharField(verbose_name="Some Field 1", max_length=100, help_text="Please the first field.")
    some_field2 = forms.CharField(verbose_name="Some Field 2", max_length=100, help_text="Please the second field.")

Personally, I do not see the advantage of having it in the database, and not in the form associated with the field.

EDIT:

This way you can override the help text. Suppose first that you have a dictionary for each form that you want to override help_text in the form. Before creating the context, you can rework the form with the dictionary as such:

my_form = SomeForm()
for field_name, new_help_text in my_form_override_help_text_dict.items():
    my_form.fields[field_name].help_text = new_help_text

and then add my_form to the context before rendering it.

, - ; , ModelFieldHelp char ( , , ) , -

class ModelHelpField(models.Model):
    model_name = CharField(max_length=50)
    field_name = CharField(max_length=50)
    new_help_text = CharField(max_length=50)

field_help_qs= ModelHelpField.objects.filter(model_name='SomeModel')
my_form_override_help_text_dict = dict([(mfh.field_name, mfh.new_help_text) for mfh in field_help_qs])

, , , ModelHelpFields ( ) ...

+3

Source: https://habr.com/ru/post/1776715/


All Articles