Tag Archives: django-rest-framework

Install vue or update it.
sudo npm install -g @vue/cli

Or, update it:

sudo npm update -g @vue/cl

Install vue addon for rapid prototyping:

npm install -g @vue/cli @vue/cli-service-global

In the django project’s root,

vue create vueapp


(venv) [email protected]:~/emr$ vue create vueapp

Vue CLI v4.5.13
? Please pick a preset: Default (Vue 3) ([Vue 3] babel, eslint)

Vue CLI v4.5.13
✨  Creating project in /home/joel/emr/vueapp.
⚙️  Installing CLI plugins. This might take a while...

yarn install v1.22.5
info No lockfile found.
[1/4] Resolving packages...
[2/4] Fetching packages...
info [email protected]: The platform "linux" is incompatible with this module.
info "[email protected]" is an optional dependency and failed compatibility check. Excluding it from installation.
info [email protected]: The platform "linux" is incompatible with this module.
info "[email protected]" is an optional dependency and failed compatibility check. Excluding it from installation.

success Saved lockfile.
Done in 21.95s.
🚀  Invoking generators...
📦  Installing additional dependencies...

yarn install v1.22.5
[1/4] Resolving packages...
[2/4] Fetching packages...
info [email protected]: The platform "linux" is incompatible with this module.
info "[email protected]" is an optional dependency and failed compatibility check. Excluding it from installation.
info [email protected]: The platform "linux" is incompatible with this module.
info "[email protected]" is an optional dependency and failed compatibility check. Excluding it from installation.
[3/4] Linking dependencies...
[4/4] Building fresh packages...

success Saved lockfile.
Done in 17.94s.
⚓  Running completion hooks...

📄  Generating README.md...

🎉  Successfully created project vueapp.
👉  Get started with the following commands:

 $ cd vueapp
 $ yarn serve

As suggested, type:

cd vueapp
yarn serve


(venv) [email protected]:~/emr$ cd vueapp/
(venv) [email protected]:~/emr/vueapp$ yarn serve
yarn run v1.22.5
$ vue-cli-service serve
 INFO  Starting development server...
98% after emitting CopyPlugin
 DONE  Compiled successfully in 2018ms                                                                                                                                                                    1:45:07 AM

  App running at:
  - Local:   http://localhost:8080/ 
  - Network:

  Note that the development build is not optimized.
  To create a production build, run yarn build.

Now we can see the default Vue app at http://localhost:8080/

Folder structure:

[email protected]:~/emr/vueapp$ tree -L 1
├── babel.config.js
├── node_modules
├── package.json
├── public
├── README.md
├── src
└── yarn.lock

[email protected]:~/emr/vueapp$ tree -L 2 src/
├── App.vue
├── assets
│   └── logo.png
├── components
│   └── HelloWorld.vue
└── main.js

Thus we can see that our Vue files are in the src subfolder, and that main.js has to load first.

Open VS code in this folder

code .

Contents of main.js:

import { createApp } from 'vue'
import App from './App.vue'


Setup django static files by following the official tutorial.

Next, move the vueapp directory to a location under static directory list. For me, I did:

mv vueapp shorten/static/shorten/

where shorten is the name of my app, and my static setting is this, in settings.py:

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = "/static/"


Now, load the javascript files in our template.

{% load static %}
<script type="text/javascript" src="{% static 'src/vue/dist/js/chunk-vendors.js' %}"></script>
<script type="text/javascript" src="{% static 'src/vue/dist/js/app.js' %}"></script>

Now we can start both the django server and the vue server and test.

From the django project folder run

./manage.py runserver

And from the vueapp folder, run

yarn serve

If it worked, we can see the Vue code working inside the “app” element.

To serve to production, run:

