#yourapp/utils.py
def send_mail_to_admin(obj):
hotels = obj.hotels.all().order_by('cost')
message = 'Тур ID ' + obj.pk + '\n'
message += 'Страна: ' + obj.country_name + ' Город: ' + obj.country_name + '\n'
message += 'Отели: \n'
for hotel in hotels:
message += hotel.name + ' ' + hotel.star + ' ' + hotel.cost + ' руб. \n'
send_mail(
'From Admin',
message,
'no-reply@example.com',
['admin@example.com'],
fail_silently=False,
)
#yourapp/admin.py
from .utils import send_mail_to_admin
class ToursAdmin(admin.ModelAdmin):
exclude = ('created_at',)
list_display = ('country',)
ordering = ('created_at',)
inlines = (HotelsInline,)
def response_add(self, request, obj, post_url_continue=None):
send_mail_to_admin(obj)
return super().response_add(request, obj, post_url_continue)
hotels = ToursHotels.objects.filter(tour_id=tour.id).order_by('cost')
hotels = self.tourshotels_set.all().order_by('cost')
# или если полю ForeignKey передан аргумент related_name:
# class ToursHotels(models.Model):
# tour = models.ForeignKey(Tours, related_name='hotels')
# так:
hotels = self.hotels.all().order_by('cost')
class HotelInline(admin.TabularInline):
model = Hotel
class TourAdmin(admin.ModelAdmin):
inlines = (HotelInline,)
def response_add(self, request, new_object):
print(new_object.pk)
print(new_object.country)
print(new_object.hotels.all())
return super().response_add(request, new_object)
admin.site.register(Tour, TourAdmin)