Tumblelog by Soup.io
Newer posts are loading.
You are at the newest post.
Click here to check if anything new just came in.

May 16 2019

updated django-mptt enabled FilteredSelectMultiple m2m widget, Django 1.11 compatible

Small fix to make https://www.djangosnippets.org/snippets/1779/ compatible with Django 1.11 To use this you'll also need the javascript from https://www.djangosnippets.org/snippets/1780/

I added an overridden optgroups method that can handle the additional tuple and a couple minor things I gathered ...

May 08 2019



May 05 2019

StringField: CharField with no max_length for Postgres

Django's CharField requires a max_length, and TextField displays a multi- line widget, but in Postgres there's no reason to add an arbitrary max thanks to the varlena storage format. So this is a TextField that displays as a single line instead of a multiline TextArea.

April 30 2019

April 18 2019

Calculating Maintainability Index for a whole project

With this command you can calculate the maintainability index for your whole project.

In your settings you have to add a dictionary called RADON_MI_SETTINGS. It could be like this:

python RADON_MI_SETTINGS = { 'paths': ['projectname'], 'exclude': 'projectname/some_app/some_file.py', 'ignore': 'migrations,tests', }

I had to add following packages: radon==3.0 ...

April 17 2019

Django nginx sendfile example

Use nginx sendfile (X-Accel-Redirect) function to serve files but pass traffic through django. Can be used to serve media files only to logged-in users.

April 06 2019





this will help any url under panel/ require login.

March 28 2019

ChoiceField's choices from model

I have a product table but don't have a brand table. brands in product.brand as denormalized and I want to choose brands from a select tag.

March 04 2019


Now you can format and compress json-data in django template

February 14 2019

Tweet embed template tag

Takes a tweet url, requests the json from Twitter oEmbed, parses the json for the html element and returns it to your template. The html returned is ready to go and will be shown as a tweet on your web page. This uses the Requests library for Python. A full ...

February 05 2019

Adding Object name in Success Message

Success Message has object properties

Success Message can have an object name or the properties of the object model to collide with the message see code below

January 05 2019

Bootstrap Accordian

This is an example of Leamug web development, you can find how to add start templates designer

Collapsible accordion are useful when you want to hide and show large amount of content. If you are looking for a modern, flat and professionally designed Bootstrap accordion, then we have a best ...

December 12 2018

Different Response Data/Serializer for DRF Views/Viewsets

Mixin for Django Rest Framework View/Viewsets to use different response data/serializers without unnecessary hacks.

Just extend your DRFs view/viewset with this mixin after the DRF's APIView (sub)classes.

October 12 2018

Hand over model instance relations to another instance of the same model

If you have a model instance you want to merge into another, it's handy to hand over all the relations into the model you want to merge into, so the deletion won't trigger cascading deletions from other tables.

