How to Pass a django model to vue.js
To pass a Django model to Vue.js, you can create an API endpoint using Django's built-in views or a third-party library like Django REST Framework, and then use Vue.js to make an HTTP request to fetch the data from the API endpoint.
Here are the basic steps to follow:
- Define a Django model that you want to pass to Vue.js. For example:
pythonfrom django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
publication_date = models.DateField()
description = models.TextField()
- Create a Django view that returns the model data in JSON format. You can use Django REST Framework to make this process easier. For example:
pythonfrom rest_framework import serializers, viewsets
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = '__all__'
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer
- Add a URL route to your Django application that maps to the view. For example:
pythonfrom django.urls import path, include
from rest_framework import routers
router = routers.DefaultRouter()
router.register(r'books', BookViewSet)
urlpatterns = [
path('', include(router.urls)),
]
- In your Vue.js application, use the Axios library to make an HTTP request to the API endpoint and fetch the data. For example:
javascriptimport axios from 'axios';
export default {
data() {
return {
books: []
};
},
mounted() {
axios.get('/api/books/')
.then(response => {
this.books = response.data;
})
.catch(error => {
console.log(error);
});
}
}
- Finally, you can use the data from the Django model in your Vue.js templates to display the information as desired. For example:
html<template>
<div>
<ul>
<li v-for="book in books" :key="book.id">
<h2>{{ book.title }}</h2>
<p>Author: {{ book.author }}</p>
<p>Publication Date: {{ book.publication_date }}</p>
<p>Description: {{ book.description }}</p>
</li>
</ul>
</div>
</template>