Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add an additional description to a Django field which would be stored in the database?

I would like to provide context help for the input fields in my forms ("First name": "Your first name. Please enter all of them if you have several."). Instead of hard-coding them in source code, I would like to make those help texts editable through the admin interface. My idea is to somehow extend the field class (include a new attribute similar to verbose_name) and store that in the database (probably a three-column table 'Model, Field, Help' would be sufficient).

However, I don't know whether this is feasible or has been done before. Do you? Could you give me some to where to start if it has been not?

like image 741
Nikolai Prokoschenko Avatar asked Oct 28 '25 14:10

Nikolai Prokoschenko


1 Answers

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

E.g.,

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 don't see the benefit of having it in the database rather than in the form tied to the field.

EDIT:

So you can override the help text. Let's say first imagine you had a dictionary for each form you want to override help_text in a form. Before rendering the Context, you could reprocess 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.

Now where and how you want to store the help text is your choice; e.g., your solution of creating a ModelFieldHelp with three char fields (Model Name, Field Name, Help Text) would work, then you need something like

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])

Now it may make sense to automate this process for all your models that you create forms for, by defining a function in the form or model that automatically creates these ModelHelpFields (if not defined) and updates itself with the current help text after being initialized ...

like image 56
dr jimbob Avatar answered Oct 30 '25 05:10

dr jimbob