Devilzc0de Forum Follow @devilzc0de
  • Home
  • Hacking
  • Networking
  • Programming
  • O.S
  • Server
  • Tweets
  • Search
  • Member List
  • Calendar
Current time: 05-25-2013, 07:35 AM Hello There, Guest! (Login — Register)
Devilzc0de Forum › Information Technology › Programming › Python v
1 2 3 4 Next »

how to create login auth with django framework (python)

Home General Computer Multimedia Business Lounge

Post Reply 
Tweet
Threaded Mode | Linear Mode
how to create login auth with django framework (python)
11-17-2010, 08:38 AM
Post: #1
5ynL0rd Offline
DC Senior
***
Posts: 53
Joined: Oct 2010
Reputation: 14
how to create login auth with django framework (python)
tulisan ini sebelumnya saya tulis di forum rekan saya di cp27, so contoh2 apps dan projectnya masih nama cp27

ingin membuat website dengan python? kita bermain sedikit dengan framework django

download django 1.2.1 here:
http://www.djangoproject.com/download/1.2.1/tarball/

extract & install:
Code:
tar xzvf Django-1.2.1.tar.gz
cd Django-1.2.1
sudo python setup.py install

utk check apakah lib django sudah terinstall silahkan masuk ke shell python:
Code:
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> django.VERSION
(1, 2, 1, 'final', 0)
>>>

buat project utk web pertama kita di django:
Code:
$ django-admin.py startproject cp27
akan ada direktori voidnetwork pada current directory. isi direktori voidnetwork tersebut adalah sbb:
Code:
`-- cp27
    |-- __init__.py
    |-- manage.py
    |-- settings.py
    `-- urls.py

untuk menjalankan server masuk ke direktori cp27 kemudian:
Code:
$ python manage.py runserver
secara default server akan listening pada IP 127.0.0.1 port 8000
Code:
Validating models...
0 errors found

Django version 1.2.1, using settings 'cp27.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

check di browser dgn URL http://127.0.0.1:8000:
[Image: x.png]

pada project voidnetwork kita akan buat aplikasi bernama 'cp27'

Code:
$ python manage.py startapp cp27

nb: cp27 akan dikenali sebagai package pada direktori kerja voidnetwork

sekarang kita develop login page:
buat url login dan url utama yg diinginkan pada file cp27/urls.py

Code:
from django.conf.urls.defaults import *

urlpatterns += patterns('cp27.views',
    url(r'^/$', 'cpmain', name='cpmain'),
    url(r'^login/$', 'cplogin', name='cplogin'),
    (r'^admin/', include(admin.site.urls)),
)

setting database dan INSTALLED_APPS pada cp27/settings.py
contoh disini kita menggunakan postgresql. lengkapi isi dari file settings.py terutama DATABASES, TEMPLATE_DIRS, dan INSTALLED_APPS

settings.py
Code:
...
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'voidnetwork',                      # Or path to database file if using sqlite3.
        'USER': 'postgres',                      # Not used with sqlite3.
        'PASSWORD': 'postgres',                  # Not used with sqlite3.
        'HOST': '127.0.0.1',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '5432',                      # Set to empty string for default. Not used with sqlite3.
    }
...
TEMPLATE_DIRS = (
    '/<absolute path ke templates>/'
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)
...
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    # Uncomment the next line to enable the admin:
    'django.contrib.admin',
    'cp27', # nama apps yg ditambah
)

masuk ke db engine menggunakan psql:
Code:
$ psql -h 127.0.0.1 -U postgres -W
command utk create database:
Code:
postgres=# CREATE DATABASE voidnetwork;

synchronize database:
Code:
$ python manage.py sql cp27
$ python manage.py syncdb
output jika berhasil kurang lebih sbb:
Code:
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_user_permissions
Creating table auth_user_groups
Creating table auth_user
Creating table auth_message
Creating table django_content_type
Creating table django_session
Creating table django_site
Creating table django_admin_log

You just installed Django's auth system, which means you don't have any superusers defined.
Would you like to create one now? (yes/no):
Would you like to create one now? (yes/no): yes
Username (Leave blank to use 'synl0rd'):  
E-mail address: root@voidnetwork.org
Password:
Password (again):
Superuser created successfully.
Installing index for auth.Permission model
Installing index for auth.Group_permissions model
Installing index for auth.User_user_permissions model
Installing index for auth.User_groups model
Installing index for auth.Message model
Installing index for admin.LogEntry model
No fixtures found.
pilih yes utk membuat account superuser django, kemudian isi email dan password yg anda inginkan.

setelah berhasil mari kita lihat halaman admin django dengan URL: http://127.0.0.1:8000/admin
jgn lupa utk menjalankan server (wsgi django).

kurang lebih tampilan admin pagenya adalah sbb:
[Image: y.png]
yak kita skip dlu mainan admin nya, sekarang kita bangun halaman utama dan halaman login yg kita inginkan.

Kita akan membuat login page berdasarkan authentification user yg ada di django sendiri (kita tidak membuat tabel sendiri untuk user).

nb: ada beberapa cara untuk membuat login page, yg saya contohkan adalah cara paling jadul, next tutor akan saya berikan cara mudahnya menggunakan decorator login required

sebelumnya kita sudah isi absolute path utk template, di laptop gw mungkin di '/home/synl0rd/voidnetwork/cp27/template' (sesuaikan dengan kondisi direktori masing2).
pada direktori template buatlah 2 buah page html. untuk contoh ini gw asumsikan sbb:

nb: template gw buat seadanya, hias sendiri selebihnya kalo mau keren

cp27/template/index.html
Code:
<html>
<title>INDEX PAGE</title>
<body>
<h1> Welcome to Index page CP27 </h1>
<a href='logout'>logout</a>
</body>
</html>

cp27/template/login.html
Code:
<html>
<title>LOGIN PAGE</title>
<body>
<form action="" method="post">
    <label for="username">User name:</label>
        <input type="text" name="username" value="" id="username"><br>
    <label for="password">Password:</label>
        <input type="password" name="password" value="" id="password"><br>
    <input type="submit" value="login" />
</form>
{% if staff_stat %}
    <blink>Sorry u are not staff</blink>
{% else %}
{% endif %}

{% if errors %}
    <blink>Sorry, that's not a valid username or password</blink>
{% else %}
{% endif %}

selanjutnya kita isi cp27/views.py dengan script sbb:
Code:
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.views.decorators.csrf import csrf_exempt
from django.contrib import auth

@csrf_exempt
def cplogin(request, error=False):
    username = request.POST.get('username', '')
    password = request.POST.get('password', '')
    user = auth.authenticate(username=username, password=password)

    if user is not None and user.is_active:
        auth.login(request, user)
        return HttpResponseRedirect('/')
    elif username == '' and password == '':
        pass
    else:
        errors = True
    return render_to_response('login.html',locals())

def cplogout(request):
    auth.logout(request)
    return HttpResponseRedirect('../login')

@csrf_exempt
def cpmain(request, staff_stat = False):
    oten = request.user
    if not oten.is_authenticated():
        return HttpResponseRedirect("login")
    else:
        if oten.is_staff == False:
            auth.logout(request)
            staff_stat = True
            return render_to_response('login.html', locals())
        else:
            return render_to_response('index.html')
pada script views kita mendefinisikan 3 function:
- cpmain() = sebagai handle halaman utama
perhatikan urls.py
Code:
url(r'^$', 'cpmain', name='cpmain'),
saya mengarahkan URL utama ke handle function cpmain(), pada function tersebut ada proses checking apakah keadaan sesi sedang autehenticated atau tidak. jika tidak redirect ke template login, jika ya tampilkan halaman index. Disitu juga sedikit sy tambahkan untuk pengecekan staff/not staff (silahkan lihat page admin untuk status tersebut)

- cplogin() = function yang dijalankan ketika URL mengarah ke http://127.0.0.1:8000/login
- cplogout() = function yang dijalankan ketika URL mengarah ke http://127.0.0.1:8000/logout

untuk screenshot mungkin tidak perlu, karena hanya halaman login biasa dan welcome page utk index (bisa lihat di template/)

nb: tutorial kali ini belum masuk ke models hanya sebatas authentification semata

kalau ada yg bingung di diskusikan saja, banyak yg mesti dijelaskan seperti templating atau tanda @csrf_exempt, dll

semoga bermanfaat, mohon maaf apabila ada kekurangan.

thnks & regards
5ynL0rd

