Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django admin: can I define fields order?

Tags:

django

I use abstract models in Django like:

class Tree(models.Model):     parent = models.ForeignKey('self', default=None, null=True, blank=True,                                related_name="%(app_label)s_%(class)s_parent")      class Meta:         abstract = True  class Genre(Tree):     title = models.CharField(max_length=150) 

And all fields from the abstract model go first in Django's admin panel:

parent: abstract_field2: title: model_field2: ... 

Is there a way to put them (fields from abstract classes) in the end of the list?
Or a more general way to define order of fields?

like image 423
Sergey Avatar asked Oct 10 '14 23:10

Sergey


People also ask

What we can do in admin portal in Django?

Overview. The Django admin application can use your models to automatically build a site area that you can use to create, view, update, and delete records. This can save you a lot of time during development, making it very easy to test your models and get a feel for whether you have the right data.

What is the Changelist in Django admin?

Django Admin's "change list" is the page that lists all objects of a given model. Now, all your articles should have a different name, and more explicit than "Article object".


2 Answers

You can order the fields as you wish using the ModelAdmin.fields option.

class GenreAdmin(admin.ModelAdmin):     fields = ('title', 'parent') 
like image 56
Alasdair Avatar answered Sep 19 '22 14:09

Alasdair


Building off rbennell's answer I used a slightly different approach using the new get_fields method introduced in Django 1.7. Here I've overridden it (the code would be in the definition of the parent's ModelAdmin) and removed and re-appended the "parent" field to the end of the list, so it will appear on the bottom of the screen. Using .insert(0,'parent') would put it at the front of the list (which should be obvious if you're familiar with python lists).

def get_fields (self, request, obj=None, **kwargs):     fields = super().get_fields(request, obj, **kwargs)     fields.remove('parent')     fields.append('parent') #can also use insert     return fields 

This assumes that your fields are a list, to be honest I'm not sure if that's an okay assumption, but it's worked fine for me so far.

like image 25
thrillhouse Avatar answered Sep 19 '22 14:09

thrillhouse