Can you change a field label in the Django Admin application? - python

As the title suggests. I want to be able to change the label of a single field in the admin application. I'm aware of the Form.field attribute, but how do I get my Model or ModelAdmin to pass along that information?

the verbose name of the field is the (optional) first parameter at field construction.

If your field is a property (a method) then you should use short_description:
class Person(models.Model):
...
def address_report(self, instance):
...
# short_description functions like a model field's verbose_name
address_report.short_description = "Address"

As Javier suggested you can use verbose name in your fields in model.py. Example as below,
class Employee(models.Model):
name = models.CharField(max_length = 100)
dob = models.DateField('Date Of Birth')
doj = models.DateField(verbose_name='Date Of Joining')
mobile=models.IntegerField(max_length = 12)
email = models.EmailField(max_length=50)
bill = models.BooleanField(db_index=True,default=False)
proj = models.ForeignKey(Project, verbose_name='Project')
Here the dob,doj and proj files will display its name in admin form as per the verbose_name mentioned to those fields.

from django.db import models
class MyClassName(models.Model):
field_name = models.IntegerField(verbose_name='Field Caption')

Building on Javier's answer; if you need one label in forms (on the front-end) and another label on admin it is best to set internal (admin) one in the model and overwrite it on forms. Admin will of course use the label in the model field automatically.

Use "verbose_name" to change a field name as the example below.
"models.py":
from django.db import models
class MyModel(models.Model): # Here
name = models.CharField(max_length=255, verbose_name="My Name")

If you want change the field label only on particular admin model without changing field of the model:
class MyModelAdmin(admin.ModelAdmin):
def get_form(self, request, obj=None, **kwargs):
form = super().get_form(request, obj, **kwargs)
form.base_fields["name"].label = "New label"
return form

Related

Sort a displayed column defined by a custom model method in the Django admin interface

I want to be able to sort a table column defined using a custom method in the Django admin.
I narrowed down the problem to this simple example in Django:
models.py:
from django.db import models
class MyObject(models.Model):
name = models.CharField(_("name"), max_length=255)
layers = models.URLField(_("Layers"), blank=True, max_length=1024)
choices = models.TextField(
verbose_name=_("Choice values"),
blank=True,
help_text=_("Enter your choice"),
)
class Meta:
verbose_name = _("Object config")
verbose_name_plural = _("Objects config")
def __str__(self): # my custom method
return self.name
and admin.py:
from django import forms
from django.contrib import admin
class MyObjectAdminForm(forms.ModelForm):
"""Form"""
class Meta:
model = models.MyObject
fields = "__all__"
help_texts = {
"layers": "URL for the layers",
}
class MyObjectAdmin(admin.ModelAdmin):
form = MyObjectAdminForm
list_filter = ["name",]
search_fields = ["name",]
# I want the first column (__str__) to be sortable in the admin interface:
list_display = ["__str__", ...] # the ... represent some other DB fields
but for the moment I cannot sort that first column (it is grayed out, I cannot click on its title):
So how could I sort the first column in this admin table as defined by the __str__() method of the MyObject model? (please note that I cannot change the model itself. I'm also brand new to Django, so don't hesitate to detail your answer as if you were speaking to a kid.)

How to change models name in django from django admin interface?

using "verbose_name" we can change the models name, but here i want this process to be kind of dynamic, like from inside admin panel itself, it will be renamed, so that it will not have to be hard coded.
can anybody suggest any solution?
You can implement some sort of model for this that will store the changed model names, like:
class ModelName(models.Model):
model_key = models.CharField(max_length=128, unique=True)
model_name = models.CharField(max_length=128)
def model_name(name):
try:
return ModelName.objects.get(model_key=name).model_name
except ModelName.DoesNotExist:
return name
Next we can make a class that lazily resolves the name, like:
from django.utils.functional import lazy
model_name_lazy = lazy(model_name, str)
Now we can set the name of an object to:
class MyModel(models.Model):
# ...
class Meta:
verbose_name = model_name_lazy('mymodel')
By then modifying the ModelName model, for example on the Django admin pages, you can add/change a ModelName object with model_key is 'mymodel', and then the verbose name of that model will be the corresponding model_name field.

