1564371406
As a developer, CRUD (Create-Read-Update-Delete) is one of the basic operations to know. In this tutorial, I’ll show you how to build an API with Django REST Framework and a SPA with Vue.js. I am going to show you step by step from scratch.
Take a look at the CRUD app we will build:
Django REST framework is a powerful and flexible toolkit for building Web APIs. Open your favorite command-line interface and make sure to install Pipenv. Pipenv is one of the best tools to manage Python project dependencies. alternatively, you can use CodeMix IDE for fast and smooth Vue and Python app development.
mkdir subscription-api
cd subscription-api
pipenv install --three
pipenv shell
pipenv install django
pipenv install django-rest-framework
BashCopy
Right now, we’ve installed Django
and Django REST Framework
. Let’s create a Django
project and a Django
app:
./manage.py startproject subscription-api .
./manage.py startapp subscriptions
So make sure to add subscriptions and restframework to our list of INSTALLEDAPPS
in the settings.py
file.
INSTALLED_APPS = [
‘django.contrib.admin’,
‘django.contrib.auth’,
‘django.contrib.contenttypes’,
‘django.contrib.sessions’,
‘django.contrib.messages’,
‘django.contrib.staticfiles’,
‘rest_framework’,
‘subscriptions’,
]
Our database model will contain Subscription
model only. Let’s create 6 fields:
# subscriptions/models.py
from django.db import modelsclass Subscription(models.Model):
name = models.CharField(max_length=255)
description = models.TextField()
currency = models.CharField(max_length=255)
amount = models.IntegerField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)def str(self):
return self.name
Now let’s update our database by first creating a new migration file and then applying it.
./manage.py makemigrations
./manage.py migrate
Create a serializer to convert our data into JSON format:
# subscriptions/serializers.py
from rest_framework import serializers
from .models import Subscriptionclass SubscriptionSerializer(serializers.ModelSerializer):
class Meta:
model = Subscription
fields = (‘name’, ‘description’, ‘currency’,
‘amount’, ‘created_at’, ‘updated_at’
)
Django REST Framework
provides class-based generic API views. Update the views.py
file:
# subscriptions/views.py
from .models import Subscription
from .serializers import SubscriptionSerializer
from rest_framework import genericsclass SubscriptionList(generics.ListCreateAPIView):
queryset = Subscription.objects.all()
serializer_class = SubscriptionSerializerclass SubscriptionDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Subscription.objects.all()
serializer_class = SubscriptionSerializer
Let’s add our API endpoints.
# subscription_api/urls.py
from django.contrib import admin
from django.urls import path, includeurlpatterns = [
path(‘api’, include(‘subscriptions.urls’)),
path(‘admin/’, admin.site.urls),
]
# subscriptions/urls.py
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from subscriptions import viewsurlpatterns = [
path(‘subscriptions/’, views.SubscriptionList.as_view()),
path(‘subscriptions/<int:pk>/’, views.SubscriptionDetail.as_view()),
]
Start the server.
./manage.py runserver
Your browsable API is ready.
Let’s add Cross-Origin Resource Sharing (CORS) headers to responses with django-cors-headers
:
pipenv install django-cors-headers
And then add it to your installed apps:
# subscription_api/settings.py
INSTALLED_APPS = [
…
‘corsheaders’,
…
]
You will also need to add a middleware class to listen in on responses:
# subscription_api/settings.py
MIDDLEWARE = [
…
‘corsheaders.middleware.CorsMiddleware’,
‘django.middleware.common.CommonMiddleware’,
…
]
Just allow all origins to make cross-site HTTP requests:
# subscription_api/settings.py
CORS_ORIGIN_ALLOW_ALL = True
Make sure you have the latest version of vue-cli
installed.
vue create subscription-app
cd subscription-app
yarn add axios bootstrap bootstrap-vue vee-validate
We just create a new Vue.js
project and installed:
axios
: a great HTTP client library;bootstrap
and bootstrap-vue
: a library to quickly integrate Bootstrap 4 components with Vue.js;vue-validate
: validate HTML inputs and Vue components the easy way.Inside src/components
folder, create the following Vue components:
Index.vue
Create.vue
Edit.vue
Make sure to import bootstrap
and vee-validate
in your main.js
:
// src/main.js
…
import BootstrapVue from “bootstrap-vue”;
import VeeValidate from “vee-validate”;import “bootstrap/dist/css/bootstrap.min.css”;
import “bootstrap-vue/dist/bootstrap-vue.css”;Vue.use(BootstrapVue);
Vue.use(VeeValidate);
…
Now, we need to define our routes.
import Vue from “vue”;
import Router from “vue-router”;Vue.use(Router);
export default new Router({
routes: [
{
path: “/”,
redirect: ‘/index’
},
{
path: “/create”,
name: “create”,
component: () => import(“./components/Create.vue”)
},
{
path: “/edit/:id”,
name: “edit”,
component: () => import(“./components/Edit.vue”)
},
{
path: “/index”,
name: “index”,
component: () => import(“./components/Index.vue”)
},
]
});
Each route should map to a component we created. We created a redirection to redirect from /to
/index
.
The next step should be to define a router view in App.vue
file.
Index.vue
So the first file called will be Index.vue
. This component will display all subscriptions.
Let’s explain this deeper. We need to get all subscriptions from our API. Create a property called susbscriptions
:
…
data() {
return {
subscriptions: []
}
},
…
Create a method which gets all subscriptions
from server with axios
:
…
all: function () {
axios.get(‘http://127.0.0.1:8000/api/subscriptions/’)
.then( response => {
this.subscriptions = response.data
});
}
…
Call method
when Index
component is created:
…
created() {
this.all();
},
…
The Index
template part is just a Bootstrap
card component with a for-loop
.
We create a delete button into the template.
<button
class=“btn btn-danger btn-sm ml-1”
v-on:click=“deleteSubscription(subscription)”>
Delete
</button>
deleteSubscription
is called when the button is clicked.
deleteSubscription: function(subscr) {
if (confirm('Delete ’ + subscr.name)) {
axios.delete(http://127.0.0.1:8000/api/subscriptions/${subscr.id}
)
.then( response => {
this.all();
});
}
},
This method will call your API after you confirm the deletion.
Create.vue
This file will create and store a subscription. We’ll use vee-validate
which is a template based validation library.
We create a property called subscription
and a boolean called submitted
:
…
subscription: {
name: ‘’,
currency: ‘’,
amount: ‘’,
description: ‘’,
},
submitted: false
…
All we need is to add the v-validate directive to the input we wish to validate. Like below:
<input
type=“text”
class=“form-control”
id=“name”
v-model=“subscription.name”
v-validate=“‘required’”
name=“name”
placeholder=“Enter name”>
The CSS class we bind is just a Bootstrap 4
HTML5 form validation hint wich display invalid-feedback
block.
<input
…
:class=“{
‘is-invalid’:
errors.has(‘subscription.name’)
&& submitted}”>
So let’s store our subscription.
create: function (e) {
this.$validator.validate().then(result => {
this.submitted = true;
if (!result) {
return;
}
axios
.post(‘http://127.0.0.1:8000/api/subscriptions/’,
this.subscription
)
.then(response => {
this.$router.push(‘/’);
})
});
}
We make a HTTP
request and return to /
path when everything works.
Edit.vue
When the Edit.vue
component is loaded, then we fetch the subscription data from the database and then display it inside the same form we used in Create.vue
.
I hope this is helpful to you. You can check out the subscription-app repo.
Originally published by Junior Gantin at dunebook.com
==================================
Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter
☞ Nuxt.js - Vue.js on Steroids
☞ Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
☞ Python and Django Full Stack Web Developer Bootcamp
☞ Django 2.1 & Python | The Ultimate Web Development Bootcamp
☞ Master Vuejs from scratch (incl Vuex, Vue Router)
☞ Vue JS 2.0 - Mastering Web Apps
☞ Vue.js Essentials - 3 Course Bundle
☞ MEVP Stack Vue JS 2 Course: MySQL + Express.js + Vue.js +PHP
☞ Python eCommerce | Build a Django eCommerce Web Application
☞ Python Django Dev To Deployment
☞ The Complete JavaScript Course 2019: Build Real Projects!
☞ JavaScript: Understanding the Weird Parts
☞ The Modern JavaScript Bootcamp (2019)
#vue-js #django #javascript #web-development
1573871423
Thanks!
1620177818
Welcome to my blog , hey everyone in this article you learn how to customize the Django app and view in the article you will know how to register and unregister models from the admin view how to add filtering how to add a custom input field, and a button that triggers an action on all objects and even how to change the look of your app and page using the Django suit package let’s get started.
#django #create super user django #customize django admin dashboard #django admin #django admin custom field display #django admin customization #django admin full customization #django admin interface #django admin register all models #django customization
1620185280
Welcome to my blog, hey everyone in this article we are going to be working with queries in Django so for any web app that you build your going to want to write a query so you can retrieve information from your database so in this article I’ll be showing you all the different ways that you can write queries and it should cover about 90% of the cases that you’ll have when you’re writing your code the other 10% depend on your specific use case you may have to get more complicated but for the most part what I cover in this article should be able to help you so let’s start with the model that I have I’ve already created it.
**Read More : **How to make Chatbot in Python.
Read More : Django Admin Full Customization step by step
let’s just get into this diagram that I made so in here:
Describe each parameter in Django querset
we’re making a simple query for the myModel table so we want to pull out all the information in the database so we have this variable which is gonna hold a return value and we have our myModel models so this is simply the myModel model name so whatever you named your model just make sure you specify that and we’re gonna access the objects attribute once we get that object’s attribute we can simply use the all method and this will return all the information in the database so we’re gonna start with all and then we will go into getting single items filtering that data and go to our command prompt.
Here and we’ll actually start making our queries from here to do this let’s just go ahead and run** Python manage.py shell** and I am in my project file so make sure you’re in there when you start and what this does is it gives us an interactive shell to actually start working with our data so this is a lot like the Python shell but because we did manage.py it allows us to do things a Django way and actually query our database now open up the command prompt and let’s go ahead and start making our first queries.
#django #django model queries #django orm #django queries #django query #model django query #model query #query with django
1624096385
In the video below, we take a closer look at the Spring Boot CRUD Operations example with exception handling. Let’s get started!
#spring boot #spring boot tutorial for beginners #crud #crud #crud #spring boot crud operations
1572860016
This Python Django tutorial will help you learn what is django web development & application, what is django and introduction to django framework, how to install django and start programming, how to create a django project and how to build django app. There is a short django project as well to master this python django framework.
Why should you watch this Django tutorial?
You can learn Django much faster than any other programming language and this Django tutorial helps you do just that. Our Django tutorial has been created with extensive inputs from the industry so that you can learn Django and apply it for real world scenarios.
#Python Django Tutorial #Django Course #Python Django Training #Python Django Course #intellipaat
1624418760
See how to create a weather app in Django that gets the current weathers for multiple cities. This tutorial uses Python Requests to call the Open Weather Map API.
📺 The video in this post was made by freeCodeCamp.org
The origin of the article: https://www.youtube.com/watch?v=qCQGV7F7CUc&list=PLWKjhJtqVAbnqBxcdjVGgT3uVR10bzTEB&index=15
🔥 If you’re a beginner. I believe the article below will be useful to you ☞ What You Should Know Before Investing in Cryptocurrency - For Beginner
⭐ ⭐ ⭐The project is of interest to the community. Join to Get free ‘GEEK coin’ (GEEKCASH coin)!
☞ **-----CLICK HERE-----**⭐ ⭐ ⭐
Thanks for visiting and watching! Please don’t forget to leave a like, comment and share!
#weather app #django #python #weather app - django tutorial (using python requests) #using python requests #django tutorial