Skip to content

Instantly share code, notes, and snippets.

@izznogooood
Last active May 21, 2023 20:03
Show Gist options
  • Save izznogooood/207271d5b3445c508f553a0003feab13 to your computer and use it in GitHub Desktop.
Save izznogooood/207271d5b3445c508f553a0003feab13 to your computer and use it in GitHub Desktop.
Using JavaScript fetch to send forms to django

The Idea

Using Django to handle login / authentication / db / email etc. Then creating "normal" endpoints for JS/JSframeworks to manipulate/get data from django Models. This means you will need to be logged inn through the Django backend.

The application can be found here.

JavaScript: A function to get the CSRF token

function getCookie(name) {
    let cookie = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
    return cookie ? cookie[2] : null;
}

JavaScript: Using fetch to send form to Django

function createItem(item) {
    const data = new FormData();
    data.append('quantity', item.quantity);
    data.append('name', item.name);

    fetch('./items/create', {
        method: 'post',
        headers: {
            "X-CSRFToken": getCookie("csrftoken"),
        },
        body: data
    })
        .then((res) => {return res.json()})
        .then(json => {
            UI.addItemToList(json);
            UI.showAlert('Item added...', 'success');
            UI.clearFields();
        })
        .catch(err => {
            UI.showAlert(`Error: ${err}`, 'danger');
            console.log(err)
        });
}

Django: The view

@login_required
def create_item(request):
    if request.method == 'POST':
        data = request.POST
        item = Item(user=request.user, quantity=data['quantity'], name=data['name'])
        item.save()

        return JsonResponse({'quantity': item.quantity, 'name': item.name})
    else:
        return HttpResponseNotFound('404')

The Django Model for reference

class Item(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='items')
    quantity = models.PositiveIntegerField()
    name = models.CharField(max_length=200)

    def __str__(self):
        return f'{self.quantity} {self.name}'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment