Category Archives: django

Install vue or update it.
Install:
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

Output:

(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

Output:

(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: http://192.168.29.135:8080/

  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/
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'

createApp(App).mount('#app')

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/"

INSTALLED_APPS = [
    ...
    "django.contrib.staticfiles",
    ...
]

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:

    /home/joel/emr/staticfiles

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..

References:

  1. Better Programming Blog Visit the blog for details.

The types of available authentication include:

  • BasicAuthentication: This class provides an HTTP basic authentication against a username and a password.
  • SessionAuthentication: This class works with Django’s session framework for authentication.
  • TokenAuthentication: This class provides a simple token-based authentication. The request must include the token generated for a user as the value for the Authorization HTTP header key with the 'Token ' string as a prefix for the token.

We shouldn’t use an HTTP basic authentication or a simple token-based authentication over plain HTTP in a production environment.

Permissions use the authentication information included in the request.user and request.auth attributes to determine whether the request should be granted or denied access. Permissions allow us to control which types of users will be granted or denied access to the different features, methods, resources, or resource collections of our RESTful Web Service.

Install DRF:

Enter your virtualenv

cd project
. venv/bin/activate

Install DRF:

pip3 install install djangorestframework

Now in settings.py, add to INSTALLED_APPS:

INSTALLED_APPS = [
    ...
    'rest_framework',
    'rest_framework.authtoken',     # Token authentication 
]

Also add an object:

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10,
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ],
    'DEFAULT_AUTHENTICATION_CLASSES': (        
        'rest_framework.authentication.TokenAuthentication',       
    ),
    'DEFAULT_FILTER_BACKENDS': ( 
        'django_filters.rest_framework.DjangoFilterBackend', 
        'rest_framework.filters.OrderingFilter', 
        'rest_framework.filters.SearchFilter', 
        ), 
}

Apply any necessary migrations with:

./manage.py migrate

My models.py:

from django.db import models
from django.utils import timezone

# Create your models here.
class ShortLink(models.Model):
    id = models.AutoField(primary_key=True, unique=True)
    short_link = models.CharField(max_length=15, unique=True)
    long_link = models.CharField(max_length=500, unique=True)
    created_at = models.DateTimeField(default=timezone.now)
    modified_at = models.DateTimeField(default=timezone.now)
    owner = models.ForeignKey( 
        'auth.User',  
        related_name='shortlinks', 
        on_delete=models.CASCADE) 

    def __str__(self):
        return self.short_link

In urls.py:

from django.urls import include, path
from rest_framework import routers
from rest_framework.authtoken.views import obtain_auth_token
from . import views

router = routers.DefaultRouter()

urlpatterns = [
    path('', include(router.urls)),
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
    path('api-token-auth/', obtain_auth_token, name='api_token_auth'),  
    ]

Add your Serializer to serializers.py:

from django.db import models
from rest_framework import serializers
from shorten.models import ShortLink

class ShortLinkSerializer(serializers.ModelSerializer):
    class Meta:
        model = ShortLink
        fields = [
            'id', 
            'short_link', 
            'long_link', 
            'created_at', 
            'modified_at',
        ]

Add your view to views.py:

from django.shortcuts import render
from rest_framework import viewsets
from shorten.models import ShortLink
from .serializers import ShortLinkSerializer

# Create your views here.
class ShortLinkViewSet(viewsets.ModelViewSet):
    queryset = ShortLink.objects.all()
    serializer_class = ShortLinkSerializer