R
R
rusrich2021-12-26 12:31:46
Python
rusrich, 2021-12-26 12:31:46

How to create an object of another model in Django Admin on the edit page of one model?

Good afternoon.

In the admin panel, when you click on the button on the edit page of one model, make sure that an object of another model is created:

from loans.models import Bid, Payment

@admin.register(Bid)
class Bid(admin.ModelAdmin):
    change_form_template = "admin/my_admin_bid.html"

        def response_change(self, request, obj):
        if "_make_paid" in request.POST:
            obj.state = 'PAID'
            obj.save()
            Payment.objects.create(bid=obj, amount=amount)
            # Получаю Error: AttributeError: type object 'Payment' has no attribute 'objects'
            self.message_user(request, "This loan mark as PAID")
            return HttpResponseRedirect(".")
        return super().response_change(request, obj)


Can't google the solution.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
rusrich, 2021-12-26
@rusrich

Works like this:

class Bid(admin.ModelAdmin):
    change_form_template = "admin/my_admin_bid.html"

        def response_change(self, request, obj):
        if "_make_paid" in request.POST:
            obj.state = 'PAID'
            obj.save()
            obj.payment.create(bid=obj, amount=amount)
            self.message_user(request, "This loan mark as PAID")
            return HttpResponseRedirect(".")
        return super().response_change(request, obj)

Instead of Payment.objects.create(bid=obj, amount=amount)
We write this obj.payment.create(bid=obj, amount=amount)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question