Please help.

I am developing an application with a database of products, I got the Product model in models.py:

class CommonModel(models.Model): created = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) class Meta: abstract = True class Product(CommonModel): product_name = models.CharField(max_length=100) measure = models.ForeignKey(Measure, on_delete=models.CASCADE, default='1') barcode = models.CharField(max_length=20, default='') def __str__(self): return '%s' % self.product_name class Meta: verbose_name = 'Продукт' verbose_name_plural = 'Продукты' ordering = ('product_name', 'id') # сортировка объектов по имени 

created serializer in serializers.py:

 class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ('id', 'product_name', 'measure', 'barcode') 

via the TemplateHTMLRenderer generated page (views.py):

 @api_view(('GET','POST')) @renderer_classes((TemplateHTMLRenderer,)) def ProductList(request): queryset = Product.objects.all() return Response({'object_list': queryset}, template_name='products/product_list.html') 

urls.py:

 urlpatterns = [ path('products/', ProductList), ] 

products / product_list.html template:

 {% for o in object_list %} <tr> <th scope="row">{{ o.id }}</th> <td>{{ o.product_name }}</td> <td>{{ o.measure }}</td> <td>{{ o.barcode }}</td> <td>{{ o.created }}</td> <td>{{ o.updated }}</td> </tr> {% endfor %} 

Now I want in the form on the generated page to add the functionality of adding a product with a background POST request (without reloading the page, through the API).

 <form method="post"> <td><input type="text" class="form-control"></td> <td> <input type="text" class="form-control"></td> <td> <input type="text" class="form-control"></td> <td><button class="btn btn-success" tabindex="-1" role="button" aria-disabled="true" id="create">Добавить</button></td> <td></td> </form> 

The question is - how can this be implemented using ajax / jquery background queries? Namely: what to add in views.py to the ProductList function so that it catches a POST request and adds the data received from the form to the database via the serializer / model?

And is it correct to use the TemplateHTMLRenderer render from django rest, in the sense that it is better than using the classic Django render?

    0