DEV Community

Bret
Bret

Posted on

DJANGO STEPS TO CREATING A MODULE (to show)

Between app.py, url.py, modules.py .... what do you do “IN ORDER” to creating a object (class) to show up in the admin?
I tried a test, but when I clicked on it... I came up as a error and it dosnt really day what it was.

Top comments (9)

Collapse
 
jmplourde profile image
Jean-Michel Plourde • Edited

So you have Person in models.py which is the model you want to show up in admin.

class Person(models.Model):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    age = models.PositiveInteger()
    bio = models.CharField(max_length=1000)

You create a file admin.py in which you import your model, register it with the decorator and declare which fields will show up where.

import models # import you model

@admin.register(models.Person) # Add the admin register decorator for your model
class PersonAdmin(admin.ModelAdmin): # Your admin class inherits from `admin.ModelAdmin`

list_display = ( # Which fields are displayed in the object list
    'id',
    'first_name',
    'last_name',
)

fields = ( # when you click on an object, tells which fields will show up
    'id'
    'first_name', 
    'last_name',
    'biography',
) 

readonly_field = ( # tells which field can't be edited
    'id',
)

Read the Django admin model doc so you can use other field options, like inline which is very useful when you want to link fields from other models.

Collapse
 
yobretyo profile image
Bret

Can I use templates and render HTML instead of a class?

Collapse
 
jmplourde profile image
Jean-Michel Plourde

Since an admin is a really comon component of a website, Django takes care of it and render everything. All you have to do is register your model as an admin model and that's it.

Thread Thread
 
yobretyo profile image
Bret

Ok, is there just one Admin.py?

Thread Thread
 
jmplourde profile image
Jean-Michel Plourde

There should be one admin per appliction in your project.

Thread Thread
 
yobretyo profile image
Bret

So for each App? I only see one admin, I created a products app and a test app

Thread Thread
 
jmplourde profile image
Jean-Michel Plourde

Yes, when you run python manage.py startapp projectApp it creates an app with all the required files. If it's not there, just create it under the app folder you want it.

Collapse
 
yobretyo profile image
Bret

Thank you! I actually followed the same steps as a different test project, and it works where I can add a product. But this isn’t working yet

Collapse
 
thatthep profile image
Thatthep

Now in your list.

I create model then add it to admin.py for each app.