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.
function getCookie(name) {
let cookie = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
return cookie ? cookie[2] : null;
}
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)
});
}
@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')
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}'