Home > Enterprise >  When I create an object in Django admin, `form_valid()` method is not called
When I create an object in Django admin, `form_valid()` method is not called

Time:07-16

When a new Listing is created the form_valid() method creates a Bid object. However, when I use Django Admin to create new a Listing then, the Bid object is not created because form_valid() is not called.

    def form_valid(self, form):
        form.instance.author = self.request.user
        self.object = form.save()
        # place a bid in the Bids table with the value starting bid and users id
        bid = round(float(form.cleaned_data['starting_bid']), 2)
        Bid.objects.create(
            bid_value = bid,
            bidder = self.request.user,
            item=self.object
        )
        print('form_valid() called')
        return HttpResponseRedirect(self.get_success_url())

I am new to Python and Django - perhaps the code for creating a new Bid be should be in a method on the Listing model?

I have tried using an admin model, but haven't had any success:
admin.py

from django.contrib import admin
from auctions.models import User, Listing, Watchlist, Bid, Comment


class BidAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change) -> None:
        obj.author = request.user
        super().save_model(request, obj, form)
        bid = round(float(form.cleaned_data['starting_bid']), 2)
        Bid.objects.create(
            bid_value = bid,
            bidder = request.user,
            item=obj
        )

# Register models.
admin.site.register([User, Watchlist, Listing, Comment])
admin.site.register(Bid, BidAdmin)

CodePudding user response:

A ModelAdmin has no .form_valid(…) method [Django-doc], this is for class-based views (CBVs) that inherit from a FormMixin [Django-doc]. The ModelAdmin will call the .save_model(…) method [Django-doc], so you should implement the logic in that method:

class MyModelAdmin(admin.ModelAdmin):
    # …
    
    def save_model(self, request, obj, form, change):
        obj.author = request.user
        super().save_model(request, obj, form)
        bid = round(float(form.cleaned_data['starting_bid']), 2)
        Bid.objects.create(
            bid_value = bid,
            bidder = request.user,
            item=obj
        )
  • Related