[PYTHON] CRUD POST with Nuxt & Django REST Framework

Overview

Front: Nuxt Backend: Django REST Framework (DRF) When I launched a new project etc. in, it became troublesome to check the settings etc. one by one, so I will summarize it.

However, writing only the configuration file is not enough as an article personally.

So, I plan to write up to the point of implementing membership registration by hitting the API, which is the basic operation, to perform CRUD. This time, DB uses SQLite. If you want to use another RDB such as PostgreSQL or MySQL, just rewrite the DB settings on the DRF side, so please make those settings yourself.

For the time being, in this article, I hit the API created by DRF from Nuxt and POST the contents entered in the form to the database.

The source code can be found at here, so if you have any questions, please take a look.

You can also answer by asking Twitter or in the comments section of this article if you have any questions.

Last time CRUD GET with Nuxt & Django REST Framework ②

Update location

Back end

POST is not possible because the view required for DRF up to the last time and the url are not written.

The reason for doing so is to allow only GET, the process of receiving information. The reason for doing so is that when considering an app that can be used practically, it is easier to manage and set permissions if it is divided. For example, with recent web applications, you can get information without registering as a member, but in most cases you can not do POST without registering as a member, and such authority is separated. But above all, there are scary people in the world, so it is important to prevent them from being abused.

So this time, I will start by adding to view and url.

views.py


......
#add to
class ItemCreateView(generics.CreateAPIView):
    serializer_class = ItemSerializer
    queryset = Item.objects.all()

urls.py


......
#add to
path('items/add',ItemCreateView.as_view()),

Well, by doing this

http://localhost:8000/api/items/add

When you access, you can now POST as follows.

スクリーンショット 2020-05-14 19.18.35.png

This is the only addition on the DRF side! It is wonderful.

Let's move on to the front end.

front end

Here you need to create a form and add a page for POST.

So I wrote a simple form. Also, regarding the logic, I wrote it according to the basic grammar of axios.

addItem.vue


<template>
<v-card
    light
    :loading="isUpdating"
  >
    <div id="app">
    <v-app id="inspire">
    <v-form @submit.prevent="submitItem">
      <v-container>
        <v-row>
          <v-col
            cols="12"
            md="4"
          >
            <v-text-field
              v-model="item.name"
              label="Product name"
              required
            ></v-text-field>
          </v-col>
  
          <v-col
            cols="12"
            md="4"
          >
            <v-text-field
              v-model="item.category"
              :counter="10"
              label="Category"
              required
            ></v-text-field>
          </v-col>
  
          <v-col
            cols="12"
            md="4"
          >
            <v-text-field
              v-model="item.price"
              label="price"
              required
            ></v-text-field>
          </v-col>
          
          <v-col
            cols="12"
            md="4"
          >
            <v-text-field
              v-model="item.description"
              label="Description of item"
              required
            ></v-text-field>
          </v-col>
          <v-col
            cols="12"
            md="4"
          >
           <v-file-input
           v-model="item.image"
           label="Product image"
           filled
           prepend-icon="mdi-camera"
           ></v-file-input>
          </v-col>
          <v-card-actions>
      <v-spacer />
      <v-btn
        class="btn-primary"
        :loading="isUpdating"
        color="primary"
        depressed
        @click="isUpdating = true"
        type="submit"
      >
        <v-icon left>
          mdi-post
        </v-icon>
Add product
      </v-btn>
    </v-card-actions>
        </v-row>
      </v-container>
    </v-form>
  </v-app>
</div>
</v-card>
</template>

<script>
export default {
  data () {
    return {
      item: {
        name: '',
        category: '',
        image: '',
        price: '',
        description: '',
      },
      preview: '',
      autoUpdate: true,
      isUpdating: false,
      title: 'Product addition',
  }
  },
  watch: {
    isUpdating (val) {
      if (val) {
        setTimeout(() => (this.isUpdating = false), 3000)
      }
    }
  },
  methods: {
    createImage (file) {
      const reader = new FileReader()
      const vm = this
      reader.onload = (e) => {
        vm.preview = e.target.result
      }
      reader.readAsDataURL(file)
    },
    async submitItem () {
      const editeditem = this.item
       //if (editeditem.image.includes('http://)') !== -1) {
        //delete editeditem.image
      //}
      const config = {
        headers: { 'content-type': 'multipart/form-data' }
      }
      const formData = new FormData()
      for (const data in editeditem) {
        formData.append(data, editeditem[data])
      }
      try {
        const response = await this.$axios.$post('/items/add', formData, config) // eslint-disable-line
        this.$router.push('/items')
      } catch (e) {
        console.log(e)
      }
    }
  }
}
</script>

スクリーンショット 2020-05-15 8.56.48.png

A form like this will come out. And if you fill in these fields and send ...

スクリーンショット 2020-05-15 8.58.22.png

It has been added successfully.

I thought I was writing it, but if I learn and write it, it will work, so I personally think that it is important to read the document about axios firmly.

I personally recommend [axios] Installation and easy usage of axios it's here.

This article is very easy to understand and is worth reading.

~~ I think that development can be done very smoothly if CRUD and membership registration manuals are created, so next time I will write about how to correct information and delete, that is, PUT and DELETE. ~~

I have written CRUD PUT, DELETE with Nuxt & Django REST Framework

Recommended Posts

CRUD POST with Nuxt & Django REST Framework
CRUD GET with Nuxt & Django REST Framework ②
CRUD GET with Nuxt & Django REST Framework ①
Django REST framework with Vue.js
Login with django rest framework
[Django] Use MessagePack with Django REST framework
CRUD with Django
Implementation of CRUD using REST API with Python + Django Rest framework + igGrid
Django REST framework basics
Django Rest Framework Tips
Implementing authentication in Django REST Framework with djoser
Create a Todo app with Django REST Framework + Angular
More new user authentication methods with Django REST Framework
Create a Todo app with the Django REST framework
Create APIs around user authentication with Django REST Framework
How to automatically generate API document with Django REST framework & POST from document screen
When you want to filter with Django REST framework
Django REST framework stumbling block
Implement hierarchical URLs with drf-nested-routers in Django REST framework
Create a REST API to operate dynamodb with the Django REST Framework
Logical deletion in Django, DRF (Django REST Framework)
Understand the benefits of the Django Rest Framework
Miscellaneous notes about the Django REST framework
Django REST Framework + Clean Architecture Design Consideration
How to deal with garbled characters in json of Django REST Framework
Generate and post dummy image data with Django
Internationalization with django
Django REST framework A little useful to know.
Implement JWT login functionality in Django REST framework
Sometimes you want to access View information from Serializer with DRF (Django REST Framework)
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 1 ~
List method for nested resources in Django REST framework
Implement APIs at explosive speed using Django REST Framework
[Django Rest Framework] Customize the filter function using Django-Filter
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 2 ~
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 3 ~
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 4 ~
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 5 ~
Django 1.11 started with Python3.6
Development digest with Django
Django python web framework
Output PDF with Django
Markdown output with Django
Use Gentelella with django
Twitter OAuth with Django
Getting Started with Django 1
Send email with Django
File upload with django
Use LESS with Django
Pooling mechanize with Django
Use MySQL with Django
Start today with Django
Getting Started with Django 2
How to write custom validations in the Django REST Framework
Eliminate errors that occur when using Django REST Swagger with Django 3.0
The first API to make with python Djnago REST framework
How to reset password via API using Django rest framework
Django rest framework decorators ʻaction decorator replaces list_route and detail_route`
[Django] Redirect to previous page after submitting with POST form