in django how can I get the "label" of a field, knowing its class name and field name as…
- User
in django how can I get the "label" of a field, knowing its class name and field name as strings? For example class MyModel(models.Model): my_field = models.IntegerField('the label'), I would like to get the label, knowing 'MyModel' and 'my_field'.
Assistant
Getting a Field's Label in Django
To get the label of a field in Django when you know the model class name and field name as strings, you can use the following approach:
from django.apps import apps def get_field_label(model_name, field_name): # Get the model class from the app registry model_class = apps.get_model(model_name) # Get the field object field = model_class._meta.get_field(field_name) # Return the verbose_name (label) return field.verbose_name
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.