Alien13
Alien13

Reputation: 618

Django - Transforming Form data to REST API, POST request

Given an arbitrary html form, what is the fastest and smoothest way of transforming the entered data to a REST API JSON POST request to an arbitrary address?

Are there any good libraries for this in Django?

Thanks

Upvotes: 4

Views: 3722

Answers (1)

Borut
Borut

Reputation: 3364

The simplest would be to use requests.

Code example for login would be:

import requests

def user_login(request):
   # If token was already acquired, redirect to home page
   if request.session.get('api_token', False):
        return HttpResponseRedirect(reverse('index'))
   
   # Get username and password from posted data, authenticate and
   # if successful save api token to session
   if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        r = requests.post('http://localhost/api-token-auth/', data={'username': username, 'password': password})
        if r.status_code == 200:
            response = r.json()
            token = response['token']
            # Save token to session
            request.session['api_token'] = token
        else:
            messages.error(request, 'Authentication failed')
            return HttpResponseRedirect(reverse('login'))
    else:
        return render(request, 'login.html', {})

That's just a simple example. The key is this part:

r = requests.post('http://localhost/api-token-auth/', data={'username': username, 'password': password})

Upvotes: 1

Related Questions