Retrieve data from django-rest to show in a form

Viewed 401

I have two classes linked with a ForeignKey. My first class is "Categories", with "ID" and "Name" properties. The second class is "Documents", with "ID", "Title" and "User" properties, the last one is linked with a category defined in the first class.

I'm developing the front-end based on Vue, so I want to know how to retrieve data from django-rest to show it in a form. For example, when a user adds a new doc, he must choose between all category options. Note that categories will be common to all documents.

Example: Categories = [{"ID": 0, "Name "Sports"}, {"ID": 1, "Name": "Music"}]

Form to add a new document:

Title: XXXX

Category:
Sports,
Music

models.py


from django.db import models

class Category(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=200)

class Documents(models.Model):
    id = models.AutoField(primary_key=True)
    title= models.CharField(max_length=200)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)

I think that if I get a answer like below it will resolve my problem.

["docs": 
     [{"ID": 1, "Title": "Doc1", "Category": Sports}, 
     {"ID": 2, "Title": "Doc2", "Category": Music}], 
 "categories": 
     [{"ID": 0, "Name: "Sports"}, 
     {"ID": 1, "Name": "Music"}]
3 Answers

No Idea about Vue, but you could just get all your categories with a GET request, then populate a dropdown Menu with those categories as options and get the value of the dropdown on submitting.

You could make a separated request to get all the category before you create the form.

To do this, you need to create a CategorySerializer and a ListCategoryProvider

class CategorySerializer(serializers.ModelSerializer):

    class Meta:
        model = Category
        fields = {'name'}

class ListCategoryProvider(generics.ListAPIView):
    serializer_class = CategorySerializer

    def get_queryset(self):
        queryset = Category.objects.all()
        return queryset

Then you need to parse the JSON containing all the categories names, to display them in your form

1) write a serializer in the Django rest for category and document. Please go through the link for serializer https://www.django-rest-framework.org/api-guide/serializers/

2) write a form in html where you can insert the document. In the javascript(vue), you can call ajax request(get request) for the category and display the category's in select options.

Related