Belajar Pemrograman Web dengan Framework Django Python



Mari kita belajar membuat aplikasi web dengan menggunakan Framework Django dengan menggunakan bahawa Python:

1. Install Python
Bagi yang belum terdapat Python dalam komputernya silahkan install Python download disini.

2. Install pip
Cara instal pip bisa dibaca disini.

3. Install virtualenv
Install virtualenv digunakan untuk melakukan isolasi terhadap lingkungan kerja Python dimana kita bisa melakukan instalasi dan setup tanpa harus mengganggu virtualenv yang lain ataupun lingkungan system aslinya. Cara install virtualenv seperti gambar dibawah.


4. Membuat direktori virtualenv
selanjutnya kita buat direktori kerja untuk virtualenv dengan sebelumnya kita menuju direktori kerja django yang akan kita pilih atau gunakan. Contoh saya akan membuat virtualenv dengan nama my_env.


5. Mengaktifkan virtualenv
Setelah sebelumnya saya membuat virtualenv dengan nama my_env, langkah selanjutnya saya masuk ke folder my_env kemudian mengaktifkan virtualenv dengan menggunakan perintah .\Scripts\activate


6. Install Django
Setelah kita berada dalam virtualenv dan sudah diaktifkan, selanjutnya kita install dframework Djangi di komputer kita dengan menggunakan perintah pip install Django


Kita bisa mengecek apakah instalasi django yang sudah dilakukan berhasil dengan menggunakan perintah sebagai berikut:
python
>>import django
>>django.VERSION

Jika informasi yang ditampilkan seperti dalam command prompt gambar diatas maka kita berhasil install Django.

7. Membuat Project Pertama Django
Selanjutnya kita akan membuat aplikasi pertama atau project menggunakan Django. Ketikan perintah berikut django-admin startproject mysite.
Perintah diatas artinya kita akanmembuat project Django dengan nama mysite. 


Setelah kita membuat project dengan perintah diatas maka secara otomatis dalam folder project kita dibuatkan struktur folder yang seperti ini 


Struktur foler dan data dalam gambar diatas terdiri dari:
manage.py yang berada pada folder mysite, merupakan sebuah utilitas command-line untuk berinterkasi dengan project kita. kita tidak harus merubah file ini.

forder mysite/ yang terdiri dari beberapa file sebagai berikut:
__init__.py : merupakan sebuah file kosong yang memberitahukan Python untuk memberlakukan direktori mysite sebagai modul Python.
setting.py    : setting dan konfigurasi project kita, yang memuat seting inisial default.
urls.py         : Tempat dimana pattern URL kita tinggal, setiap URL yang definisikan dipetakan untuk ditampilkan.
wsgi.py        : merupakan konfigurasi untuk menjalankan project-project sebagai sebuah aplikasi WSGI.

File generate setting.py yang mempunyai konfigurasi dasar untuk digunakan sebuah database SQLite dan daftar aplikasi Django yang telah ditambahkan ke dalam project secara default. Kita harus membuat tabel dalam database untuk inisialisasi aplikasi.

8. Membuat database
Untuk membuat tabel untuk inisialisasi aplikasi ketikan perintah 
cd mysite
python manage.py migrate


Dengan perintah tersebut kita telah membuat tabel untuk inisialisasi aplikasi yang dibuat dalam database.

9. Menjalankan server yang dikembangkan
Django mempunyai webserver yang ringan untuk menjalankan kode perintah kita, tanpa membutuhkan waktu yang lama untuk configurasi server. Ketika server dijalankan maka otomatis dilakukan pengecekan kepad source kode kita. Namun ketika kita menambahkan file baru kedalam project  kita harus melakukan restart server. Untuk menjalankan server ketikan perintah python manage.py runserver 


Hasil dari perintah menjalankan server telihat bahwa server telah berjalan dan kita bisa mengecek dengan browser di alamat 127.0.0.1:8000 atau localhost:8000


Secara default server lokal dijalankan pada port 8000, namun kita bisa mengeset port yag akan kita gunakan dengan perintah
python manage.py runserver 127.0.0.1:8001 --settings=mysite.settings

Hasil dari perintah tersebut adalah sebagai berikut dimana server dijalankan dalam 127.0.0.1:8001, dan untuk menghentikan server gunakan CTRL + C