yarn build
(venv) [email protected]:~/emr/vueapp$ yarn build
yarn build
yarn run v1.22.5
$ vue-cli-service build
⠦  Building for production...
 DONE  Compiled successfully in 5322ms                                                                                                                                                                    2:31:05 AM
  File                                      Size                                                                               Gzipped
  ../../src/vue/dist/js/chunk-vendors.js    147.13 KiB                                                                         52.86 KiB
  ../../src/vue/dist/js/app.js              4.53 KiB                                                                           1.62 KiB
  ../../src/vue/dist/css/app.css            0.33 KiB                                                                           0.23 KiB
  Images and other types of assets omitted.
 DONE  Build complete. The ../../src/vue/dist directory is ready to be deployed.
 INFO  Check out deployment instructions at https://cli.vuejs.org/guide/deployment.html
Done in 7.60s.
(venv) [email protected]:~/emr/vueapp$ 

Now we can run collectstatic to collect all our static resources.

(venv) [email protected]:~/emr$ ./manage.py collectstatic

You have requested to collect static files at the destination
location as specified in your settings:


This will overwrite existing files!
Are you sure you want to do this?

Type 'yes' to continue, or 'no' to cancel: yes

60 static files copied to '/home/joel/emr/staticfiles', 25208 unmodified, 48311 post-processed.

Now, try running the server again

Note that `yarn build` must be built each time code is changed in debug too..


  1. Better Programming Blog Visit the blog for details.

Scenario: I have Flutter as front end, and django as back end. django-rest-framework is used for managing the API. I have a dataset of customer profile details, which needs to be edited. So from the flutter front end, this data is passed to the backend, which updates the data, and sends a successful message.

My model:

class customer(models.Model):
    # Need autoincrement, unique and primary
    cstid = models.AutoField(primary_key=True, unique=True)
    date_of_registration = models.DateField(default=timezone.now)
    insurance_number = models.CharField(max_length=100, blank=True, null=True)
    name = models.CharField(max_length=35, blank=False)
    ageyrs = models.IntegerField(blank=True)
    agemnths = models.IntegerField(blank=True)
    dob = models.DateField(null=True, blank=True)

I write an APIView, as described in the documentation:

class UpdateCustomerDetail(APIView):
    Retrieve, update or delete a snippet instance.
    For details, refer: https://www.django-rest-framework.org/tutorial/3-class-based-views/
    print("In UpdateCustomerDetail")

    def get_object(self, pk):
            return customer.objects.get(pk=pk)
        except customer.DoesNotExist:
            raise Http404

    def get(self, request, pk, format=None):
        snippet = self.get_object(pk)
        serializer = customerSerializer(snippet)
        return Response(serializer.data)

    def patch(self, request, pk, format=None):
        cst = self.get_object(pk)
        print("request.data:", request.data)
        customer_data = json.loads(request.data['customer'])
        serializer = customerSerializer(cst, data=customer_data)
        if serializer.is_valid():
            print("Serializer is valid")
            return Response(serializer.data)
            print("Serializer is NOT valid")
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk, format=None):
        snippet = self.get_object(pk)
        return Response(status=status.HTTP_204_NO_CONTENT)

Now, add a url for it:

    path('update_customer_new/<int:pk>/', views.UpdateCustomerDetail.as_view(),

So, what we are doing, is to pass the pk (which never changes), along with the JSON of a representation, of the model, here, customer, to django.

I am using it from Flutter., So I call the url: /api/update_customer_new/5/

The Flutter code is as follows:

  Future updateCustomerNew({
    int clinicID,
    Customer customer,
  }) async {
    print("In Network::updateCustomer");
    String basicAuth =
        'Basic ' + base64Encode(utf8.encode('$userName:$passWord'));
    int cstID = customer.cstid;
    var response = await http.patch(
      headers: <String, String>{
        'Content-Type': 'application/json; charset=UTF-8',
        'authorization': basicAuth,
      body: jsonEncode(<String, String>{
        'clinicID': clinicID.toString(),
        'customer': jsonEncode(customer),
    print("Sending: ${jsonEncode(customer)}");
    print('Response status: ${response.statusCode}');
    return response.body;

So, django gets the pk, as part of the url, and the data as json. It then calls the APIView, which passes the request to the patch method. The object is retrieved by its pk, so we can update any or all fields on it.