loading...

DJANGO STEPS TO CREATING A MODULE (to show)

yobretyo profile image Bret ・1 min read

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.

Discussion

pic
Editor guide
Collapse
bigj1m profile image
Jim Plourde

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 Author

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

Collapse
bigj1m profile image
Jim 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 Author

Ok, is there just one Admin.py?

Thread Thread
bigj1m profile image
Jim Plourde

There should be one admin per appliction in your project.

Thread Thread
yobretyo profile image
Bret Author

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

Thread Thread
bigj1m profile image
Jim 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 Author

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.