System check identified no issues (0 silenced).
November 13, 2016 - 14:41:10
Django version 1.10.3, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8001/
Quit the server with CTRL-BREAK.

Jika tampilan di browser kita seperti diatas, maka selamat aplikasi Django berhasil kita buat inilah halaman default dari aplikasi Django. Oke sampe sini kita istirahat sejenak dan minum kopi dulu ...
Namun sebagai catatan server ini hanya berlaku untuk pengembangan saja, untuk pekerjaan produktif kita harus menjalankan aplikasi sebagai WSGI (Web Server Gateway Interface) dengan webserver Apache, Gunicorn, atau uWSGI. Untuk melihat informasi lebih lanjut silahkan kunjungi halaman ini https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi

10. Setting Project
Setting project dapat kita lakukan denganmengubah file setting.py, konfigurasi dalam file tersebut adalah:
- DEBUG is a boolean that turns on/off the debug mode of the project. If set to True, Django will display detailed error pages when an uncaught exception is thrown by your application. When you move to a production environment, remember you have to set it to False. Never deploy a site into production with DEBUG turned on because you will expose sensitive data of your project. 

- ALLOWED_HOSTS is not applied while debug mode is on or when running tests. Once you are going to move your site to production and set DEBUG  to False, you will have to add your domain/host to this setting in order  to allow it to serve the Django site. 

- INSTALLED_APPS is a setting you will have to edit in all projects. This setting tells Django which applications are active for this site. By default, Django includes the following applications:  
   - django.contrib.admin: This is an administration site. 
   - django.contrib.auth: This is an authentication framework. 
   - django.contrib.contenttypes: This is a framework for  content types. 
   - django.contrib.sessions: This is a session framework. 
   - django.contrib.messages: This is a messaging framework.  
   - django.contrib.staticfiles: This is a framework for managing static files. 

- MIDDLEWARE_CLASSES is a tuple containing middlewares to be executed. 

- ROOT_URLCONF indicates the Python module where the root URL patterns  of your application are defined. 

- DATABASES is a dictionary containing the settings for all the databases to be used in the project. There must always be a default database. The default configuration uses a SQLite3 database. 

- LANGUAGE_CODE Defines the default language code for this Django site. 

Jangan khawatir saat ini biarkan file-file tersebut, nanti kita bahas di selanjutnya.

11.  Membuat Aplikasi Blog
Dalam Project kita bisa buat beberapa aplikasi, dimana dalam aplikasi tersebut terdapat model, view, template dan URL.

Kita buat aplikasi dengan perintah misal saya akan buat aplikasi blog dalam project mysite, sehingga dalam folder mysite terdapat dua aplikasi mysite dan blog

(my_env) C:\Django-project\my_env\mysite>python manage.py startapp blog

Hasil dari perintah diatas maka dapat dilihat dalam windows explorer dihasilkan sebuah folder(aplikasi) blog yang berisi file-file seperti dibawah ini.


admin.py: This is where you register models to include them into the Django administration site. Using the Django admin site is optional.  

- migrations: This directory will contain database migrations of your application. Migrations allow Django to track your model changes and synchronize the database accordingly. 

- models.py: Data models of your application. All Django applications need  to have a models.py file, but this file can be left empty. 

- tests.py: This is where you can add tests for your application. 

- views.py: The logic of your application goes here. Each view receives an HTTP request, processes it, and returns a response.

12. Merancang Data Skema Blog
Pertama kita mulai dengan mendefiniskan data model untuk blog kita. Sebuah model adalah clas python dari subclass django.db,models.Model dimana setiap atribut merepresentasikan sebuah field database.  Django akan membuat sebuah tabel untuk setiap model yang telah didefinisikan dalam file models.py  Ketika kita buat model, Django menyediakan API untuk query database dengan mudah. Pertama kita akan mendefinisikan model Post, tambahkan beberapa baris dalam kode porgram dalam models.py.

from django.db import models 
from django.utils import timezone 
from django.contrib.auth.models import User

class Post(models.Model):
    STATUS_CHOICES = (
        ('draft', 'Draft'),
        ('published', 'Published'),
    )
    title = models.CharField(max_length=250)
    slug = models.SlugField(max_length=250, unique_for_date='publish')
    author = models.ForeignKey(User, related_name='blog_posts')
    body = models.TextField()    
    publish = models.DateTimeField(default=timezone.now)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft')

class Meta:        
    ordering = ('-publish',)

def __str__(self):        
    return self.title

This is our basic model for blog posts. Let's take a look at the fields we just defined for this model:
• title: This is the field for the post title. This field is CharField, which translates into a VARCHAR column in the SQL database.

• slug: This is a field intended to be used in URLs. A slug is a short label containing only letters, numbers, underscores, or hyphens. We will use the slug field to build beautiful, SEO-friendly URLs for our blog posts. We have added the unique_for_date parameter to this field so we can build URLs  for posts using the date and slug of the post. Django will prevent from multiple posts having the same slug for the same date.

• author: This field is ForeignKey. This field defines a many-to-one relationship. We are telling 
Django that each post is written by a user and  a user can write several posts. For this field, Django will create a foreign key in the database using the primary key of the related model. In this case, we are relying on the User model of the Django authentication system. We specify the name of the reverse relationship, from User to Post, with the related_name attribute. We are going to learn more about this later.

• body: This is the body of the post. This field is TextField, which translates into a TEXT column in the SQL database.

• publish: This datetime indicates when the post was published. We use Django's timezone now method as default value. This is just a timezone-aware datetime.now.

• created: This datetime indicates when the post was created. Since we are using auto_now_add here, the date will be saved automatically when creating an object.

• updated: This datetime indicates the last time the post has been updated. Since we are using auto_now here, the date will be updated automatically when saving an object.

• status: This is a field to show the status of a post. We use a choices parameter, so the value of this field can only be set to one of the given choices.

Since we are going to deal with datetimes, we will install the pytz module. This module provides timezone definitions for Python and is required by SQLite to work with datetimes. Open the shell and install pytz with the following command:

pip install pytz

Django comes with support for timezone-aware datetimes. You can activate/ deactivate time zone support with the USE_TZ setting in the settings.py file of your project. This setting is set to True when you create a new project using the startproject management command.

13. Mengaktifkan  Aplikasi
In order for Django to keep track of our application and be able to create database tables for its models, we have to activate it. To do this, edit the file settings.py in folder mysite and add blog to the INSTALLED_APPS setting. It should look like this:

INSTALLED_APPS = ( 
   'django.contrib.admin',    
   'django.contrib.auth',    
   'django.contrib.contenttypes',    
   'django.contrib.sessions',    
   'django.contrib.messages',    
   'django.contrib.staticfiles',
   'blog', ) 

Now Django knows that our application is active for this project and will be able  to introspect its models.

14. Membuat dan menggunakan migration

Let's create a data table for our model in the database. Django comes with a migration system to track the changes you do to your models and propagate them into the database. The migrate command applies migrations for all applications listed in INSTALLED_APPS; it synchronizes the database with the current models  and migrations.

First, we need to create a migration for the new model we just created. From the root directory of your project, enter this command: python manage.py makemigrations blog

(my_env) C:\Django-project\my_env\mysite>python manage.py makemigrations blog
Migrations for 'blog':
  blog\migrations\0001_initial.py:
    - Create model Post

Django just created a file 0001_initial.py inside the migrations directory of the blog application. You can open that file to see how a migration looks like. Let's take a look at the SQL code that Django will execute in the database to create the table for our model. 

The sqlmigrate command takes migration names and returns their SQL without running it. Run the following command to inspect its output:

python manage.py sqlmigrate blog 0001 


The exact output depends on the database you are using. The output above is generated for SQLite. As you can see, Django generates the table names by combining the app name and the lowercase name of the model (blog_post), but  you can also specify them in the Meta class of the models using the db_table attribute. Django creates a primary key automatically for each model but you can also override this specifying primary_key=True on one of your model fields.

Let's sync our database with the new model. Run the following command to apply existing migrations:

python manage.py migrate 

You will get the following output that ends with the following line:

Applying blog.0001_initial... OK


We just applied migrations for the applications listed in INSTALLED_APPS, including our blog application. After applying migrations, the database reflects the current status of our models.

If you edit your models.py file in order to add, remove, or change fields of existing models, or if you add new models, you will have to make a new migration using the makemigrations command. The migration will allow Django to keep track of model changes. Then you will have to apply it with the migrate command to keep the database in sync with your models.

