Setelah di setting proxy maka kita dapat menginstall library python, sebagai contoh install shapely seperti berikut: > conda install shapely Terima kasih sudah menyimak semoga bermanfaat. @wawanhn Pada bahasan ini saya akan membahas bagaimana jika kita ingin mengetahui atau analisis dari peta batas administrasi, dimana kit aingin mengetahui tetangga dari sebuah Kabupaten dari sebuah peta batas administrasi kabupaten. Dalam contoh bahasan saya menggunakan peta batas admnistrasi Propinsi Jawa Barat dalam bentuk polygon yang dapat di download disini. Gambar diatas merupakan tampilan dari peta batas administrasi kabupaten yang ada di Propinsi Jawa Barat. Selanjutnya dengan menggunakan Python dan beberapa tekhnik yang sudah dipelajari sebelumnya kita akan mencoba membuat kode program untuk membaca tetangga dari setiap kabupaten dari peta tersebut. Kemudian dengan menggunakan IDLE kita buat kode program python dengan nama baca_tetang_kabupaten.py seperti dibawah ini: import ogr import shapely.wkt def main(): shapefile = ogr.Open("D:\Master\Peta\BIG2016\export\Batas_Kab_Jawa_Barat.shp") layer = shapefile.GetLayer(0) kabupatens = {} for i in range(layer.GetFeatureCount()): feature = layer.GetFeature(i) kabupaten = feature.GetField("KABUPATEN") outline = shapely.wkt.loads(feature.GetGeometryRef().ExportToWkt()) kabupatens[kabupaten] = outline print "Dalam file Batas_Kab_Jawa_Barat.shp terdapat %d kabupaten" % len(kabupatens) for kabupaten in sorted(kabupatens.keys()): outline = kabupatens[kabupaten] for kabupaten_lain in sorted(kabupatens.keys()): if kabupaten == kabupaten_lain: continue outline_lain = kabupatens[kabupaten_lain] if outline.touches(outline_lain): print"%s batas-batas %s" % (kabupaten, kabupaten_lain) if __name__ == "__main__": main() Dalam kode program tersebut, pertama kita membaca jumlah seluruh objek Kabupaten dan selanjutnya mengecek objek-objek kabupaten yang bersebtuhan dengan sebuah objek kabupaten yang dicari. Dilakukan untuk setiap objek kabupaten. Setelah kita run kode program tersebut sehingga menghasilkan output seperti dibawah ini: Hasil dari kode program tersebut adalah menampilkan setiap border atau tetangga dari setiap kabupaten dalam peta propinsi Jawa Barat. Tetangga kabupaten tersebut merupakan kabupaten yang bersentuhan langsung dengan objek suatu kabupaten. File WKT (Well Know Text) merupakan teks markup language untuk merefresentasikan geometri objek vektor dari sebuah peta, sistem referensi geometri (sstem kordinat) dan transformasi antar siste kordinat.
Kali ini kita lanjutkan penggunaan library shapefile untuk membaca file WKT dari peta DesaIndonesia.shp. Langkahnya masih menggunakan IDLE python dan buat file baru dengan nama baca_shp_wkt.py kemudian ketikan kode program sebagai berikut: import ogr import shapely.wkt shapefile = ogr.Open("D:\Master\Peta\DesaIndonesia.shp") layer = shapefile.GetLayer(0) feature = layer.GetFeature(0) geometry =feature.GetGeometryRef() wkt = geometry.ExportToWkt() outline = shapely.wkt.loads(wkt) X = outline.centroid.x Y = outline.centroid.y B = outline.bounds print "X : ", X , "Y : ", Y print "Boundary: ", B Maka akan dihasilkan output sebagai berikut: Penjelasan: Digunakan untuk mendapatkan feature nomor 0dan disimpan ke variable feature. geometry =feature.GetGeometryRef() Sintax tersebut digunakan untuk mendapatkan referensi geometri. wkt = geometry.ExportToWkt() Sintax untuk melakukan ekport ke file WKT dan disimpan di variabel wkt. outline = shapely.wkt.loads(wkt) Sintax untuk meload file wkt ke variabel outline. X = outline.centroid.x Y = outline.centroid.y B = outline.bounds Sintax untuk menyimpan nilai tengah x ke variabel X, nilaing tengah y ke variabel Y dan menyimpan nilai boundari dari feature ke 0 ke variabel B. Data boundary yang ditampilkan adalah nilai minimum longitud dan latitud serta nilai maksimum longitud dan latitud (berati, min_x, min_y, max_x, max_y). print "X : ", X , "Y : ", Y print "Boundary: ", B Sintax untuk menampilkan nilai variabel ke layar. <<Sebelumnya Selanjutnya>> Setelah dalam bahasan sebelumnya mengenai persiapan Python dan library untuk mengakses data spasial dilakukan pada tulisan "Python untuk Analisis Geospatial Bagian 1: Install Library GDAL dan Shapely di Windows"Langkah selanjunya adalah menggunakan library GDAL/OGR dan Shapely untuk mengakses data spatial. Sebelum kita melanjutkan ke contoh program dengan python, pertama kita harus mengenal mengenal data spasial yang akan kita olah disini. "Mengenal Data Spasial"Tools yang akan kita gunakan dalam contoh dibawah nanti adalah IDLE sebagai text editor bawan dari instalan Python. Langkah-langkah yang akan kita lakukan sebagai berikut:
import ogr shapefile = ogr.Open("D:\Master\Peta\DesaIndonesia.shp") layer = shapefile.GetLayer(0) for i in range(layer.GetFeatureCount()): feature = layer.GetFeature(i) feature_name = feature.GetField("KECAMATAN") geometry = feature.GetGeometryRef() geometry_type = geometry.GetGeometryName() print i, feature_name, geometry_type
import ogr Sintak tersebut untuk mengimport librarry OGR yang merupakan library dari OSGEO yang dibuat untuk menulis dan membaca data vektor. shapefile = ogr.Open("D:\Master\Peta\DesaIndonesia.shp") Sintax diatas untuk membuka file DesaIndonesia.shp menggunakan library OGR. layer = shapefile.GetLayer(0) Sintax ini digunakan untuk menyimpan variable shapefile dalam sebuah datasource di libarry OGR, dimana datasource OGR dapat membaca beberapa informasi layer. Namun dalam contoh hanya terdapat 1 layer, dan kita mengakses 1 layer. for i in range(layer.GetFeatureCount()): feature = layer.GetFeature(i) Sintax tersebut digunakan untuk melakukan iterasi terhadap feature yang terdapat dalam shapefile, dan iterasi dilakukan untuk semua feature di file tersebut. feature_name = feature.GetField("KECAMATAN") Sintax tersebut untuk mendapatkan string dari field / kolom / atribut "KECAMATAN", dimana dalam file DesaIndonesia.shp tersebut terdapat kolom yang bernama KECAMATAN, dan ingat cara menulisnya harus sama anatara penggunaan huruf besar dan kecil karena penamaan tersebut bersifat case sensitive. geometry = feature.GetGeometryRef() Sintax tersebut digunakan untuk mendapatkan referensi geometri. geometry_type = geometry.GetGeometryName() Sintax tersebut digunakan untuk mendapatkan jenis geometry dari DesaIndonesia.shp. print i, feature_name, geometry_type Sintax tersebut untuk mencetak nilai i (urutan dari 0 sampai data terakhir), nama kecamatan dan jenis geometri dari file DesaIndonesia.shp. Demikianlah tulisan ini untuk melanjutkan klik Bagi yang sedang belajar Python untuk analisis geospasial akan berkaitan dengan beberapa library yang bisa digunakan untuk mengolah data spasial seperti GDAL untuk data raster, OGR untuk data vektor dan shapely untuk analisis operasi data spasial. Pada bagian awal tulisan Python untuk Analisis Geospatial, akan membahas persiapan Python dan beberapa library yang akan digunakan untuk analisis geospatial. Dalam hal ini akan dijabarkan langkah-langkah dalam menginstal Python, GDAL/OGR library, Shapely library dan library lain-lainya yang dperlukan. Dalam bagian pertama tulisan ini akan dijebarkan persiapan analisis geospatial dengan menggunakan python. Dalam uraian dibawah akan dijelaskan langkah-langkah dalam menginstall di Windows aplikasi Python, GDAL dan Shapely. 1. Install Python 2.7.14 link Python 2.7.14 2. Install GDAL untuk menginstall gdal python gunakan perintah Python -m pip install <lokasi file>\<file.whl> link GDAL windows Python 2.7 3. Install Shapely untuk menginstall shapely python gunakan perintah Python -m pip install <lokasi file>\<file.whl> Link Shapely Python 2.7 32 Bit Demikian semoga bermanfaat. @wawanhn. Sumber: https://pythongisandstuff.wordpress.com/2016/04/13/installing-gdal-ogr-for-python-on-windows/ Ada beberapa webhosting yang dapat digunakan untuk deploying aplikais web dengan menggunakan bahasa Python, salah satu yang terkenal adalah menggunakan website pythonanywhere.
$ mkvirtualenv --python=/usr/bin/python3.4 deploy <enter>
from flask import Flask app = Flask(__name__) @app.route('/') def index(): return '<h1>Deployed!</h1>' if __name__ == '__main__': app.run()
Demikian tulisan sederhana ini selamat mencoba... Bagi yang sedang utak-atik bahasa pemrograman Python, berikut saya share kode program untuk mengirim email dengan kode program sederhana. Untuk menulis kode program tersebut dapat menggunakan berbagai editor ataupun menggunakan shell atau cmd maupun ipython. Berikut kode programnya: #menggunakan python 2.7.5 #mengirim data ke gmail melalui python #hanya untuk gmail, bukan ymail atau yg lainnya #harus terkoneksi internet import smtplib from email.mime.text import MIMEText from email.MIMEMultipart import MIMEMultipart pengirim = '[email protected]' #masukkan email pengirim penerima = ('yyyygmail.com') #bisa satu penerima atau lebih msg = MIMEText('isi dari email') msg ['Subject'] = 'Mengirim email via python' msg ['From'] = pengirim msg ['To'] = penerima msg = MIMEMultipart() msg.attach(MIMEText(file('test.txt').read())) #buatlah file (satu folder) yg akan dikirim dgn program seperti [kita.txt] try: pwd = 'password' #isikan password gmail mu?? s = smtplib.SMTP_SSL() s.connect('smtp.gmail.com', 465) s.login(pengirim, pwd) s.sendmail(pengirim, penerima, msg.as_string()) s.quit() print 'Berhasil mengirim e-mail'#pesan ketika berhasil mengirim except Exception: print 'Koneksi gagal, silahkan coba lagi!'#pesan ketika tidak terkoneksi semoga bermanfaat. @wawanhn referensi: http://python113.blogspot.co.id/2014/04/mengirim-email-gmail-via-python.html 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 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: [email protected] 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. |