default text for foreign key in form in django

I know that is the simple question but I have trouble with this
I have a table that shows colors and I used this as foreign key in Post table
class Post(models.Model):
"""docstring for Post"""
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1 )
slug = models.SlugField(unique=True)
post_title = models.CharField(max_length=50, help_text="write about your product")
color=models.ForeignKey(Color)
phone=models.CharField(max_length=20)
now when I want to show the form of Post to show the first row like this in color field
now I want to show choose color instead of --------.
In your model form, you can use __init__() to initialize your form. Something like:
from django import forms
from .models import Post
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('post_title', 'color') # fields to show in your form
def __init__(self, *args, **kwargs):
super(PostForm, self).__init__(*args, **kwargs)
self.fields['color'].empty_label = "Choose color"
By default the widget used by ModelChoiceField will have an empty choice at the top of the list. You can change the text of this label (which is "---------" by default) with the empty_label attribute, or you can disable the empty label entirely by setting empty_label to None
Docs
Ex:
field1 = forms.ModelChoiceField(queryset=..., empty_label="(Choose color)")

Django admin: Edit fields of one-to-one model class

I have two models with the following relationship defined in models.py:
class InnerModel(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class OuterModel(models.Model):
inner = models.OneToOneField(InnerModel)
def __str__(self):
return "OuterModel"
My forms.py looks like this:
class OuterModelForm(forms.ModelForm)
class Meta:
model = OuterModel
fields = ['inner']
My admin.py form looks like this:
class OuterModelAdmin(admin.ModelAdmin)
form = OuterModelForm
admin.site.register(OuterModel, OuterModelAdmin)
When I display the admin page, I can see the InnerModel instance and the name field is present, but the name field is an empty drop-down menu rather than a blank text field that can be edited.
How can I change the InnerModel name field so that it can be edited by admin?
You need to use inlines (doc):
class InnerModelInline(admin.StackedInline):
model = InnerModel
class OuterModelAdmin(admin.ModelAdmin):
inlines = [InnerModelInline]
admin.site.register(OuterModel, OuterModelAdmin)
Similar question: here

django Model Forms customizing fields

I have created a model with some classes:
class Student(models.Model):
name = models.CharField(max_length=40)
last_name = models.CharFIeld(max_length=40)
(...)
and in the same models.py file at the bottom I've added a class corresponding to one of my models so i can create a form:
class StudentForm(ModelForm):
class Meta:
model = Student
How do I customize form fields created via ModelForm class ? I was reading django Documentation and I can't understand overriding the default types part.
For example, in documentation they say this will work:
class ArticleForm(ModelForm):
pub_date = DateField(label='Publication date')
class Meta:
model = Article
but when i type my values it's not working. I can't define my label:
class StudentForm(ModelForm):
name = CharField(label='New label')
class Meta:
model = Student
Do i have to create a file like forms.py with identical fields as in Model class and then customize them ? Is it possible to change single field css attributes like width, height using only Model Forms ?
Field for form use a difference library to create a from. You need to import django.forms and use form.XXX for specific Field
from django import forms
class StudentForm(ModelForm):
class Meta:
model = Student
subject = forms.CharField(label='New label')
In order to customize field in model form, you don't need to create it manually. Django model fields have special attributes:
verbose_name (goes to label of the field)
help_text (by default rendered as additional description below the field)
So, all you need is:
class Student(models.Model):
name = models.CharField(
max_length=40,
verbose_name="Student's Name",
help_text="Please tell me your name") # Optional
last_name = models.CharFIeld(max_length=40)
...
Then you don't need to do any customization in model form.
See: https://docs.djangoproject.com/en/dev/ref/models/fields/#verbose-name

Categories

Resources