简体   繁体   中英

How can I implement post_save signals in Django?

I am currently building a geolocation app, and I'm somewhat stuck somewhere. I'm trying to implement a post_save Django signals in this code, but I can't figure out what exactly I need to do. any help here would be appreciate. Here's my code:

from ipaddress import ip_address

from django.contrib.auth import get_user_model

from celery import shared_task from apps.users.abstractapi import AbstractAPI

User = get_user_model()

@shared_task def enrich_user(user_pk): user = User.objects.get(pk=user_pk) api = AbstractAPI()

location_details = api.get_geolocation_details(ip_address=user.ip_address)
if location_details is not None:
    user.country = location_details.get("country")
    user.country_code = location_details.get("country_code")
    user.country_geoname_id = location_details.details.get("country_geoname_id")
    user.longitude = location_details.get("longitude")
    user.latitude = location_details.get("latitude")
    user.save(update_fields=("country", "country_code", "country_geoname_id", "longitude", "latitude"))

holiday_details = api.get_holiday_details(
    country_code=user.country_code,
    day=user.date_joined.day,
    month=user.date_joined.month,
    year=user.date_joined.year,
)

if holiday_details is not None and any(holiday_details):
    user.joined_on_holiday = True
    user.save(update_fields=("joined_on_holiday",))

A post_save signal in Django looks like this:

from django.dispatch import receiver

@receiver(models.signals.post_save, sender=User)
def your_function(sender, instance, using, **kwargs):
    # your code that you want to run

    instance.save()

Be careful with saving the instance - that will itself cause the post_save signal to run again. You should put a condition in place that will only evaluate once before the instance is saved. Something like:

if instance.joined_on_holiday == False:
   instance.joined_on_holiday = True
   instance.save()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM