I want to send data by POST to the API created in the following article and register it in the database. I want to access the api created by DRF from Vue.js of Jsfiddle
book/models.py
from django.db import models
import uuid
from django.utils import timezone
# Create your models here.
class Book(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
title = models.CharField(verbose_name='title', max_length=50)
price = models.IntegerField(verbose_name='price')
created_at = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.title
Also, Vue.js is listed on jsfiddle.
I want to register the title field and price field as new data in the Book table. id and created_at are added automatically, so you can go through.
html
<div id="app">
<div>
<h1>GET</h1>
<p>title: {{ results[1].title }}</p><hr>
</div>
<div>
<h1>POST</h1>
<h2>title: {{ title }}</h2>
<h2>¥{{ price }}</h2>
<input v-model='title'>
<input v-model='price'>
<button v-on:click='postBook'>Send</button>
</div>
</div>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
javascript
new Vue({
el: '#app',
data: {
results: [],
title: '',
price: '',
},
methods:{
postBook: function(){
console.log('Hello')
axios.post('http://127.0.0.1:8000/apiv1/book/',
{ title : this.title , price : this.price })
}
},
mounted() {
axios.get('http://127.0.0.1:8000/apiv1/book/')
.then(response => {this.results = response.data})
},
})
Use the v-model directive in the ʻinput tag to set the
titleand
price`.
Define a data object with the same name in your Vue instance and leave it empty.
Register postBook
in methods. Use the v-on directive for the button tag
to register it.
In the postBook
method, ʻaxios.post ('endpoint of list screen', {field name: data, field name: data})` is set, and the field and the data for it are POSTed.
So far:
When you press send ...
It has been added.
If you want to add a comma when displaying the price, create a filter in the Vue instance and apply the filter to the mustache of the template you want to apply with pipe = |
.
vue instance
filters: {
comma(value) {
if (!value) return ''
value = value.toString()
return value.replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
}
}
html
<h2>¥{{ price | comma }}</h2>
Recommended Posts