Answer the question
In order to leave comments, you need to log in
How to render Vue components using data from the database?
Good day
To begin with, I would like to say that I am completely new to both django and vue.
I have the following task: I have implemented a backend, I need to write a frontend.
There are records in the database (the default in Django is SQLite), they need to be displayed. Records are component entities (Messages). That is, I need to display messages from the database and render it all (using vue). Moreover, it is necessary to display new messages every 10 seconds.
What is implemented in the backend:
There is a database of records, there is a message model (Message), there is a serializer, there is a view.
I think it would be appropriate to show the view code and urls, because this is the key point.
views:
from rest_framework import viewsets
from .models import Message
from .serializers import MessageSerializer
from rest_framework.views import APIView
from rest_framework.response import Response
# REST'full
class MessageViewSet(APIView):
# queryset = Message.objects.all().order_by('-created_at')
# serializer_class = MessageSerializer
def get(sefl, request):
messages = Message.objects.all()
serializer = MessageSerializer(messages, many=True)
return Response(serializer.data)
def post(sefl):
pass
def index(request):
return render(request, 'webapp/index.html', {})
from django.conf.urls import url, include
# from .views import index
#from .views import MessageViewSet
#urlpatterns = [
# url(r'^$', views.index, name='index'),
# Test api
# url(r'^api/test', views.test_api, name='test_api'),
#]
from rest_framework import routers
from .views import MessageViewSet
# Создаем router и регистрируем наш ViewSet
router = routers.DefaultRouter()
router.register(r'message', MessageViewSet)
# URLs настраиваются автоматически роутером
urlpatterns = [
url(r'^$', MessageViewSet, name='message'),
# url(r'^api/test', views.test_api, name='test_api')
]
urlpatterns += router.urls
from django.conf.urls import url, include
from django.contrib import admin
from rest_framework.urlpatterns import format_suffix_patterns
from webapp import views
urlpatterns = [
# url(r'^$', include('webapp.urls')),
# url(r'^api/v1/', include('webapp.urls')),
url(r'^admin/', admin.site.urls),
url(r'^message/', views.MessageViewSet.as_view())
]
urlpatterns = format_suffix_patterns(urlpatterns)
from rest_framework import serializers
from .models import Message
class MessageSerializer(serializers.ModelSerializer):
class Meta:
model = Message
fields = ('id', 'text', 'readed')
http://127.0.0.1:8000/message/
, this url is processed and a JSON representation of the records in the database is returned. For example:[
{
"id": 1,
"text": "First message.",
"readed": false
}
]
<template>
<div class="message">
<b-card class="mb-2">
<p class="card-text">{{data.text}}</p>
<p>{{data.msg_date}}</p>
<b-button @click="readed">Прочитано</b-button>
</b-card>
</div>
</template>
<script>
import axios from 'axios'
export default {
name: 'message',
data () {
return {
data: {},
}
},
methods: {
readed: function() {
console.log('Message readed')
// ?...
}
}
}
</script>
<style scoped>
</style>
<template>
<div class="messages">
<message
v-for='message in messages'
v-bind:key="message.id"
></message>
</div>
</template>
<script>
import axios from 'axios'
import Message from './Message'
export default {
name: 'messages',
data () {
return {
messages: [1],
data: {}
}
},
mounted () {
this.get_messages()
},
methods: {
// FIXME:
get_messages: function(){
this.intervalid1 = setInterval(() => {
console.log('get')
this.messages.push('3')
axios.get(????)
.then((responce) => {
this.data = responce.data
})
.catch((error) => {
console.log(error)
})
}, 10000)
}
},
components: {
Message
}
}
</script>
<style scoped>
</style>
Answer the question
In order to leave comments, you need to log in
Try to understand vuex
I have an idea what:
- actions to receive data are registered in vuex
- commit to save data
- getters to receive data
from the .vue component, refer to actions vuex
further in this.YourObject, enter data using getters,
then write data () {YourObject: this.YourObject}
everything, logically you got the newest data. And then output to html using v-for
In axios, you must specify the full URL for which you want to get the data. In your case it is " 127.0.0.1:8000/message "
I understand that you have front and backend on different servers. In order for Vue to receive data on the backend, you need to use the django-cors-headers library for cross-domain requests. Without this, django won't give the data
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question