未加星标

Build a blog with Django: Add post admin

字体大小 | |
[开发(python) 所属分类 开发(python) | 发布者 店小二03 | 时间 2017 | 作者 红领巾 ] 0人收藏点击收藏

Entering blog content via the command-line is certainlypossible but not very user-friendly. As Raymond Hettinger would prod you to shout, "There must be a better way."


Build a blog with Django: Add post admin

And, there is a better way. It's called the Django admin .

Django is able to automatically generate an admin interface based on the metadata it collects from your models.

I'll show you how to use the admin to manage your blog content.

N.B. The admin is best used only as an internal management tool. If you need an interface that's less model-centric and more process-centric then you should consider writing your own views. Buddy Lindsey from GoDjango gives a good list of 5 reasons not to use the Django admin .

Let's get started.

Accessing the admin

The admin is already enabled since we started with the default project template used by startproject .

N.B. If you're curious about the admin's requirements then you can check here .

To login to the admin you need to create a user. Use the createsuperuser command to do it.

(venv) $ python manage.py createsuperuser Username (leave blank to use 'dwayne'): Email address: [email protected] Password: Password (again): Superuser created successfully.

Then, you can start up the server and navigate to http://127.0.0.1:8000/admin to login and view the admin site.


Build a blog with Django: Add post admin

Take some time to explore the admin site before continuing. I can wait.

Manage posts via the admin

You'd notice that our posts app is nowhere to be found. Let's fix this by telling the admin about our Post model.

Edit posts/admin.py to contain the following:

from django.contrib import admin from .models import Post admin.site.register(Post)

Refresh http://127.0.0.1:8000/admin to see the posts app.


Build a blog with Django: Add post admin

That's it. We can now manage our posts via the admin.

Let me show you.

Click on the Add link next to Posts to view the add page for posts.


Build a blog with Django: Add post admin

Enter some information into the required fields and click the Save button to persist your changes to the database and get redirected to the change list page.


Build a blog with Django: Add post admin

Finally, click on the post to be taken to its change page. Notice that it's similar to the add page. Make any edits you need and save it when you're done.

I'll now show you how easy it is to customize the pages you just saw.

Customize the change list page

Update posts/admin.py to contain the following:

from django.contrib import admin from .models import Post @admin.register(Post) class PostAdmin(admin.ModelAdmin): date_hierarchy = 'published_at' list_display = ( 'title', 'is_published', 'published_at', 'created_at', 'updated_at', ) list_filter = ('is_published',) ordering = ( '-published_at', '-created_at', ) search_fields = ( 'title', 'excerpt', )

Firstly, we create a new class, PostAdmin , that subclasses admin.ModelAdmin . It gives us a place to put our custom values.

Notice that I used the register decorator this time around to register the Post model with PostAdmin . However, doing it the previous way is perfectly fine as well. After the class definition you'd just put admin.site.register(Post, PostAdmin) .

N.B. You can't use the register decorator if you have to reference your model admin class in its __init__() method, e.g. super(PersonAdmin, self).__init__(*args, **kwargs) .

Here's what each class attribute does:

date_hierarchy : It makes the change list page use the published_at field of the Post model to display a date-based drilldown navigation.

list_display : It controls which fields are displayed as columns in the table shown on the change list page.

list_filter : It activates search filters in the right side bar of the change list page based on the elements of the tuple. In our case it will allow us to easily filter between draft and published posts.

ordering : It determines how the posts are ordered. First in descending order of published_at and then in descending order of created_at . This keeps draft posts at the top so they're right there in front of us when we go to the page to continue working on them. Then comes the most recent published posts. Finally, if two posts are published on the same day then the most recently created one appears first in the table.

search_fields : It enables a search box. I've set it to search the title and excerpt fields of the Post model whenever a search query is submitted.

Here's the final result of this customization:


Build a blog with Django: Add post admin
Customize the add/change pages

We're going to make the following changes:

Re-label the is_published field to Is published? .

Auto-populate the slug field when entering the title of the post.

Exclude the published_at field from the form.

Lastly, set the published_at field to an appropriate value when the is_published field is toggled. In particular, when is_published is true then published_at should contain the current date and time when the change is saved. And, when is_published is false then published_at should be set to None .

Here are the edits to posts/admin.py that will make all that possible:

from django import forms from django.contrib import admin from django.utils.timezone import now from .models import Post class PostAdminForm(forms.ModelForm): class Meta: model = Post fields = ['is_published', 'title', 'slug', 'excerpt', 'body'] labels = { 'is_published': 'Is published?', } @admin.register(Post) class PostAdmin(admin.ModelAdmin): # ... form = PostAdminForm prepopulated_fields = { 'slug': ('title',) } def save_model(self, request, obj, form, change): if form.has_changed() and 'is_published' in form.changed_data: if obj.is_published: obj.published_at = now() else: obj.published_at = None super().save_model(request, obj, form, change)

I create a custom model form called PostAdminForm and then tell PostAdmin to use that form instead of the default it generates by setting the form class attribute.

The prepopulated_fields class attribute allows me to auto-populate the slug field when entering the post's title.

Finally, notice how I override the ModelAdmin 's save_model method to perform a custom pre-save operation.

Here are the visible changes:


Build a blog with Django: Add post admin
Wrap up

That completes the customizations we'll be doing to the admin for now. I hope you're still tracking your changes with Git. If so, then now is the time to make your commits. Here are links to the ones I made:

Change list page customizations Add/change page customizations

Finally, check off the second task on your Trello card and bask in the joy of being 50% complete with the feature.

P.S. Let me know in the comments if you get into any problems. I'd be happy to help.

P.S.S. Subscribe to my newsletter if you're interested in getting exclusive Django content.

本文开发(python)相关术语:python基础教程 python多线程 web开发工程师 软件开发工程师 软件开发流程

主题: DjangoGit
分页:12
转载请注明
本文标题:Build a blog with Django: Add post admin
本站链接:http://www.codesec.net/view/524404.html
分享请点击:


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 开发(python) | 评论(0) | 阅读(68)