15. Creating an administration site for your models

Now that we have defined the Post model, we will create a simple administration site to manage blog posts. Django comes with a built-in administration interface that is very useful for editing content. The Django admin site is built dynamically by reading your model metadata and providing a production-ready interface for editing content. You can use it out-of-the-box, configuring how you want your models to be displayed in it.

Remember that django.contrib.admin is already included in the INSTALLED_APPS setting of our project and that's why we don't have to add it.

16. Creating a superuser First,
we need to create a user to manage the admin site. Run the following command:

python manage.py createsuperuser

You will see the following output. Enter your desired username, e-mail, and password:

(my_env) C:\Django-project\my_env\mysite>python manage.py createsuperuser
Username (leave blank to use 'wawanhn'): admin
Email address: wawanhn@gmail.com
Password:
Password (again):
This password is too short. It must contain at least 8 characters.
This password is too common.
Password:
Password (again):
Superuser created successfully.

(my_env) C:\Django-project\my_env\mysite>

misal saya buat user admin dengan passrod admin1234

17. Menjalankan server


Kemudian kita buka browser pada alamat 

127.0.0.1/admin

sehingga terdapat tampilan seperti dibawah ini

kemudian masukan username dan password yang telah kita tentuka sebelumnya, sehingga tampil halaman depan dari admin


The Group and User models you see here are part of the Django authentication framework located in django.contrib.auth. If you click on Users, you will see the user you created before. The Post model of your blog application has a relationship with this User model. Remember, it is a relationship defined by the author field

18. Adding your models to the administration site
Let's add your blog models to the administration site. Edit the admin.py file of your blog application and make it look like this:

from django.contrib import admin
from .models import Post

# Register your models here.

admin.site.register(Post)

Now, reload the admin site in your browser. You should see your Post model in the admin site as follows:


That was easy, right? When you register a model in the Django admin site, you get  a user-friendly interface generated by introspecting your models that allows you  to list, edit, create, and delete objects in a simple way. 

Click on the Add link on the right of Posts to add a new post. You will see the  create form that Django has generated dynamically for your model, as shown  in the following screenshot:


Django uses different form widgets for each type of field. Even complex fields such as DateTimeField are displayed with an easy interface like a JavaScript date picker.

19. Customizing the way models are displayed 
Now we are going to see how to customize the admin site. Edit the admin.py file of your blog application and change it into this:

from django.contrib import admin
from .models import Post
class PostAdmin(admin.ModelAdmin):   
list_display = ('title', 'slug', 'author', 'publish', 'status')
admin.site.register(Post, PostAdmin)

We are telling the Django admin site that our model is registered into the admin site using a custom class that inherits from ModelAdmin. In this class, we can include information about how to display the model in the admin site and how to interact with it. The list_display attribute allows you to set the fields of your model that you want to display in the admin object list page.
Let's customize the admin model with some more options, using the following code:

class PostAdmin(admin.ModelAdmin):   
list_display = ('title', 'slug', 'author', 'publish',                         'status')   
list_filter = ('status', 'created', 'publish', 'author')   
search_fields = ('title', 'body')   
prepopulated_fields = {'slug': ('title',)}   
raw_id_fields = ('author',)   
date_hierarchy = 'publish'   
ordering = ['status', 'publish']

You can see that the fields displayed on the post list page are the ones you specified in the list_display attribute. The list page now includes a right sidebar that allows you to filter the results by the fields included in the list_filter attribute. A search bar has appeared on the page. This is because we have defined a list of searchable fields using the search_fields attribute. Just below the search bar, there is a bar to navigate quickly through a date hierarchy. This has been defined by the date_hierarchy attribute. You can also see that the posts are ordered by Status and Publish columns by default. You have specified the default order using the ordering attribute. 

Now click on the Add post link. You will also see some changes here. As you type the title of a new post, the slug field is filled automatically. We have told Django to prepopulate the slug field with the input of the title field using the prepopulated_fields attribute. Also, now the author field is displayed with a lookup widget that can scale much better than a dropdown select input when you have thousands of users, as shown in the following screenshot:

Sekian dulu belajar pemrograman web dengan Django, kalau ingin download tutorial diatas dalam format pdf silahkan download disini.

Semoga bermanfaat @wawanhn 
12 November 2016









Previous
Next Post »
0 Komentar