Amon
Amon

Reputation: 2951

Creating new model in Django with POST data from Python requests

I'm trying to take information from a POST request made from Python requests and add them to my model:

def message(request):

    if request.method == 'POST':
        form = InputInfoForm(request.POST)
        #form models make validation easy
        if form.is_valid():
            InputInfo.name = request.POST.get('name')
            InputInfo.conversation_id = request.POST.get('conversation_id')
            InputInfo.message_body = request.POST.get('message_body')


        return HttpResponse(status=200)

    return HttpResponse(status=200)

Here's the request

post_data = {'name': 'charles', 'conversation_id': '3', 'message_body': 'Ada Challenge'}
r = requests.post('http://127.0.0.1:8000/message/', data=post_data)

I am not sure if I am handling the requests right in the view

Upvotes: 1

Views: 1690

Answers (1)

Ritesh Agrawal
Ritesh Agrawal

Reputation: 821

As mentioned in comments that InputInfoForm is a ModelForm. So you can call form.save method after calling form.is_valid method.

if form.is_valid():
    form.save() # This method will handle data saving part, no need to assign explicitly

Upvotes: 2

Related Questions