Iqbal
Iqbal

Reputation: 2324

Update a particular field in the entire django model

I have a model

class College(models.Model):
    is_published = models.NullBooleanField(default=False)
    name = models.CharField(max_length=255)

I registered the model in admin.py

@admin.register(College)
class CollegeAdmin(admin.ModelAdmin):
    list_display = ('id', 'name')

Now I want to have a button on the admin panel, on pressing which I can change the is_published field of all the objects in the model to True.

I have no idea how should I proceed. Any working code snippet will be appreciated.

Upvotes: 0

Views: 49

Answers (1)

Iain Shelvington
Iain Shelvington

Reputation: 32294

A custom admin action is the perfect tool for this job.

For example (copied almost word for word from the documentation):

def publish(modeladmin, request, queryset):
    queryset.update(is_published=True)
publish.short_description = "Mark selected stories as published"

@admin.register(College)
class CollegeAdmin(admin.ModelAdmin):
    list_display = ('id', 'name')
    actions = [publish]

Upvotes: 2

Related Questions