Search Google

Tuesday 9 June 2015

django tutorial for beginners create your first app

 

django-admin.py startproject myproject
creates a project and files like
  • __init__.py use files as an global modules
  • manage.py to manage project like, Syncdb, migrate, startserver
  • settings.py Contains The Project Settings
  • urls.py Contains Project URL,you can include the app url file
python manage.py startapp appname
creates a app inside my project and files like
  • __init__.py use files as an global modules
  • models.py You can write your model classes here
  • tests.py To write test cases
  • views.py App URLs

1 django-admin.py startproject myproject
creates a project and files like init.py, manage.py, settings.py, urls.py
2 python manage.py startapp appname
creates a app inside my project and files like init.py, models.py, tests.py, views.py
-------------------------------------------------------------------

Getting Django setup on Windows

A friend asked me how to setup an Django enviroment on Windows without the Cygwin fuzz. Here is the shortest steps I can think of:

1. Install Python3.4 as default path. (It should be "C:\Python34").
2. Open cmd.exe program on Windows and run the following commands:

    set PATH=%PATH%;C:\Python34;C:\Python34\Scripts
    pip install django
    python C:\Python34\Lib\site-packages\django\bin\django-admin.py startproject mysite
    cd mysite
    python manage.py syncdb

    (Follow prompts to setup an initial db. remember the user you used here.)

    python manage.py runserver

3. You are ready to django! Open your browser http://127.0.0.1:8000 to verify.
    Or login into http://127.0.0.1:8000/admin with the user you setup above.
  
What's next?
    Explore django with a guided tutorial here:
    https://docs.djangoproject.com/en/1.6/intro/tutorial01

  ----------------------------------------------------------------------------------




Django Basics - Installing Django and Setting Up a Project and App


This brief tutorial shows the basics of installing and setting up a simple app in Django that is used to submit and retrieve information about books you've read:
  • Part 1 - Installing and Setting up Django
  • Part 2 - Creating the Database Model
  • Part 3 - Django API vs Admin site
  • Part 4 - Django Templates and Views
Each part includes an accompanying video. You can download the source via Github - which includes all four parts. I will be delivering this tutorial from a Windows-perspective, but the Mac OS X perspective is pretty much the same.
This tutorial follows the first few sections of the official Django tutorial.
Videos - Part 1, Part 2, Part 3, Part 4
GitHub - https://github.com/mjhea0/django-tutorial
Django?
Developed in 1995 Django is one of, if not the most, popular Python web frameworks. It promotes rapid development via the model-view-controller architecture. You can learn more about it here.
Prerequisites:
  • You have Python 2.7 installed.
  • You have PIP installed. To install, you need to first install setup tools. Click here for a brief tutorial on how to do that. Then you can just run the command easy_install pip from the command prompt to install PIP.

Alright let's get started …

Part 1 - Installing Django

Open the command prompt with admin privileges and run the command-




pip install Django
-to install Django into your site-packages directory.

To setup, you need to create a new project. Within command prompt, navigate to the directory you wish to create the new project, then run the command -




python C:\Python27\Lib\site-packages\django\bin\django-admin.py startproject testproject
Your path to *django-admin.py* may be different, so make sure to tailor it if necessary. Also, *testproject* is the name of the created project. Feel free to name this whatever you like. ### Next you need to make sure everything was setup correctly. To do that, you can launch the Django server. First, navigate to your newly created directory (*testproject*, in my case), and then run the command-
python manage.py runserver
Open up a new browser window and navigate to http://localhost:8000/. If setup correctly, you will see the Welcome to Django screen. ### Let’s setup the database. Open up *settings.py* in the *testproject* directory with a text editor. (I use Notepad++.) Append *sqlite3* to the end of the Engine key and then add the path to the name key. You can name the database whatever you’d like because if the database doesn’t exist, Django will create it for you in the next step. The results should look like something similar to this (depending upon your path)-
'ENGINE': 'django.db.backends.sqlite3',    
'NAME': 'C:/Python27/django/testproject/test.db',
(Yes, use forward slashes.)

