loading...

re: DJANGO STEPS TO CREATING A MODULE (to show) VIEW POST

FULL DISCUSSION
 

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.

 

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

 

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

 

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.

Ok, is there just one Admin.py?

There should be one admin per appliction in your project.

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

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.

Code of Conduct Report abuse