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

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

entry_points={
    'console_scripts': [
        'yourproject = yourproject.manage:main',
    ],
}

Replace your manage.py content with::

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

if __name__ == '__main__':
    main('yourproject.settings')

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{

constructor(){
}

}

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:

<template>
<div>
<h1>Contacts ()</h1>


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

<thead>

<tr>

<th>#</th>

<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Phone</th>
<th> Address </th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<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>

<td>

<button class="btn btn-danger" @click="deleteContact(contact)"> X</button>
</td>
</tr>
</tbody>
</table>
<div>
</div>
</div>

</template>

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:

<script>
import {APIService} from '../APIService';

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

export default {

name: 'ListContacts',

components: {

},

data() {

return {
contacts: [],
numberOfContacts:0,

};

},

methods: {

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

        this.contacts = data.data;
        this.numberOfContacts= data.count;
    });
},
},

mounted() {
this.getContacts();
},
}
</script>

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:

createContact(contact){

    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:

updateContact(contact){

    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:

deleteContact(contact){
    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.

Conclusion

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.

Vue Tutorial with Django RESTful API — Vue CLI 3 Tutorial In Depth

Throughout this Vue tutorial with Django RESTful API, we are going to learn to use the Vue CLI v3 (In beta — 3.0.0-beta.15 as of this writing) to generate our Vue front-end application.

In this tutorial, we're going to see:

  • How to install the latest version of Vue CLI — version 3
  • How to use various features of the Vue CLI v3
  • How to use the Vue CLI v3 to create a front-end
  • How to set environment variables for development and production
  • How to add a proxy to forward API calls
  • How to install and add Vue CLI plugins manually etc.

The Vue CLI v3 provides a new experience to developers as it allows you to easily generate new Vue projects with zero initial configuration but once your project needs more control you have the possibility to add more configuration options using plugins. Unlike create-react-app, you can customize your configuration without ejecting but only via Vue CLI plugins.

The Vue CLI v3 is a complete tooling system that provides many features, out of the box, such as:

  • Interactive project scaffolding via @vue/cli.
  • Zero configuration rapid prototyping via @vue/cli and @vue/cli-service-global.
  • A runtime dependency (@vue/cli-service) that provides many features: It's upgradeable, built on top of webpack, has sensible defaults, configurable via in-project config file, extensible via plugins etc.
  • Official plugins to support using powerful existing tools in the front-end ecosystem. So you don't need to eject webpack in order to customize your project's configuration.

Installing the Vue CLI v3

You can install the Vue CLI v3 from npm using the following command:

$ npm install -g @vue/cli

This will install the Vue CLI 3 globally on your system so depending on your npm configuration your may need super-user access i.e add sudo on debian-based systems.

Vue is using scoped packages for various packages such as the cli using the @vue namespace.

If you are using yarn instead of npm, you can run the following command instead:

yarn global add @vue/cli

Creating a New Vue Project

Using the Vue CLI 3, you can create or generate a new Vue project by running the following command from your terminal:

$ vue create frontend 

You'll be asked for various features such as TypeScript support, adding the Vue Router, adding Vuex etc.

Vue CLI v3.0.0-beta.15
? Please pick a preset: Manually select features
? Check the features needed for your project: (Press <space> to select, <a> to t
oggle all, <i> to invert selection)
❯◉ Babel
 ◯ TypeScript
 ◯ Progressive Web App (PWA) Support
 ◯ Router
 ◯ Vuex
 ◯ CSS Pre-processors
 ◉ Linter / Formatter
 ◯ Unit Testing
 ◯ E2E Testing

Serving the Vue Front-End Application

After generating the new Vue application using Vue CLI v3, you can use various built-in scripts to work with the application. Navigate inside your project's root folder and run the following command in order to serve your front-end application using a local development server:

$ cd frontend
$ npm run serve

This is the output you are going to get:

 DONE  Compiled successfully in 2729ms                                  01:50:56


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

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

Using your web browser, you can navigate to http://localhost:8080/ to see your Vue application up and running.

Demystifying the Project's Anatomy

The Vue front-end application generated with Vue CLI v3 has a special directory structure. Let's use the tree command to display this structure excluding the node_modules folder which contains installed packages:

tree -I "node_modules"

The output is similar to the following:

.
├── babel.config.js
├── package.json
├── package-lock.json
├── public
│   ├── favicon.ico
│   └── index.html
└── src
    ├── App.vue
    ├── assets
    │   └── logo.png
    ├── components
    │   └── HelloWorld.vue
    └── main.js

Let's quickly describe these files and folders:

  • babel.config.js: Contains Babel (ES Transpiler that allows you to use modern JavaScript features which are not yet implemented on the browser ) configuration.
  • package.json: Required for each Node.js module. It contains project's meta information and dependencies.
  • public: This is a folder that contains public assets such as index.html and favicon.
  • src: This is the folder where we are going to spend most time. It contains the source code of our Vue application
  • src/main.js: This file contains the initialization or bootstrapping code of our application.
  • src/App.vue: This file contains the main component of our Vue application.
  • src/assets: It contains the static assets.
  • src/components: It contains the components of our Vue application.

NPM Scripts

The Vue CLI v3 provides many npm scripts which setups zero-configuration development and production environments with various features such as hot code or module reloading, concatenation, minification and linting etc.

If your open package.json of your project you'll see different available (serve, build and lint) scripts:


...

  
"scripts"
:
 
{

    
"serve"
:
 
"vue-cli-service serve"
,

    
"build"
:
 
"vue-cli-service build"
,

    
"lint"
:
 
"vue-cli-service lint"

  
}
,



All scripts use the vue-cli-service which has ready webpack configurations for development and production so you don't have to deal with Webpack when you are just starting to work with your project.

Environment Variables

You can use environment variables with Vue CLI v3 by adding a .env file with the following structure:

VUE_APP_DEBUG=true
...

Your environment variable should start with VUE_APP_.

The Vue CLI will load your defined environment variables and make them available via process.env. For example, you can access the VUE_APP_DEBUG variable via process.env.VUE_APP_DEBUG.

You can also define environment variables to be available for specific environments i.e development or production by adding an appropriate suffix to the name of the environment file. For example:

  • .env.development: For development
  • .env.production: For production

Environment variables defined in .env will be overridden with the same variables if they are defined in .env.development or .env.production etc.

Using Proxies with Vue CLI v3

Sometimes, when making API calls from your Vue front-end application, you'll need to use a proxy to proxy calls in order to avoid issues such as CORS related to Same Origin Policy enforced by web browsers. Vue CLI v3 provides a built-in feature to use a proxy.

You can configure a proxy by simply adding a proxy object to package.json file. For example:


{

  
"proxy"
:
 
{

    
"/api"
:
 
"http://localhost:8000"

  
}


}



So if you need to make API calls to Django server running at http://localhost:8000 you simply call http://localhost:8080/api/* and Vue CLI will take care of forwarding the calls to http://localhost:8000/*.

Adding Vue CLI Plugins

Vue CLI v3 makes use of plugins to provide different functionalities. When you choose features at the start of project initialization the Vue CLI installs and invokes the required plugins but you can also install any plugin and invoke it manually. For example, you can add the Progressive Web App (PWA) functionality using the following commands:

$ npm install @vue/cli-plugin-pwa
$ vue invoke pwa 

Inspect Your Webpack Config Without Ejecting

The Vue CLI relives you from manually dealing with Webpack configuration by providing plugins for configuring many features and dependencies. But, in many situations, you'll want to have access to the Webpack configuration file for making advanced things not available via a CLI plugin.

Aside from ejecting, the Vue CLI allows you also to inspect the Webpack configuration to see what's the Vue CLI is generating. This will help you to make sure the generated configuration is what you're expecting. In your project generated with the Vue CLI, run the following command:

vue inspect

This will display the Webpack configuration in your terminal but you can write it into a file by running the following command:

vue inspect > webpack.config.js

You can also inspect portions of the configuration file using dots paths:

vue inspect resolveLoader.modules

Conclusion

We've seen how to install the Vue CLI v3 and various features such as adding plugins, adding environment variables and proxying API calls.

June 12 2018

python django Automated Testing

Automated Testing

The automated testing are simple routines that checks the operation of your code . There are some tests  which tests the small part of the code and others are which tests the overall operation of the program automated tests are tests which are done by the system for us like we create a set of tests and then we make changes to our app and test if the code works as if we it were originally intended to work without performing time consuming manual testing

Benefits of Testing

  • Test will save Time:If we change any of the components of the code could cause unexpected application behavior checking that it still works means running the test through your code functionality with twenty different variations of your test data just to make sure its working properly this is not a good use of time we can do this test in seconds with automated testing like writing the automated test is more beneficial than testing your application manually 
  •  Test prevent the problem: they can prevent the coming problems from identifying them early before you could fall in any problems
  • Test make the code more attractive: if you have made an amazing software then also most developers will refuse to take your software because it lacks tests they won't trust it jacob koplan moss one of the original developers of django says that code without test is broken by design the other developers want see test in your software to take it seriously 
  • Test helps teams work together: The tests helps in software which are made by teams test guarantees that the colleagues don't inadvertently break your code and you don't break their code without knowing 

The different Testing strategies

There are many ways to approach on writing test one of the discipline is the test driven development in which that relies on the repetition of a very short development cycle requirements are turned in to very specific test cases then the software is improved to pass the new tests only some programmers write their tests before their code test driven development simply formalizes the problem in a python test case it will be difficult to figure out where to get started with writing test if there are thousands of line of python code choosing something to test might not be easy its beneficial write the first test before you make a change either when you add a new feature or fix bugs

Start to write our first Test

The django unit test uses the python standard library module unittest
  this module defines test using a class based approach first in our code we make a subclass of  TestCase from django.test which is a subclass of unittest.TestCase that runs each test inside a transaction to provide isolation

from django.test import TestCase
from myapp.models import Animal
 
class AnimalTestCase (TestCase):
           def setup(self):
                            Animal.objects.create(name= "lion" ,color = "brown")
                        Animal.object .create(name = "tiger", color = "red")
          def animal_has_color(self):
                   """Animals that have color are identified"""
                         Lion = Animal.objects.get(name = "lion")
                         Tiger = Animal.objects.get(name = "tiger")
                         self.assertEqual(lion.color(),"the lion has color 'brown'")
                        self.assertEqual(tiger.color(),"the tiger has color 'red'") In here the test case when we run it the default behavior of the test utility is to find all the test cases that is subclasses of unittest.TestCase in any file whose name begins with test automatically build a test suite out of those test cases and run the test suit
As explained in my previous chapters by default the test.py file will be created in the new applicatiion of "myproj" folder but this will not be enough as your test suite grows at that time you will need to restructure it into a tests package so you can split your tests into different submodels such as test_models.py,test_views.py,test_forms.py etc you can pick whatever organizational scheme you like and one important point to note here is if your tests rely on database access such as creating or querying models be sure to create the test classes as subclasses of django.test.TestCase rather than unittest.TestCase because using unittest.TestCase avoids the cost of running each test in a transaction and flushing the database but if your tests interact with the database their behavior will vary based on the order that the test runner executes then this can lead to unit tests that pass when run in isolation but fails when run in a suite

More on how to run the tests and more will be included in the next post hope you like the post to get latest updates please follow by email and dont forget to share ,follow and comment below your doubts and suggestions



June 11 2018

Handling repetitive tests in Django

When writing tests (unit and/or functional), one of the goal is to cover all edge-cases. DDT is a great way to write such tests; here is how to do so in Python and Django.

June 09 2018

Angular 6 Tutorial with Django RESTful API — Adding Angular Material Design 6 UI By Example

In the previous tutorial, you have seen how you can install the Angular CLI 6 and generate a brand new Angular 6 front-end application. In this tutorial, we'll be learning how to use Angular 6 Material Design to build a beautiful and professional grade UI interface.

What's Material Design and Angular Material 6

Material Design is a design language created by Google in 2014 that dictates a set of principles and guidelines for creating UIs including motion (animations) and interaction (gestures).

Angular Material 6 is the implementation of Material Design for Angular 6. It offers a plethora of components and patterns for navigation, forms, buttons and layouts.

In this tutorial, we'll see how to add Material Design to Angular 6 in two ways:

  • The long way: by following a bunch of steps manually. This works for Angular 4, 5 and Angular 6.
  • The short way: by using ng add command to quickly add Angular Material in one step using Angular 6 Schematics. This method only works with Angular 6+.

Step1: Installing Angular Material and Angular CDK

Head over to your terminal, navigate inside your created Angular front-end application and then run the following commands to install Angular Material 6 and Angular 6 CDK

npm install --save @angular/material @angular/cdk

Step 2: Adding Support for Animations

Some Angular Material 6 components use animations so you need to add support for animations in your Angular 6 front-end application in order to enable these animations.

Head back to your terminal and run the following command to install the Angular animations module

npm install --save @angular/animations

Next you only need to add this module to your app configuration so go ahead and open the app.module.ts file then import the BrowserAnimationsModule module and add it to the list of imports

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

imports: [
    BrowserModule, BrowserAnimationsModule
],

Step 3: Adding Support for Gestures with HammerJS

some Angular Material components depend on HammerJS for gestures support so you need to add HammerJS to your application in order to get all the features of those components

You can simply head to your terminal and install the library from npm

npm install --save hammerjs

You'll then need to import the library in your app entry point (main.ts)

/*...*/
import 'hammerjs';

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule)
  .catch(err => console.log(err));

Step 4: Including a Theme

Themes are required to add styles/colors to Material components used in your application. You can either use a custom or a pre-built theme.

Themes are CSS files. To find all available pre-built themes you can check @angular/material/prebuilt-themes

  • deeppurple-amber.css
  • indigo-pink.css
  • pink-bluegrey.css
  • purple-green.css

So let's use the deeppurple-amber.css theme for our application.

Simply open the style.css file and add the following CSS @import

@import '~@angular/material/prebuilt-themes/deeppurple-amber.css';

Adding Angular Material 6 with ng-add and Schematics

[With the release of Angular 6 the new ng add command is available which makes it easy to add new capabilities to the project. This command will use the package manager to download new dependencies and invoke corresponding installation scripts. This is making sure that the project is updated with dependencies, configuration changes and that package-specific initialization code is executed.

In the following we’ll use the ng add command to add Angular Material to the previously created Angular 6 application:

$ ng add @angular/material

By executing this command we’re installing Angular Material and the corresponding theming into the project. Furthermore new starter components are registered into ng generate.]

[### Exploring Angular Material Stater Components

With Angular 6 and Angular Material 6, you can now use ng generate to quickly generate Material design components. The following boilerplate components are available:

  • @angular/material:materialDashboard: Generates a card-based Material dashboard component
  • @angular/material:materialTable: Generates a Material data-table component
  • @angular/material:materialNav: Generates a Material navigation component with a responsive sidenav.

You can generate these components using the ng generate command as in the following examples:

$ ng generate @angular/material:materialNav --name exampleNavbar

$ ng generate @angular/material:materialDashboard --name exampleDashboard

$ ng generate @angular/material:materialTable -- name exampleDatatable

These commands generates boilerplate files for the component and update your application module accordingly.

Let's take an example. Go ahead and open src/app/app.component.html and update it to add a Material Design navigation bar:

<example-navbar></example-navbar>

This will include the output of ExampleNavbarComponent in our main application component.

Now, we need to add our links and use the routerLink directive to create navigation links. Open src/app/example-navbar/example-navbar.component.html then add the following links:

<mat-nav-list>      
<a  mat-list-item [routerLink]="'/accounts'"> Accounts </a>
<a  mat-list-item  [routerLink]="'/create-account'"> Create Account </a>
<a  mat-list-item [routerLink]="'/contacts'"> Contacts </a>
<a  class="mat-list-item " [routerLink]="'/create-contact'"> Create Contact </a>
<a  class="mat-list-item " [routerLink]="'/leads'"> Leads </a>
<a  class="mat-list-item " [routerLink]="'/create-lead'"> Create Lead </a>
<a  class="mat-list-item" [routerLink]="'/opportunities'"> Opportunities </a>
<a  class="mat-list-item " [routerLink]="'/create-opportunity'"> Create Opportunity </a>
</mat-nav-list>

Conclusion

That's it, we now have updated our Angular 6 front-end application to use Angular Material and updated our navigation bar to use <mat-nav-list>. In the next tutorial we'll see more detailed example of using Material data-table to create tables for our data.

June 08 2018

Install Jupyter Notebooks in a Virtual Environment

Let's install Jupyter for a di...

June 06 2018

Angular 6 Tutorial with Django RESTful API — Building Bootstrap 4 UIs

In this Angular 6 tutorial we'll learn how to use Bootstrap 4 with Angular 6 to build professional UIs.

Angular 6 is the latest version of Angular when writing this tutorial and Bootstrap 4 is the latest version of Bootstrap — The most popular CSS framework. You can use Bootstrap to create professional looking interfaces without being a CSS designer.

In this tutorial, we'll particularly look at how to add Bootstrap 4 to Angular projects generated using Angular CLI 6.

In the previous tutorial, we've built a web application with Angular 6 and Django. In this part, we're going to style the UI interface with Bootstrap 4, after installing and setting up the framework in the Angular 6 front-end.

In the previous tutorial we’ve: - Installed Angular CLI v6. - Generated a new front-end application using Angular CLI v6. - Created some UI components.

In this tutorial, we'll be using the following versions of libraries:

  • Angular 6 and Angular CLI 6.
  • Bootstrap 4.

Different Ways to Integrate Bootstrap 4 with Angular 6

There are many ways to add Bootstrap 4 to Angular 6 projects:

  • Installing bootstrap and jquery via npm and add adding scripts and styles to angular.json.
  • Importing bootstrap style and script files in src/index.html. You can use a bootstrap 4 CDN.
  • Installing bootstrap via npm and importing @import "~bootstrap/dist/css/bootstrap.css"; in src/styles.css.
  • Installing and using ng-bootstrap npm install --save @ng-bootstrap/ng-bootstrap: It's a library that contains native Angular components for Bootstrap’s markup and CSS styles. It's not dependent on jQuery or Bootstrap’s JavaScript.

How to Work with This Tutorial?

To complete this tutorial, you'll need to, either:

  • Start with the previous tutorial, which takes you from installing the Angular CLI 6 to calling the Django RESTful API
  • Clone the font-end project from GitHub and follow the steps in the previous tutorial for setting up the project.
  • Directly follow the steps to integrate Bootstrap 4 in your own Angular 6 project.

How to add Bootstrap 4 to your Angular 6 Front-End?

After seeing different ways to add Bootstrap 4 to Angular 6, let's now style our Angular 6 front-end UI, built in the previous tutorial, with Bootstrap. We'll use the first approach i.e we'll install bootstrap from npm and then we'll include bootstrap.css CSS file, jQuery and Popover.js

Please note that projects generated using Angular CLI 6 are using angular.json instead of .angular-cli.json for configuration settings

Installing Bootstrap 4 and jQuery

Head over to your project, you created in the previous tutorial, navigate inside your Angular 6 front-end application:

cd frontend

Next, install bootstrap and jquery from npm using:

npm install --save bootstrap jquery

Adding Bootstrap 4 to Angular CLI v6

Next, open angular.json. You should similar content to the following:


{



"$schema"
:
 
"./node_modules/@angular/cli/lib/config/schema.json"
,


"version"
:
 
1
,


"newProjectRoot"
:
 
"projects"
,


"projects"
:
 
{

    
"crmapp"
:
 
{

    
"root"
:
 
""
,

    
"sourceRoot"
:
 
"src"
,

    
"projectType"
:
 
"application"
,

    
"prefix"
:
 
"app"
,

    
"schematics"
:
 
{},

    
"architect"
:
 
{

        
"build"
:
 
{

        
"builder"
:
 
"@angular-devkit/build-angular:browser"
,

        
"options"
:
 
{

        
"outputPath"
:
 
"dist/crmapp"
,

        
"index"
:
 
"src/index.html"
,

        
"main"
:
 
"src/main.ts"
,

        
"polyfills"
:
 
"src/polyfills.ts"
,

        
"tsConfig"
:
 
"src/tsconfig.app.json"
,

        
"assets"
:
 
[

            
"src/favicon.ico"
,

            
"src/assets"

        
],

        
"styles"
:
 
[

            
"src/styles.css"

        
],

        
"scripts"
:
 
[]

        
},



...


}
,


"defaultProject"
:
 
"crmapp"


}



Under projects -> architect -> build -> scripts add node_modules/jquery/dist/jquery.min.js and node_modules/bootstrap/dist/js/bootstrap.min.js:


"scripts"
:
 
[

    
"node_modules/jquery/dist/jquery.min.js"
,

    
"node_modules/bootstrap/dist/js/bootstrap.min.js"


]



Under projects -> architect -> build -> styles add node_modules/bootstrap/dist/css/bootstrap.min.css:


"styles"
:
 
[

    
"src/styles.css"
,

    
"node_modules/bootstrap/dist/css/bootstrap.min.css"


]
,



That's it. You can now use Bootstrap 4 in your Angular 6 front-end application just lie you would normally do.

Styling Angular Components with Bootstrap 4

Let's take an example. Go ahead and open src/app/app.component.html and update it to add a Bootstrap navigation bar:

<nav  class="navbar navbar-expand-lg navbar-light bg-light">
    <a  class="navbar-brand"  href="#">Angular CRM</a>
    <button  class="navbar-toggler"  type="button"  data-toggle="collapse"  data-target="#navbarSupportedContent"  aria-controls="navbarSupportedContent"  aria-expanded="false"  aria-label="Toggle navigation">
    <span  class="navbar-toggler-icon"></span>
    </button>
<div  class="collapse navbar-collapse"  id="navbarSupportedContent">
    <ul  class="navbar-nav mr-auto">
        <li  class="nav-item active">
        <a  class="nav-link"  href="#">Home <span  class="sr-only">(current)</span></a>
        </li>
        <li  class="nav-item dropdown">
        <a  class="nav-link dropdown-toggle"  href="#"  id="navbarDropdown"  role="button"  data-toggle="dropdown"  aria-haspopup="true"  aria-expanded="false">
        Actions
        </a>
        <div  class="dropdown-menu"  aria-labelledby="navbarDropdown">
        <a  class="dropdown-item" [routerLink]="'/accounts'"> Accounts </a>
        <a  class="dropdown-item" [routerLink]="'/create-account'"> Create Account </a>
        <div  class="dropdown-divider"></div>
        <a  class="dropdown-item" [routerLink]="'/contacts'"> Contacts </a>
        <a  class="dropdown-item" [routerLink]="'/create-contact'"> Create Contact </a>
        <div  class="dropdown-divider"></div>
        <a  class="dropdown-item" [routerLink]="'/leads'"> Leads </a>
        <a  class="dropdown-item" [routerLink]="'/create-lead'"> Create Lead </a>
        <div  class="dropdown-divider"></div>
        <a  class="dropdown-item" [routerLink]="'/opportunities'"> Opportunities </a>
        <a  class="dropdown-item" [routerLink]="'/create-opportunity'"> Create Opportunity </a>
        </div>
        </li>
</ul>
</div>
</nav>
<div  class="container-fluid">
    <router-outlet></router-outlet>
</div>

Now, let's style contact list component. Open src/app/contact-list.component.html and add:

<h1>
My Contacts
</h1>
<div>
<table  class="table">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Phone</th>
<th>Email</th>
<th>Address</th>
</tr>
</thead>
<tr *ngFor="let contact of contacts">
    <td>  </td>
    <td>  </td>
    <td>  </td>
    <td>  </td>
    <td>  </td>
</tr>
</table>
</div>

This is a screen-shot of the result after adding Bootstrap 4 classes:

Angular 6 and Bootstrap 4 tutorial

Conclusion

In this tutorial, we've seen different ways you can use if you want to add Bootstrap 4 to your project and then we have seen by example how to add Bootstrap 4 to our Angular 6 front-end application generated with Angular CLI v6 in the previous tutorial.

June 05 2018

Django Models Best Practices

A list of tips for designing better models in Python/Django.

June 04 2018

Taming Irreversibility with Feature Flags (in Python)

Feature Flags are a very simple technique to make features of your application quickly toggleable. The way it works is, everytime we change some behavior in our software, a logical branch is created and this new behavior is only accessible if some specific configuration variable is set or, in certain cases, if the application context respects some

Django REST Framework Read & Write Serializers

Django REST Framework (DRF) is a terrific tool for creating very flexible REST APIs. It has a lot of built-in features like pagination, search, filters, throttling, and many other things developers usually don't like to worry about. And it also lets you easily customize everything so you can make your API work the way you want. There are many gene

Multitenancy: juggling customer data in Django

Suppose you want to build a new SaaS (Software as a Service) application. Suppose your application will store sensitive data from your customers. What is the best way to guarantee the isolation of the data and make sure information from one client does not leak to the other? The answer to that is: it depends. It depends on the number of customers y

Going to Technical Events is Awesome: A DjangoCon Experience

We just got back from DjangoCon US! It was quite a marathon for us because Filipe Ximenes and I have been to PyBay and DjangoCon AU too, right before DjangoCon US. Besides having a great time presenting our talks, it was awesome to meet new people and reunite with old friends. From our blog, you’d guess that we really enjoy conferences. We do incentivize collaborators to attend them since we believe it's very important to keep in touch with the community.

Organizing Django Girls Recife

In Brazil, women are the majority in schools and universities and represent 60% of the people who have a university degree. Despite this, in STEM, they represent only 20% of the quantitative. This scenario is present not only in Brazil but all over the world. In technological areas, it’s no different. IT is still a mostly male world. It was with the intention of diversifying this context that the Django Girls was created.

[pt-BR] Organizando o Django Girls Recife

No Brasil, as mulheres são maioria nas escolas e universidades e representam 60% das pessoas que concluíram cursos superiores. Apesar disso, em cursos de exatas, representam apenas 20% do quantitativo. Esse cenário se repete não só no Brasil, mas em todo o mundo. Nas áreas tecnológicas não é diferente. TI é, ainda, um mundo majoritariamente masculino. Foi com o intuito de diversificar esse contexto que o Django Girls foi criado.

DjangoCon Europe 2017 was awesome!

DjangoCon Europe happened in one of the most historical cities in Italy! Florence was the most exciting place to be around in Europe, if you are a Django enthusiast, from April 3rd to April 7th. The event had the presence of some important names on it, like Andrew Godwin and Marc Tamlyn, both core developers at Django, and Tom Christie, author of t

Advanced Django querying: sorting events by date

Imagine the situation where our application has events (scheduled tasks, appointments, python conferences across the world) happening in different moments of time. Almost anything with a date attached to it. We want to display them in a simple list to the user. Given we are in February 2017 (the date this post was written), what would be the best w

Contributing to Django Framework is easier than you think

For those who are starting to code and wish to make open source, sometimes it is hard to start. The idea of contributing with that fancy and wonderful lib that you love can sound a little bit scary. Lucky for us many of those libs have room for whoever is willing to start. They also give us the support that we need. Pretty sweet, right? Do you know
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!

Schweinderl