You can pass an Iterable of the same objects (a ...

September 11 2018

create custom permissions

create custom permissions

July 19 2018


this is a test

July 09 2018

generic 12factor manage.py for containers

Base manage.main hack which supports being an entry point.

In your project setup.py, add::

    'console_scripts': [
        'yourproject = yourproject.manage:main',

Replace your manage.py content with::

#!/usr/bin/env python
from crudlfap.manage import main

if __name__ == '__main__':

Note that it will enable DEBUG env ...

June 26 2018

Filter to shorten Natural Time

  • This is a filter to shorten the natural time value obtained using naturaltime function from humanize.

June 13 2018

Full-Stack Vue Tutorial with Django RESTful API — CRUD Using Axios with Vue

Throughout this tutorial with Vue.js and Axios we'll see how to add CRUD (Create, Read, Update and Delete) methods with a Vue front-end and a Python Django RESTful API back-end.

Axios is a promise-based modern http client library that runs on the browser and the server through Node.js. Axios works asynchronously and allows you to make HTTP calls to REST endpoints and consume REST APIs.

Using Axios with Vue

We'll use Axios to send API or HTTP calls (We'll write code for sending GET, POST, DELETE and PUT HTTP requests.) from a Vue.js interface to a RESTful API back-end built with Django.

First things first, let's get the back-end code.

Getting the Django Back-End

In this tutorial, we'll be focusing on building the Vue.js and Axios front-end so we'll be using a previously built Django API available from this GitHub repository

Using the following command, you can clone the back-end code:

$ git clone https://github.com/techiediaries/django-crm
$ cd django-crm

Next, you need to create a virtual environment and install packages using pipenv:

$ pipenv install

Next, activate the virtual environment using:

$ pipenv shell 

Finally, create and migrate the database and run the local development server using:

$ python manage.py migrate
$ python manage.py runserver

You server will be running from http://localhost:8000. You are now ready to create the Vue.js interface to communicate with the back-end using the Axios HTTP client.

Creating the Vue Front-End

Navigate inside your project and create a front-end project using the Vue CLI we've installed on the previous tutorial.

$ vue create frontend

That's it! You now have a Vue project ready.

You can serve your application using the following command:

$ vue serve

Installing Axios Http Client

The next step is to install Axios in your Vue project using the following command:

$ npm install --save axios

Consuming The RESTful API Using Axios

After installing Axios, we'll use it to consume to RESTful API exposed from http://localhost:8000.

To encapsulate all the code interfacing with REST API server we'll create a JavaScript class inside the frontend project and we'll add different methods to send API calls such as POST, GET, PUT and DELETE.

Go ahead and create APIService.js inside the frontend/src folder:

cd frontend/src
touch APIService.js

Next open APIService.js using your favorite code editor and add the following code to create the APIService class:

import axios from 'axios';
const API_URL = 'http://localhost:8000';
export class APIService{



We've imported axios, defined an API_URL variable which holds the address of the REST API server and then declared and exported the APIService class with a constructor.

We have different REST endpoints such as /api/accounts and /api/contacts etc. Let's see an example with the /api/contacts endpoint:

Example Making Http GET API Call

Let's start by getting the list of contacts using an HTTP GET request. Add the following code to the APIService.js:

getContacts() {
    const url = `${API_URL}/api/contacts/`;
    return axios.get(url).then(response => response.data);

We declared a getContacts() method which makes a GET call, using the axios.get() method, to the /api/contacts endpoint. We are taking the data part from the response and then returning a Promise, from the function, which would resolve to an array of contacts or an error.

We also need a method to get single contacts by id or primary key. Let's add a second method to APIService.js:

getContact(pk) {
    const url = `${API_URL}/api/contacts/${pk}`;
    return axios.get(url).then(response => response.data);

In the same way, the method returns a Promise which would resolve to a single contact or error.

Example Using Http GET Calls

After adding the two methods for sending GET requests to the API server, we can now call them from any Vue component.

First create a Vue components for displaying contacts. Navigate inside frontend/src/components then run the following command:

touch ListContacts.js

Open the ListContacts.js file and start by adding a template:

<h1>Contacts ()</h1>

<table class="table table-bordered table-hover">




<th>First Name</th>
<th>Last Name</th>
<th> Address </th>
<tr v-for="contact in contacts">

<th>{ { contact.pk } }</th>

<th>{ { contact.first_name } }</th>

<td>{ { contact.last_name } }</td>

<td>{ { contact.email } } </td>

<td>{ { contact.phone } }</td>

<td>{ { contact.address } }</td>


<button class="btn btn-danger" @click="deleteContact(contact)"> X</button>


We use the v-for directive to loop through the contacts array and display information about each contact in a HTML table.

Next, in the same file add the following JavaScript code:

import {APIService} from '../APIService';

const API_URL = 'http://localhost:8000';
const apiService = new APIService();

export default {

name: 'ListContacts',

components: {


data() {

return {
contacts: [],



methods: {

    apiService.getContacts().then((data) => {

        this.contacts = data.data;
        this.numberOfContacts= data.count;

mounted() {

We first declare a contacts and numberOfContacts variables in the data() method of our Vue component. Next, we add a getContacts() method which call the getContacts() of the APIService instance we created in the start of the file. When the promise resolves we assign the results to our declared variables i.e contacts and numberOfContacts. In the mounted() method of the component we call the getContacts() method so we can get contacts to display as soon as the component is mounted.

Example Making Http POST API Call

Let's now see how we can post data to our RESTful API server by sending an http POST call using Axios. Add the following method to the APIService.js class:


    const url = `${API_URL}/api/contacts/`;
    return axios.post(url,contact);

We declared a function createContact() which takes a contact object and send it via a POST request using axios.post() method. The function returns a Promise which can be resolved to success or error response.

Example Making Http PUT API Call

After implementing the http POST method , let's see the code for making an http PUT method which can be used to update data. In the APIService.js class add the following method:


    const url = `${API_URL}/api/contacts/${contact.pk}`;
    return axios.put(url,contact);

The updateContact() method makes a PUT call to the API server by using the axios.put() method.

Example Making Http DELETE API Call

Let's see how to add a method for deleting contacts. In the APIService.js class, add the following method:

    const url = `${API_URL}/api/contacts/${contact.pk}`;
    return axios.delete(url);

The deleteContact() use the axios.delete() method to send a DELETE request to the API server.


In this tutorial, we've seen how to implement CRUD (Create, Read, Update and Delete) functionality using the Axios http client with Vue and a RESTful API server.

Older posts are this way If this message doesn't go away, click anywhere on the page to continue loading posts.
Could not load more posts
Maybe Soup is currently being updated? I'll try again automatically in a few seconds...
Just a second, loading more posts...
You've reached the end.

Don't be the product, buy the product!