M
M
matue892018-07-23 06:27:18
JavaScript
matue89, 2018-07-23 06:27:18

CRUD background via Django REST API?

Good afternoon.

Please help.

I am developing an application with a database of products, I started 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 a serializer in serializers.py:

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

through TemplateHTMLRenderer I generate a 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 to add the functionality of adding a product by a background POST request in the form on the generated page (without reloading the page, via 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>

Question - how can this be implemented with ajax/jquery background requests? Namely: what to add to views.py in the ProductList function so that it catches the POST request and adds the data received from the form to the database through the serializer / model?

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

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Tim, 2018-07-27
@darqsat

Will this fit?

def ProductList(request):
    if request.method == 'GET':
        queryset = Product.objects.all()
        return Response({'object_list': queryset}, template_name='products/product_list.html')
    elif request.method == 'POST':
        form = request.POST
        # ТВОЙ КОД

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question