cth site sederhana menggunakan django framework:
http://void-labs.org (my site with django + mongodb [document oriented database])
http://www.lawrence.com/
http://projects.washingtonpost.com/
http://www.tabblo.com/
dan masih banyak lagi
Visit this user's website Find all posts by this user
Quote this message in a reply
11-17-2010, 04:01 PM (This post was last modified: 11-17-2010 04:01 PM by supermenganteng.)
Post: #2
supermenganteng Offline
SPA Holic
********
Jendral Team
Posts: 1,961
Joined: Jun 2010
Reputation: -188
RE: how to create login auth with django framework (python)
wow..nice bro..ijin mempelajari , biar gak ketinggalan ilmu ane
Find all posts by this user
Quote this message in a reply
08-20-2011, 08:44 PM
Post: #3
deadpool Offline
./Devilz 1st Cadet
Posts: 6
Joined: Jul 2011
Reputation: 0
RE: how to create login auth with django framework (python)
bro, boleh add ym ga nih? mau tanya2 seputar python n django nih
Find all posts by this user
Quote this message in a reply
10-20-2012, 12:36 AM
Post: #4
ulZaAceh Offline
./Devilz 1st Cadet
Posts: 41
Joined: Jul 2011
Reputation: 1
RE: buy nexium online 15853
waawww...
tread a bagus tapi sangat susah di pelajari
nice tread a kk,banggabangga
Visit this user's website Find all posts by this user
Quote this message in a reply
12-07-2012, 11:57 AM
Post: #5
xombix Offline
./Devilz 1st Cadet
Posts: 23
Joined: Sep 2010
Reputation: 0
RE: how to create login auth with django framework (python)
nice thread kk smangat
ane pelajari dulu kk belajar
Find all posts by this user
Quote this message in a reply
04-25-2013, 06:17 AM
Post: #6
1g0rpr3m4nk4mpus Offline
./Devilz 1st Cadet
Posts: 3
Joined: Jul 2011
Reputation: 0
RE: how to create login auth with django framework (python)
wow good jom synlord
Find all posts by this user
Quote this message in a reply
04-25-2013, 08:06 AM
Post: #7
dophponh Offline
Banned
Posts: 1
Joined: Dec 2012
nordstrom coupon code Nkkfgqx
Cover it all with water, bring to a boil and then simmer, covered for three hours or so. We talked a little about water safety. Nike Free Run I weigh 210lbs plus 80 pounds of gear.. It all depends on your skin tone, hair, and other physical features.
nike free run 2 The first is that dogs don't have feelings. The look of both the Beetle and the PT Cruiser provoked an emotional response in buyers who had a fondness for the cars' predecessors.
The captivating looks were created by folding single pieces of jewel-toned silk twill and wool Melton. Normally i don act as flamboyant as my disposition gives off but i don act "manly" at the same time. http://www.brandsunglassesaustralia.com
You need to have socks and probably run out of them frequently or run through them often if you are like most people. This could result in slipped discs and torn tendons.
http://www.frairmaxpascher.fr Residents of Michigan may purchase any pellet gun except for pellet guns or BB guns measuring 30 inches or less (overall length).
Visit this user's website Find all posts by this user
Quote this message in a reply
« Next Oldest | Next Newest »
Post Reply 


Topic Tools
Topic Link :
BBCode :
HTML Code :
View a Printable Version Send Thread to a Friend Subscribe to this thread
Submit Google Submit Face book Submit to Digg Submit to Reddit Submit to Furl Submit to Del.icio.us Submit to Jeqq

Possibly Related Threads...
Thread: Author Replies: Views: Last Post
Thumbs Up Belajar Python GUI Gaya Baru candragati 20 764 05-18-2013 07:49 PM
Last Post: dewa-crot
  NGOPREK Bahasa Pemprograman (Python) Bunga.Mataharry 29 7,286 04-30-2013 06:07 PM
Last Post: pr4bu_51l1w4n61
Star [Tutor] Materi DIC "Basic Programming Python" root31 20 433 04-23-2013 07:56 AM
Last Post: orochimadit
  [PYTHON] Install Python di Windows sang.sakaya 12 3,899 04-19-2013 03:40 PM
Last Post: fata
  [cloning] nembak cewek dengan python test 13 419 03-31-2013 11:58 AM
Last Post: 2easy4me
  Belajar bahasa pemrograman Python whitehat 17 5,376 03-03-2013 08:01 PM
Last Post: eM.eL
  [Tutor] [Share]Program Pencacah Pecahan dengan Python hitheir 5 354 02-24-2013 02:21 PM
Last Post: ghosthands
  [Tutor] Slideshare Disabled Python Looping Slide Download hitheir 9 205 01-27-2013 05:53 PM
Last Post: sotbot
  django alessandra 11 292 01-25-2013 12:45 AM
Last Post: whitecoinDC
  [cloning] Segitiga bolak balik di python test 5 223 12-15-2012 09:17 AM
Last Post: qpdll

Users Browsing
1 Guest(s)

  • Contact Us
  • devilzc0de
  • Return to Top
  • Mobile Version
  • RSS Syndication
  • Help
Current time: 05-25-2013, 07:35 AM Powered By MyBB, © 2002-2013 MyBB Group. Theme created by Justin S. | Mixed By Chaer.Newbie | Fixed By Aditya

USING THIS SITE INDICATES THAT YOU HAVE READ AND ACCEPT OUR TERMS. IF YOU DO NOT ACCEPT THESE TERMS, YOU ARE NOT AUTHORIZED TO USE THIS SITE