[PYTHON] Send data to DRF API with Vue.js

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

environment

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.

Data you want to register

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.

Write Vue.js

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 titleandprice`. 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: スクリーンショット 2020-03-28 15.26.17.png

Send

スクリーンショット 2020-03-28 15.46.41.png

When you press send ...

スクリーンショット 2020-03-28 15.48.11.png

It has been added.

Add a comma to the number

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>
スクリーンショット 2020-03-28 16.00.46.png

Recommended Posts

Send data to DRF API with Vue.js
How to deal with imbalanced data
How to deal with imbalanced data
How to Data Augmentation with PyTorch
[Python] Create API to send Gmail
Send images taken with ESP32-WROOM-32 to AWS (API Gateway → Lambda → S3)
How to send a request to the DMM (FANZA) API with python
Retrieving food data with Amazon API (Python)
Convert Excel data to JSON with python
Convert FX 1-minute data to 5-minute data with Python
Try converting to tidy data with pandas
How to read problem data with paiza
How to create sample CSV data with hypothesis
Send a message to LINE with Python (LINE Notify)
How to send a message to LINE with curl
Try to aggregate doujin music data with pandas
Convert data with shape (number of data, 1) to (number of data,) with numpy.
I want to analyze songs with Spotify API 2
I created a tool to correct GPS data with Mapbox Map Matching API (Mapbox Map Matching API)
[DRF + Vue.js] Error when getting API (general mistake)
I tried to save the data with discord
I want to knock 100 data sciences with Colaboratory
Get stock price data with Quandl API [Python]
Save data to flash with STM32 Nucleo Board
How to scrape horse racing data with BeautifulSoup
I want to analyze songs with Spotify API 1
[Introduction to minimize] Data analysis with SEIR model ♬
How to get article data using Qiita API
Sample to send slack notification with python lambda
Write CSV data to AWS-S3 with AWS-Lambda + Python
Send msgpack with ajax to flask (werkzeug) environment
To automatically send an email with an attachment using the Gmail API in Python
[Python] Mention to multiple people with Slack API
[First API] Try to get Qiita articles with Python
How to use xgboost: Multi-class classification with iris data
How to scrape image data from flickr with python
How to convert horizontally held data to vertically held data with pandas
Send log data from the server to Splunk Cloud
Reading Note: An Introduction to Data Analysis with Python
How to get more than 1000 data with SQLAlchemy + MySQLdb
Send data from Python to Processing via socket communication
How to extract non-missing value nan data with pandas
I tried to uncover our darkness with Chatwork API
termux × AWS Send smartphone location information to AWS with IoT
Get comments and subscribers with the YouTube Data API
How to analyze with Google Colaboratory using Kaggle API
I tried to analyze J League data with Python
Upload to a shared drive with Google Drive API V3
Input Zaim data to Amazon Elasticsearch Service with Logstash
How to operate Discord API with Python (bot registration)
Carry over data to another page (tab) with streamlit
How to extract non-missing value nan data with pandas
Data analysis with python 2
Convert 202003 to 2020-03 with pandas
Visualize data with Streamlit
Reading data with TensorFlow
Send email with Django
Data visualization with pandas
Extrude with Fusion360 API
Data manipulation with Pandas!
Shuffle data with pandas