'Django webhook receiver

I built a web hook receiver that takes JSON and creates a model object. It works fine with JSON. But someone I am receiving data from uses a different type of string data. I am currently just printing it out in the console. How would I convert this into a model object?

The data they are sending looks like this:

Phone1=4441114444&FirstName=Chris&LastName=Farley&DOB=1982-11-21&[email protected]

class Client(models.Model):
   first_name = models.CharField(blank =True, max_length=100)
   last_name = models.CharField(blank=True, max_length=100)
   phone = models.CharField(max_length=100, null=True, default="", blank=True)
   email = models.EmailField(max_length=100,default="", blank=True)


@csrf_exempt
def webhook(request):
  if request.method == 'POST':
    print(json.loads(request.body)) 
    Client.objects.create(
       first_name=json.loads(request.body)['FirstName'], 
       last_name=json.loads(request.body)['LastName'],
       phone=json.loads(request.body)['Phone1'],
       email=json.loads(request.body)['Email']
       
       )


    return HttpResponse(request.body, status=200)


Solution 1:[1]

You access this with request.POST, so:

def webhook(request):
  if request.method == 'POST':
    Client.objects.create(
       first_name=request.POST['FirstName'], 
       last_name=request.POST['LastName'],
       phone=request.POST['Phone1'],
       email=request.POST['Email']
   )
    return HttpResponse(request.body, status=200)

But usually it is better to process data with forms [Django-doc]: these can perform validation, cleaning, and a ModelForm can save this to a model object in the database.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Willem Van Onsem