django官网ModelForm ModelAdmin

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django官网ModelForm ModelAdmin相关的知识,希望对你有一定的参考价值。

格式整理

  1. ModelForm
class AuthorForm(ModelForm):
        title = CharField(validators=[def_of_validator_name])

    class Meta:
        model = Author
        fields = (‘name‘, ‘title‘, ‘birth_date‘)  
        widgets = {
            ‘name‘: Textarea(attrs={‘cols‘: 80, ‘rows‘: 20}),
        }
        labels = {
            ‘name‘: _(‘Writer‘),
        }
        help_texts = {
            ‘name‘: _(‘Some useful help text.‘),
        }
        error_messages = {
            ‘name‘: {
                ‘max_length‘: _("This writer‘s name is too long."),
            },
        }

2 ModelAdmin

class ArticleAdmin(admin.ModelAdmin):
    ## 2 
    search_fields=(‘title‘,‘join__xx‘)
    list_display = [‘title‘, ‘status‘]
    list_filter=(‘title‘,)
    list_editable=(‘xxx‘,)
    ordering = [‘title‘]
    actions = [make_published]
    ## 3
    filter_horizontal=(‘manytomany‘,)

admin.site.register(Article, ArticleAdmin)

3 Admin Action

技术分享图片

from django.db import models
from django.utils.html import format_html

STATUS_CHOICES = (
    (‘d‘, ‘Draft‘),
    (‘p‘, ‘Published‘),
    (‘w‘, ‘Withdrawn‘),
)

class Article(models.Model):
    title = models.CharField(max_length=100)
    body = models.TextField()
    status = models.CharField(max_length=1, choices=STATUS_CHOICES)

    ## for web display  
    def colored_status(self):
           if self.status==‘d‘:
                format_td=format_html(‘<span class="xxxcolor">xxx<span>‘)
          return format_td
     colored_status.short_description="onweb_show_name"         

    def __str__(self):
        return self.title
from django.contrib import admin
from myapp.models import Article

def make_published(modeladmin, request, queryset):
    queryset.update(status=‘p‘)
make_published.short_description = "Mark selected stories as published"

class ArticleAdmin(admin.ModelAdmin):
    list_display = [‘title‘, ‘status‘,‘colored_status‘]
    ordering = [‘title‘]
    actions = [make_published]

admin.site.register(Article, ArticleAdmin)

技术分享图片

以上是关于django官网ModelForm ModelAdmin的主要内容,如果未能解决你的问题,请参考以下文章

Django的ModelForm

Django之ModelForm组件

django的modelform怎么设置required=False

Django(Form,ModelForm)

Django之ModelForm详解

django中的modelform和modelfoemset