Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot override save_model django admin?

Tags:

python

django

I do not understand what I am doing wrong. I want a user to only add the title and description of the Annoucement Model and the rest should be filled automatically. Here is my model:

class Annoucement(models.Model):
    username = models.ForeignKey(User, on_delete=None)
    title = models.CharField(max_length=500, default="")
    description = models.TextField(max_length=5000, default="")
    datetime = models.DateTimeField(default=datetime.now)

    def __str__(self):
        return self.title + " " + self.username.username

And this is admin.py file.

from django.contrib import admin

from .models import Profile, Activity, View, Annoucement
# Register your models here.


class AnnoucementAdmin(admin.ModelAdmin):
    fields = ['title', 'description']


    def save_model(self, request, obj, form, change):
        obj.username = request.user
        print("yes")
        super(AnnoucementAdmin, self).save_model(request, obj, form, change)

admin.site.register(Profile)
admin.site.register(Activity)
admin.site.register(View)
admin.site.register(Annoucement)

Also, the print("yes") is also not coming on the terminal once I save the model from the admin panel. HELP!

like image 525
Baqir Khan Avatar asked Jan 21 '26 02:01

Baqir Khan


2 Answers

1) admin.site.register(Annoucement, AnnoucementAdmin)

2) add 'return' in the last of save_model

class AnnoucementAdmin(admin.ModelAdmin):
    fields = ['title', 'description']

    def save_model(self, request, obj, form, change):
        obj.username = request.user
        print("yes")
        return super(AnnoucementAdmin, self).save_model(request, obj, form, change)
like image 91
Neeraj Kumar Avatar answered Jan 23 '26 16:01

Neeraj Kumar


you have to pass the class AnnoucementAdmin, like this:

....
admin.site.register(Annoucement, AnnoucementAdmin)
like image 27
Vinicius Campanate Avatar answered Jan 23 '26 15:01

Vinicius Campanate



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!