Finally, you need to create and then sync the database by navigating to the directory where manage.py is located (should be the project's main directory) and then running the following command-




python manage.py syncdb
Create a superuser. I used admin for both my username and password.
Alright, the setup is complete. You're now ready to start creating an app.

Part 2 - Creating the Database Model

Start by creating an app. Within command prompt, navigate to the testproject directory and then type the command-




python manage.py startapp books
CD into the directory. You should see a models.py file. This file is used to setup the entities and attributes for your database.

Go ahead and open models.py in Notepad++ and add in the following code:




class Books(models.Model):
  title = models.CharField(max_length=150)
  author = models.CharField(max_length=100)
  read = models.CharField(max_length=3)
This code should be relatively clear. This class defines the database fields- title, author, and read. The data in the read field will either be "yes" or "no" depending on whether you've read the book or not.
Since there is only one table, we don't need to establish a foreign key. The primary key, a unique id, will be automatically generated for us by Django's magic.
Save the file.

Now open up the settings.py file, scroll down to Installed Apps and add the app name, books, to the installed apps so that Django knows to include it. Your installed apps section should look like this-




INSTALLED_APPS = (
  'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
  'books',
    # Uncomment the next line to enable the admin:
    # 'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
)
Save the file.

CD back to the main project directory and run the command-




python manage.py sql books
-to display the actual SQL statements for creating the table. Did you notice the primary key?
Your output should look like this-



BEGIN;
CREATE TABLE "books_books" (
    "id" integer NOT NULL PRIMARY KEY,
    "title" varchar(150) NOT NULL,
    "author" varchar(100) NOT NULL,
    "read" varchar(3) NOT NULL
)
;
COMMIT;
You can also use the following command to check to see if there are any errors in your models-



python manage.py validate

Finally, you need to run the following command to execute the SQL statements:




python manage.py syncdb
Next, I'll show you how to access the Django API to add data to the database.

Part 3 - Django API vs Admin site

First open up command prompt, navigate to your project directory, and then run the command-




python manage.py shell
This opens an interactive environment for us to use.

Next go ahead and import your app with the following command-




from books.models import Books

There's a number of different things you can do within this environment, but let's stick with adding data to our database. To add a row, run this command-




b = Books(title="To Kill a Mockingbird", author="Harper Lee", read="yes")
b.save()
b = Books(title="Brave New World", author="Aldous Huxley", read="yes")
b.save()
b = Books(title="War and Peace", author="Leo Tolstoy", read="no")
b.save()
Go ahead and add as many books as you'd like for practice.
Once complete, you can view the data in your database in a number of ways. I like to just use SQLite, which can be downloaded here. So, go ahead and open the text.db file which is located within your project's main directory, switch to the Browse Data tab, and then under the Table dropdown choose books_books. You should see all the books you added.
You can exit the Django interactive environment using the exit() command.
Okay, let's look at an even easier means of adding data using Django's admin site.

Open the settings.py file, scroll down to Installed Apps and uncomment the line 'django.contrib.admin',. Then save the file.

Update the database by running the command-




python manage.py syncdb

Next open the urls.py file within the books directory. You need to uncomment these three lines-




from django.contrib import admin
admin.autodiscover()
url(r'^admin/', include(admin.site.urls)),
Save the file and exit.

Now create a new file in your books directory called admin.py and add the following code to the file-




from books.models import Books
from django.contrib import admin
admin.site.register(Books)

Next, open up your models.py file and add these two lines of code-




def __unicode__(self):
  return self.title + " / " + self.author + " / " + self.read
Essentially, self refers to the current object.

Now start the development server - python manage.py runserver, point your browser to http://localhost:8000/admin, and enter your login credentials. You should see the Books app. And if you click the app, you should now see the data we added earlier.

Go ahead and add a few more books in. Try deleting a row as well. See how much easier that is in the Admin console?
So we're done with the Admin console. Hit CTRL+BREAK to exit. I'm also done showing you how to create and modify your app's model(s). Next, we'll look at how to modify what the user sees (views and templates).

Part 4 - Django Templates and Views

Again, in this final tutorial I'll go over how to create the public interface.

The first thing we need to do is setup the URL structure. Open up urls.py and then add this code to the urlpatterns-




url(r'^books/$', 'books.views.index'),
This is essentially a tuple that points a user to a Django page based on the URL that user visits. In this case the regular expression dictates that when the user visits any page with the ending /books they will be see the books.views.index page. This is a bit complicated, so be sure to visit the Django tutorial for more into.

Now to ensure that this is setup correctly run the server and then point your browser to http://localhost:8000/books.

As long as you get the error, ViewDoesNotExist at /books, then the url is setup correctly.
We need to actually write the view now.

Stop the server (CRTL+BREAK) and then within the books directory open views.py in Notepad++ and write the following code to test out your views-




from django.http import HttpResponse
def index(request):
  return HttpResponse("Hello. This is a test.")
Save the file. Run the server. And refresh the page. You should no longer see an error. Instead, you should just see a page with the words Hello. This is a test. in the top corner.

Okay, now let's display something a bit more meaningful - like a listing of all the books in the database. To do that, you need your views.py file to look like this-




from django.http import HttpResponse
from books.models import Books
def index(request):
    books_list = Books.objects.all()
    return HttpResponse(books_list)
-and then just hit refresh on your browser. (Remember: we didn't stop the server).
You should see all of the books in one long line. It looks bad, but it works.
Next, we're going to work with templates, which will allow us to easily create a much more readable output.

Start by making a new directory in the django directory, outside of the project, called templates. Within that directory, make a directory called books.

Next open up settings.py, scroll down to TEMPLATE_DIRS and add the template directory-




"C:/Python27/django/templates"
Yes, those are forward slashes. ### Now create a new file in your *temples\books* directory. Save it as index.html and add the following code-
<h1>My Fab Book Collection</h1>
{% if books_list %}
<ul>
{% for b in books_list %}
    <li>{{b.title}} | {{b.author}} | {{b.read}}</li>
{% endfor %}
</ul>
{% endif %}

Open views.py again and make it looks like this-




from django.http import HttpResponse
from books.models import Books
from django.template import Context, loader      
def index(request):
  books_list = Books.objects.all()
  t = loader.get_template('books/index.html')
  c = Context({'books_list': books_list,})
  return HttpResponse(t.render(c))
Basically, the loader is the path to the template we created, which then gets assigned to the Python object via the Context dictionary.

Save the file. Run the server. Refresh the http://localhost:8000/books page. There's the books. Looks a little better, too.

I know I said that I'd show to make it so a non-administrator can add data to the database - but I just realized that this would be another lesson in itself. So, I'm going to stop here. Feel free to view the Django Tutorial to learn how to add that functionality to your application.
In fact, the whole point to these tutorials is for you to get started with the Django tutorial. I bounced around a bit but I hope that you can now go through the tutorial a bit easier now that you have a starting off point.
Thanks for watching. See you next time.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 from http://www.programmersbook.com/page/21/Django-Beginner-Tutorial-Part-I/

  work with database command 

syncdb create the required tables as follows: 

 C:\DjangoProjects\mysite>python manage.py syncdb

http://stackoverflow.com/questions/4795045/django-syncdb-failes-when-adding-super-user-windows-7-mysql-django-1-2-4-mys 

-----------------------------------

Django is a free web framework written in python. It's very to use!

Let's create a blog in less then 10min!

1. First create a project

django-admin.py startproject blog

Switch to folder "blog"

Start the dev server

./manage runserver 8000

Type: http://127.0.0.1:8000 in browser


2. Create a file "models.py"

 Create a model

from django.db import models

class Blog(models.Model):
    title = models.CharField(max_length=32)
    date = models.DateTimeField(auto_now_add=True)
    text = models.TextField()

3. Setup your database settings

Edit the file "settings.py"

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'test',                      # Or path to database file if using sqlite3.
        'USER': 'test',                      # Not used with sqlite3.
        'PASSWORD': 'password',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}

4. "Install" the blog models

Add "blog" to INSTALLED_APPS

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'blog', #<-------------------------------
    # Uncomment the next line to enable the admin:
    #'django.contrib.admin',
)

