[Django]-How to add Search_fields in Django

51👍

✅

The search fields should be a list, not a tuple.

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

Then make sure that you associate this admin object with the model.

admin.site.register(Blog, BlogAdmin)

EDIT:

It’s hard to tell from above, but you should consider just importing the models from models.py instead of redefining them in your admin.py file. Again, it looks like that’s what you’re doing above.

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

0👍

You should register your site at the bottom of the site rather than at the top.
Please try admin.site.register(Blog, BlogAdmin) at the bottom of the page.
I hope that will solve your question

Leave a comment