如何在Django中添加Search_fields

时间:2012-06-26 16:47:28

标签: python django django-admin

我尝试使用python在Django中添加搜索字段。以下是我使用过的代码。

# admin.py file

from django.db import models
from blog.models import Blog
from django.contrib import admin
admin.site.register(Blog)

class Blog(models.Model):
    title = models.CharField(max_length=60)
    body = models.TextField()
    created = models.DateTimeField("Date Created")
    updated = models.DateTimeField("Date Updated")
    def __unicode__(self):
        return self.title

class Comment(models.Model):
    body = models.TextField()
    author = models.CharField(max_length=60)
    created = models.DateTimeField("Date Created")
    updated = models.DateTimeField("Date Updated")
    post = models.ForeignKey(Blog)
    def __unicode__(self):
        return self.body

class CommentInline(admin.TabularInline):
    model = Comment


class BlogAdmin(admin.ModelAdmin):
    list_display = ('title','created', 'updated')
    search_fields = ['title','body']
    list_filter = ('Date Created','Date Updated')
    inlines = [CommentInline]

class CommentAdmin(admin.ModelAdmin):
    list_display = ('post','author','body_first_60','created','updated')
    list_filter = ('Date Created','Date Updated')

我尝试使用以下代码为标题和正文添加search_fields。

class BlogAdmin(admin.ModelAdmin):
    . . .
    search_fields = ('title','body')
    . . .

当我运行时,我看不到任何搜索框。这是为什么 ?我想要你的帮助。我只是个初学者。 谢谢!

2 个答案:

答案 0 :(得分:28)

搜索字段应该是列表,而不是元组。

class BlogAdmin(admin.ModelAdmin):
    . . .
    search_fields = ['title','body']
    . . . 

然后确保将此管理对象与模型相关联。

admin.site.register(Blog, BlogAdmin)

修改

上面很难说,但你应该考虑从models.py导入模型,而不是在admin.py文件中重新定义它们。再次,看起来这就是你正在做的事情。

admin.py:

from django.db import models
from blog.models import Blog
from django.contrib import admin

class CommentInline(admin.TabularInline):
    model = Comment

class BlogAdmin(admin.ModelAdmin):
    list_display = ('title','created','updated',)
    search_fields = ['title','body',]
    list_filter = ('Date Created','Date Updated',)
    inlines = [CommentInline,]

class CommentAdmin(admin.ModelAdmin):
    list_display = ('post','author','body_first_60','created','updated',)
    list_filter = ('Date Created','Date Updated',)

admin.site.register(Blog, BlogAdmin)

models.py

from django.db import models

class Blog(models.Model):
    title = models.CharField(max_length=60)
    body = models.TextField()
    created = models.DateTimeField("Date Created")
    updated = models.DateTimeField("Date Updated")

    def __unicode__(self):
        return self.title

class Comment(models.Model):
    body = models.TextField()
    author = models.CharField(max_length=60)
    created = models.DateTimeField("Date Created")
    updated = models.DateTimeField("Date Updated")
    post = models.ForeignKey(Blog)

    def __unicode__(self):
        return self.body

答案 1 :(得分:0)

您应该在网站底部而不是在顶部注册您的网站 请尝试页面底部的admin.site.register(博客,BlogAdmin)。
我希望能解决你的问题