5. Create a templates

Create folder "templates".

Switch to folder "templates". Create file "index.html"

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>My Blog</title>
    </head>

<body>
    <div id="content">
    {% block content %}
    {% endblock %}
    </div>
</body>

</html
6. Setup the templates path
Edit "settings.py" file.
Import os at the top
Add path to TEMPLATES_DIRS
TEMPLATE_DIRS = (
    # 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.
    os.path.join(os.path.dirname(__file__),'templates'), # creates a absolute path
)

7. Create the blog tables

Run "./manage syncdb"

It will create the blog tables.
It will ask you to create a superuser, follow the instructions

8. Add a url pattern

Edit file "urls.py"

urlpatterns = patterns('',
    # Example:
    # (r'^blog/', include('blog.foo.urls')),
    (r'^, 'blog.views.index'), #<------------------- index/root entry

    # Uncomment the admin/doc line below and add 'django.contrib.admindocs' 
    # to INSTALLED_APPS to enable admin documentation:
    # (r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    #(r'^admin/', include(admin.site.urls)),
)

9. Create a view

Create a file "views.py"
from django.shortcuts import render_to_response

def index(request):
    return render_to_response('index.html', locals())

Run the dev server: ./manage runserver 8000


10. Activate the admin

Uncomment "django.contrib.admin" in INSTALLED_APPS
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'blog',
    # Uncomment the next line to enable the admin:
    'django.contrib.admin', #<<<------- uncommented
)

Edit "urls.py" file

from django.conf.urls.defaults import *

# Uncomment the next two lines to enable the admin:
from django.contrib import admin #<<< uncomment this
admin.autodiscover() #<<< uncomment this

urlpatterns = patterns('',
    (r'^, 'blog.views.index'),
    # Uncomment the next line to enable the admin:
    (r'^admin/', include(admin.site.urls)), #<<< uncomment this
)

Run ./manage syncdb

11. Activate the module in admin

Create file "admin.py"

from django.contrib import admin
from blog.models import Blog

class AdminBlog(admin.ModelAdmin):
    pass

admin.site.register(Blog, AdminBlog)

Type "http://127.0.0.1:8000/admin" in your browser

Login as superuser which you choose before


Click on "Add" and create some posts

12. Fill the view with logic

from django.shortcuts import render_to_response
from blog.models import Blog

def index(request):
    entries = Blog.objects.all()
    return render_to_response('index.html', locals())

13. Show it in template

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>My Blog</title>
    </head>

<body>
    <div id="content">
    {% block content %}
        {% for e in entries %}
            {{ e.title }}<br/>
            {{ e.date }}<br/>
            {{ e.text }}<br/>
            <hr/>
        {% endfor %}

    {% endblock %}
    </div>
</body>

</html>
Type http://127.0.0.1:8000 in your browser and you see your blog!



-------------------------------------------------------------------------------------
Every view renders a webpage. For this Django has a own template system.
1. First we create a templates folder in our root project and change into it
2. Now create a folder what ever you like, the best would be the name of the application, like homepage and change into it
3. When create a index.html, to make clear that is the entry point of this application template
4. Create your our html template or for example:

<html>
<head>
    <title>My Blog Index</title>
</head>
<body>
    <h3>Index Page</h3>
</body>
</html>


5. Open the global settings
6. Import on the top the os module and modify the TEMPLATE_DIRS variable and add the path, for example
import os
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
    # ('Your Name', 'your_email@example.com'),
)
#....
TEMPLATE_DIRS = (
    # 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.
    os.path.join( os.path.dirname(__file__), 'templates' ),)
#....

7. Open the views.py file
8. Import the render_to_response function. This will do the job for you, parse a template and return a valid HttpResponse object.
9. Use the render_to_response in the view, for example
from django.shortcuts import render_to_response
def index(request):
    return render_to_response('homepage/index.html')  
10. The first parameter is the template.
11. Start the dev server: python manage.py runserver



-------------



-------------------------------------------

http://geonode.readthedocs.org/en/latest/tutorials/devel/projects/apps.html#

Adding additional Django apps to your GeoNode Project

Since GeoNode is based on Django, your GeoNode project can be augmented and enhanced by adding additional third-party pluggable Django apps or by writing an app of your own.
This section of the workshop will introduce you to the Django pluggable app ecosystem, and walk you through the process of writing your own app and adding a blog app to your project.

Django pluggable apps

The Django app ecosystem provides a large number of apps that can be added to your project. Many are mature and used in many existing projects and sites, while others are under active early-stage development. Websites such as Django Packages provide an interface for discovering and comparing all the apps that can plugged in to your Django project. You will find that some can be used with very little effort on your part, and some will take more effort to integrate.

Adding your own Django app

Let’s walk through the an example of the steps necessary to create a very basic Django polling app to and add it to your GeoNode project. This section is an abridged version of the Django tutorial itself and it is strongly recommended that you go through this external tutorial along with this section as it provides much more background material and a signficantly higher level of detail. You should become familiar with all of the information in the Django tutorial as it is critical to your success as a GeoNode project developer.
Throughout this section, we will walk through the creation of a basic poll application. It will consist of two parts:
  • A public site that lets people view polls and vote in them.
  • An admin site that lets you add, change, and delete polls.
  1. Create app structure
    Since we have already created our GeoNode project from a template project, we will start by creating our app structure and then adding models:
    $ python manage.py startapp polls
    
    That’ll create a directory polls, which is laid out like this:
    polls/
        __init__.py
        models.py
        tests.py
        views.py
    
    This directory structure will house the poll application.
  2. Add models
    The next step in writing a database web app in Django is to define your models—essentially, your database layout with additional metadata.
    In our simple poll app, we’ll create two models: polls and choices. A poll has a question and a publication date. A choice has two fields: the text of the choice and a vote tally. Each choice is associated with a poll.
    These concepts are represented by simple Python classes.
    Edit the polls/models.py file so it looks like this:
    from django.db import models
    
    class Poll(models.Model):
        question = models.CharField(max_length=200)
        pub_date = models.DateTimeField('date published')
        def __unicode__(self):
            return self.question
    
    class Choice(models.Model):
        poll = models.ForeignKey(Poll)
        choice = models.CharField(max_length=200)
        votes = models.IntegerField()
        def __unicode__(self):
            return self.choice
    
    That small bit of model code gives Django a lot of information. With it, Django is able to:
    • Create a database schema (CREATE TABLE statements) for this app.
    • Create a Python database-access API for accessing Poll and Choice objects.
    But first we need to tell our project that the polls app is installed.
    Edit the <my_geonode>/settings.py file, and update the INSTALLED_APPS setting to include the string “polls”. So it will look like this:
    INSTALLED_APPS = (
    
        # Apps bundled with Django
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.sites',
        'django.contrib.admin',
        'django.contrib.sitemaps',
        'django.contrib.staticfiles',
        'django.contrib.messages',
        'django.contrib.humanize',
    
        #Third party apps
    
        # <snip>
    
        # GeoNode internal apps
        'geonode.maps',
        'geonode.upload',
        'geonode.layers',
        'geonode.people',
        'geonode.proxy',
        'geonode.security',
        'geonode.search',
        'geonode.catalogue',
        'geonode.documents',
    
        # My GeoNode apps
        'polls',
    )
    
    Now Django knows to include the polls app. Let’s run another command:
    $ python manage.py syncdb
    
    The syncdb command runs the SQL from sqlall on your database for all apps in INSTALLED_APPS that don’t already exist in your database. This creates all the tables, initial data, and indexes for any apps you’ve added to your project since the last time you ran syncdb. syncdb can be called as often as you like, and it will only ever create the tables that don’t exist.
    GeoNode uses south for migrations ...
  3. Add Django Admin Configuration
    Next, let’s add the Django admin configuration for our polls app so that we can use the Django Admin to manage the records in our database. Create and edit a new file called polls/admin.py and make it look like the this:
    from polls.models import Poll
    from django.contrib import admin
    
    admin.site.register(Poll)
    
    Run the development server and explore the polls app in the Django Admin by pointing your browser to http://localhost:8000/admin/ and logging in with the credentials you specified when you first ran syncdb.
    ../../../_images/admin_top.png
    You can see all of the other apps that are installed as part of your GeoNode project, but we are specifically interested in the Polls app for now.
    ../../../_images/admin_polls.png
    Next we will add a new poll via automatically generated admin form.
    ../../../_images/add_new_poll.png
    You can enter any sort of question you want for initial testing and select today and now for the publication date.
    ../../../_images/add_poll.png
  4. Configure Choice model
    The next step is to configure the Choice model in the admin, but we will configure the choices to be editable in-line with the Poll objects they are attached to. Edit the same polls/admin.py so it now looks like the following:
    from polls.models import Poll, Choice
    from django.contrib import admin
    
    class ChoiceInline(admin.StackedInline):
        model = Choice
        extra = 3
    
    class PollAdmin(admin.ModelAdmin):
        fieldsets = [
            (None,               {'fields': ['question']}),
            ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
        ]
        inlines = [ChoiceInline]
    
    admin.site.register(Poll, PollAdmin)
    
    This tells Django that Choice objects are edited on the Poll admin page, and by default, provide enough fields for 3 choices.
  5. Add/edit poll
    You can now return to the Poll admin and either add a new poll or edit the one you already created and see that you can now specify the poll choices inline with the poll itself.
    ../../../_images/choice_admin.png
  6. Create views
    From here, we want to create views to display the polls inside our GeoNode project. A view is a “type” of Web page in your Django application that generally serves a specific function and has a specific template. In our poll application, there will be the following four views:
    • Poll “index” page—displays the latest few polls.
    • Poll “detail” page—displays a poll question, with no results but with a form to vote.
    • Poll “results” page—displays results for a particular poll.
    • Vote action—handles voting for a particular choice in a particular poll.
    The first step of writing views is to design your URL structure. You do this by creating a Python module called a URLconf. URLconfs are how Django associates a given URL with given Python code.
    Let’s start by adding our URL configuration directly to the urls.py that already exists in your project at <my_geonode>/urls.py. Edit this file and add the following lines after the rest of the existing imports around line 80:
    url(r'^polls/$', 'polls.views.index'),
    url(r'^polls/(?P<poll_id>\d+)/$', 'polls.views.detail'),
    url(r'^polls/(?P<poll_id>\d+)/results/$', 'polls.views.results'),
    url(r'^polls/(?P<poll_id>\d+)/vote/$', 'polls.views.vote'),
    
    Note
    Eventually we will want to move this set of URL configurations inside the URLs app itself, but for the sake of brevity in this workshop, we will put them in the main urls.py for now. You can consult the Django tutorial for more information on this topic.
    Next write the views to drive the URL patterns we configured above. Edit polls/views.py to that it looks like the following:
    from django.template import RequestContext, loader
    from polls.models import Poll
    from django.http import HttpResponse
    from django.http import Http404
    from django.shortcuts import render_to_response
    
    def index(request):
        latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
        return render_to_response('polls/index.html',
            RequestContext(request, {'latest_poll_list': latest_poll_list}))
    
    def detail(request, poll_id):
        try:
            p = Poll.objects.get(pk=poll_id)
        except Poll.DoesNotExist:
            raise Http404
        return render_to_response('polls/detail.html', RequestContext(request, {'poll': p}))
    
    def results(request, poll_id):
        return HttpResponse("You're looking at the results of poll %s." % poll_id)
    
    def vote(request, poll_id):
        return HttpResponse("You're voting on poll %s." % poll_id)
    
    Note
    We have only stubbed in the views for the results and vote pages. They are not very useful as-is. We will revisit these later.
    Now we have views in place, but we are referencing templates that do not yet exist. Let’s add them by first creating a template directory in your polls app at polls/templates/polls and creating polls/templates/polls/index.html to look like the following:
    {% if latest_poll_list %}
        <ul>
        {% for poll in latest_poll_list %}
            <li><a href="/polls/{{ poll.id }}/">{{ poll.question }}</a></li>
        {% endfor %}
        </ul>
    {% else %}
        <p>No polls are available.</p>
    {% endif %}
    
    Next we need to create the template for the poll detail page. Create a new file at polls/templates/polls/detail.html to look like the following:
    <h1>{{ poll.question }}</h1>
    <ul>
    {% for choice in poll.choice_set.all %}
        <li>{{ choice.choice }}</li>
    {% endfor %}
    </ul>
    
    You can now visit http://localhost:8000/polls/ in your browser and you should see the the poll question you created in the admin presented like this.
    ../../../_images/polls_plain.png
  7. Update templates
    We actually want our polls app to display as part of our GeoNode project with the same theme, so let’s update the two templates we created above to make them extend from the site_base.html template we looked at in the last section. You will need to add the following two lines to the top of each file:
    {% extends 'site_base.html' %}
    {% block body %}
    
    And close the block at the bottom of each file with:
    {% endblock %}
    
    This tells Django to extend from the site_base.html template so your polls app has the same style as the rest of your GeoNode, and it specifies that the content in these templates should be rendered to the body block defined in GeoNode’s base.html template that your site_base.html extends from.
    You can now visit the index page of your polls app and see that it is now wrapped in the same style as the rest of your GeoNode site.
    ../../../_images/polls_geonode.png
    If you click on a question from the list you will be taken to the poll detail page.
    ../../../_images/poll_geonode_hidden.png
    It looks like it is empty, but in fact the text is there, but styled to be white by the Bootswatch theme we added in the last section. If you highlight the area where the text is, you will see that it is there.
    ../../../_images/poll_geonode_highlight.png
Now that you have walked through the basic steps to create a very minimal (though not very useful) Django app and integrated it with your GeoNode project, you should pick up the Django tutorial at part 4 and follow it to add the form for actually accepting responses to your poll questions.
We strongly recommend that you spend as much time as you need with the Django tutorial itself until you feel comfortable with all of the concepts. They are the essential building blocks you will need to extend your GeoNode project by adding your own apps.

Adding a 3rd party blog app

Now that we have created our own app and added it to our GeoNode project, the next thing we will work through is adding a 3rd party blog app. There are a number of blog apps that you can use, but for purposes of this workshop, we will use a relatively simple, yet extensible app called Zinnia. You can find out more information about Zinnia on its website or on its GitHub project page or by following its documentation. This section will walk you through the minimal set of steps necessary to add Zinnia to your GeoNode project.
  1. Install Zinnia
    The first thing to do is to install Zinnia into the virtualenv that you are working in. Make sure your virtualenv is activated and execute the following command:
    $ pip install django-blog-zinnia
    
    This will install Zinnia and all of the libraries that it depends on.
  2. Add Zinnia to INSTALLED_APPS
    Next add Zinnia to the INSTALLED_APPS section of your GeoNode projects settings.py file by editing <my_geonode>/settings.py and adding ‘django.contrib.comments’ to the section labeled “Apps Bundled with Django” so that it looks like the following:
    # Apps bundled with Django
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.admin',
    'django.contrib.sitemaps',
    'django.contrib.staticfiles',
    'django.contrib.messages',
    'django.contrib.humanize',
    'django.contrib.comments',
    
    And then add the tagging, mptt and zinnia apps to the end of the INSTALLED_APPS where we previously added a section labeled “My GeoNode apps”. It should like like the following:
    # My GeoNode apps
    'polls',
    'tagging',
    'mptt',
    'zinnia',
    
  3. Synchronize models
    Next you will need to run syncdb again to synchronize the models for the apps we have just added to our project’s database. This time we want to pass the --all flag to syncdb so it ignores the schema migrations. Schema migrations are discussed further in GeoNode’s documentation, but it is safe to ignore them here.
    $ python manage.py syncdb --all
    
    You can now restart the development server and visit the Admin interface and scroll to the very bottom of the list to find a section for Zinnia that allows you to manage database records for Categories and Blog Entries.
    ../../../_images/zinnia_admin.png
  4. Configure project
    Next we need to configure our project to add Zinnia’s URL configurations. Add the following two URL configuration entries to the end of <my_geonode>/urls.py:
    url(r'^blog/', include('zinnia.urls')),
    url(r'^djcomments/', include('django.contrib.comments.urls')),
    
    If you visit the main blog page in your browser at http://localhost:8000/blog/ you will find that the blog displays with Zinnia’s default theme as shown below.
    Note
    If you are not able to visit the main blog page, you will have to set USE_TZ = True in settings.py. Restart the server and try again!
    ../../../_images/zinnia_default.png
    This page includes some guidance for us on how to change the default theme.
  5. Change default theme
    The first thing we need to do is to copy Zinnia’s base.html template into our own project so we can modify it. When you installed Zinnia, templates were installed to /var/lib/geonode/lib/python2.7/site-packages/zinnia/templates/zinnia/. You can copy the base template by executing the following commands:
    $ mkdir <my_geonode>/templates/zinnia
    $ cp /var/lib/geonode/lib/python2.7/site-packages/zinnia/templates/zinnia/base.html <my_geonode>/templates/zinnia/
    
    Then you need to edit this file and change the topmost line to read as below such that this template extends from our projects site_base.html rather than the zinnia skeleton.html:
    {% extends "site_base.html" %}
    
    Since Zinnia uses a different block naming scheme than GeoNode does, you need to add the following line to the bottom of your site_base.html file so that the content block gets rendered properly:
    {% block body %}{% block content %}{% endblock %}{% endblock %}
    
    ../../../_images/zinnia_geonode.png
    You can see that there are currently no blog entries, so let’s add one. Scroll to the bottom of the interface and click the Post an Entry link to go to the form in the Admin interface that lets you create a blog post. Go ahead and fill out the form with some information for testing purposes. Make sure that you change the Status dropdown to “published” so the post shows up right away.
    ../../../_images/zinnia_create_post.png
    You can explore all of the options available to you as you create your post, and when you are done, click the Save button. You will be taken to the page that shows the list of all your blog posts.
    ../../../_images/zinnia_post_list.png
    You can then visit your blog post/entry at http://localhost:8000/blog/.
    ../../../_images/zinnia_blog.png
    And if you click on the blog post title, you will be taken to the page for the complete blog post. You and your users can leave comments on this post and various other blog features from this page.
    ../../../_images/zinnia_post.png
  6. Integrate app into your site
    The last thing we need to do to fully integrate this blog app (and our polls app) into our site is to add it to the options on the navbar. To do so, we need to add the following block override to our Projects site_base.html:
    {% block extra-nav %}
    <li id="nav_polls">
        <a href="/polls/">Polls</a>
    </li>
    <li id="nav_blog">
        <a href="{% url 'zinnia_entry_archive_index' %}">Blog</a>
    </li>
    {% endblock %}
    
    ../../../_images/navbar_add.png
At this point, you could explore options for tighter integration between your GeoNode project and Zinnia. Integrating blog posts from Zinnia into your overall search could be useful, as well as including the blog posts a user has written on their Profile Page. You could also explore the additional plugins that go with Zinnia.

Adding other apps

No comments:

Post a Comment