How can Django REST Framework be used to render a list of model instances with specific fields editable by the user?
I'm a few months into Django, and only a couple days into DRF. I've tried several different approaches, but just can't seem to wrap my head around it.
Prior to using DRF, my workflow would have been to set up a view (and associated URL) that: queried my model, picked my custom form from forms.py (exposing only the fields I needed), put the two together into a dictionary, and sent it to a template.
In the template, I could then loop through my model instances and set up my editable fields, piping them through django crispy forms, as required.
I could then call this template through an AJAX get request.
models.py
class Buyer(models.Model):
name = models.CharField(unique=True, max_length = 20)
class Item(models.Model):
name = models.CharField(unique=True, max_length = 50)
active = models.BooleanField(default=True)
bought_by = models.ForeignKey(Buyer, null=True, blank=True, to_field="name",)
views.py
class ItemViewSet(viewsets.ModelViewSet):
queryset = models.Item.objects.select_related("bought_by")
serializer_class= serializers.ItemSerializer
filterset_fields = ("bought_by")
serializers.py
class ItemSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = models.Item
fields = "__all__"
extra_kwargs = {"url": {"view_name: "myapp:item-detail"}}
urls.py
router = routers.DefaultRouter()
router.register(r"items", views.ItemViewSet)
template.html
{% load static %}
{% load rest_framework %}
<table id="item_table" class="table">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Active</th>
<th scope="col">Buyer</th>
</tr>
</thead>
<tbody>
{% for item in data %}
<tr scope="row">
<td>{{ item.name }}</td>
<td>{{ item.active }}</td>
<td>{{ item.bought_by }}</td>
</tr>
{% endfor %}
</tbody>
</table>
Some Js file
function getData(){
updateRequest = $.ajax({
type: "GET",
url: "myapp/items/",
success: function(data) {
//....
}
});
}
First Approach: Customize the ListModelMixin for ItemViewSet to render the template and pass along the serializer. Something along the lines of:
def list(self,request, *args, **kwargs):
...
return Response ({'data': queryset, 'serializer': serializer}, template_name = "myapp/template.html")
then in template.html change {{ item.active }} to:
<form action="{{ item.url }}" method="post">
{% csrf_token %}
{{ render_form serializer }}
</form>
Error: serializer is not iterable. Make sense. Changed it to :
{{ render_field item.bought_by }}
Error: needs 'style', added that. continued to get other errors
Second Approach: Try to modify the ListModelMixin to collect a dictionary of serialized model instances e.g.,:
items= dict()
for item in queryset:
items[item] = serializers.ItemSerializer(item, data=request.data)
Never quite figured this out as serializers.ItemSerializer(item, data=request.data) doesn't seem to be a dictionary item and so can't use data.items() to iterate through it in the template.
Apologies for the long write up, but I'm a bit at sea and not quite sure how to proceed.
What is the most elegant DRF way of returning a list of all model instances with some fields editable (similar to how you would have in django admin with list_editable specified)?
I could always the older method, but it feels like I'm missing something obvious with DRF here.
References:
https://www.django-rest-framework.org/topics/html-and-forms/
Django Rest Framework serializers render form individually
Rendering a form with django rest framework's ModelViewSet class insead of APIView