Roshan Book

My Tech Notebook

Django revision 2


Dictionaries,tuple and lists

Setting up templates

1. Create templates folder in root of your project

2. Add this code to top of settings.py

import os.path
DIRNAME=os.path.abspath(os.path.dirname(__file__))

3. Go to TEMPLATE_DIRS = ( and add

os.path.join(os.path.dirname(__file__), ‘templates’ ),

That is it

Setting up css, js

1. Create a folder static in root of project

2. To Media root and Media url add

MEDIA_ROOT = os.path.join(DIRNAME,’static/’)

MEDIA_URL = ‘/static/’

3. Go to urls.py

4. To the top add – import os and then –  static=os.path.join(os.path.dirname(__file__),’static’)

5. To urlpatterns = patterns(”, add

(r’^static/(?P<path>.*)$’, ‘django.views.static.serve’,{‘document_root’: static}),

That is it

You can refer to them in templates as you do normally like

<link rel=”stylesheet” type=”text/css”
href=”/static/css/style.css” />

* Add following code to your model def to see values by name

def __unicode__(self):
return self.name

Few useful Notes

Start a project : django-admin.py startproject mysite

Running a server :python manage.py runserver 8080

Sync database :python manage.py syncdb

Creating an app -python manage.py startapp polls

Add a app to settings.py – below installed app ‘projectname.appname’

Add a middleware class to enable login logout functionality out of the box -‘django.middleware.csrf.CsrfResponseMiddleware’,

Looking at sql :python manage.py sql polls

Running a python shell :python manage.py shell

Inside shell looking at attributes of user class

@login_required – to save a view to login required. Add from django.contrib.auth.decorators import login_required – to top of views.py

>>from django.contrib.auth.models import User

>>dir(user)

Few useful reference charts
Regular Expression

Models Field Type 
Available Formfieldtypes and Widgets 


Additonal parameters forformfieldtypes

Create folder by name

modifying admin view

DataEntry via shell

Look at : https://docs.djangoproject.com/en/1.3/intro/tutorial01/

Form to database

Create form.py

call the class into views

refer to a template

Rendering the form:

3 types:

form.as_table()
This command will give you a long output in which you will see the HTML
rendering of the form using table tags. You can also render the form using ul
and p tags by calling form.as_ul() and form.as_p() respectively.

Creating a form inside forms.py

from django import forms
import re
from django.contrib.auth.models import User

class RegistrationForm(forms.Form):
username=forms.CharField(label=u’Username’, max_length=30)
email=forms.EmailField(label=u’Email’)
password1=forms.CharField(label=u’Password’, widget=forms.PasswordInput())
password2=forms.CharField(label=u’Password (Again)’,widget=

Templates notes

1. Create base.html in template directory

2. To the next template include base.html by using -{% extends “base.html” %}

3. In base.html use blocks like – {% block title %}{% endblock %}

4. In next template override this block as {% block title %}Welcome to B2wPms{% endblock %}

5. Call a database variable inside template as – Welcome {{project. user.username }}

6. calling a form inside template

<form method=”post” action=”.”>
{{ form.as_p }}
<input type=”submit” value=”save” />
</form>

include tag – {% include “bookmark_list.html” %}

Database to table

Direct to template concept

Datamodel relationships – view this

Decoupling Django app

Copy the file mysite/urls.py to polls/urls.py. Then, change mysite/urls.py to remove the poll-specific URLs and insert aninclude(), leaving you with:

# This also imports the include function
from django.conf.urls.defaults import *

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    url(r'^polls/', include('polls.urls')),
    url(r'^admin/', include(admin.site.urls)),
)

include() simply references another URLconf. Note that the regular expression doesn’t have a $ (end-of-string match character) but has the trailing slash. Whenever Django encounters include(), it chops off whatever part of the URL matched up to that point and sends the remaining string to the included URLconf for further processing.

 

Enabling admin interface

  • Add "django.contrib.admin" to your INSTALLED_APPS setting.
  • Run python manage.py syncdb. Since you have added a new application to INSTALLED_APPS, the database tables need to be updated.
  • Edit your mysite/urls.py file and uncomment the lines that reference the admin – there are three lines in total to uncomment. This file is a URLconf; we’ll dig into URLconfs in the next tutorial. For now, all you need to know is that it maps URL roots to applications. In the end, you should have a urls.py file that looks like this:
    from django.conf.urls.defaults import patterns, include, url
    
    # Uncomment the next two lines to enable the admin:
    from django.contrib import admin
    admin.autodiscover()
    
    urlpatterns = patterns('',
        # Examples:
        # url(r'^$', 'mysite.views.home', name='home'),
        # url(r'^mysite/', include('mysite.foo.urls')),
    
        # Uncomment the admin/doc line below to enable admin documentation:
        # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    
        # Uncomment the next line to enable the admin:
        url(r'^admin/', include(admin.site.urls)),
    )

    (The bold lines are the ones that needed to be uncommented.)

     

    Create admin.py in apps folder : 

    And add following codes :

    from django.contrib import admin
    from bookmarks.models import *

    class LinkAdmin(admin.ModelAdmin):
    list_display = (‘title’, ‘link’, ‘user’)

    list_filter = (‘user’,)

    ordering = (‘title’,)
    search_fields = (‘title’,)

    admin.site.register(Link, LinkAdmin)

    Do this for all the models for which you want to enable admin features.

    Customizing Admin interface

    Go to /usr/lib/pythonX.X/site-packages/django

    These files are important:

    admin/base_site.html: This is the base template for the administration interface. All the pages inherit from this template.

    admin/change_list.html: This template generates a list of available objects in a particular model.

    admin/change_form.html: This template generates a form for adding or editing an object.

    admin/delete_confirmation.html: This template generates the confirmation page when deleting an object.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: