Skip to content

Instantly share code, notes, and snippets.

@hemantbadhe
Last active September 16, 2019 18:29
Show Gist options
  • Select an option

  • Save hemantbadhe/d59add15b43aeff510288779f6efaa2b to your computer and use it in GitHub Desktop.

Select an option

Save hemantbadhe/d59add15b43aeff510288779f6efaa2b to your computer and use it in GitHub Desktop.
Django post save signal
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_api.models import UserProfile
@api_view(['GET', 'POST'])
def index(request):
"""
request_data = {
"meta": [
{
"first_name": "Test"
},
{
"last_name": "Demo"
},
{
"address": "Pune, Maharastra, India"
}
]
}
"""
user_profile = UserProfile.objects.get(user__username='admin')
if request.method == 'GET':
response_dict = {
'username': user_profile.user.username,
'first_name': user_profile.user.first_name,
'last_name': user_profile.user.last_name,
'email': user_profile.user.email,
'address': user_profile.address,
'phone_number': user_profile.phone_number,
'meta': user_profile.meta,
}
return Response(response_dict)
data = request.data.get('meta')
user_profile = UserProfile.objects.get(id=1)
user_profile.meta = data
user_profile.save()
return Response({"success": True})
def check_field(field, data): # checks if key is present in list of dict
return any(field in d for d in data)
def get_value(field, data): # get value if key is present in list of dict
return next(d for i, d in enumerate(data) if field in d)[field]
@receiver(post_save, sender=UserProfile)
def update_user_from_meta_data(sender, **kwargs):
user_profile = kwargs['instance']
meta_data = user_profile.meta
if meta_data:
post_save.disconnect(update_user_from_meta_data, sender=sender)
user_obj = User.objects.get(pk=user_profile.user.id)
if check_field('first_name', meta_data):
user_obj.first_name = get_value('first_name', meta_data)
if check_field('last_name', meta_data):
user_obj.last_name = get_value('last_name', meta_data)
user_obj.save()
if check_field('address', meta_data):
user_profile.address = get_value('address', meta_data)
user_profile.save()
post_save.connect(update_user_from_meta_data, sender=sender)
print('*** success **')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment