Django & Python Adventure Part 2

Hello again.  Today we’ll continue from Part 1 and create an initial Template and some database Models.  Django is MVC, it just calls it MTV.  So, Model-View-Control = Model-Template-View.  I think the View part is what’s most confusing, but, that’s how it is.

Well, on with it then.  First we’ll be creating the main page view:
Open a command prompt and get to your bookmarks project again (remember you still should have another command prompt running the built in Django web server).
Type: python manage.py startapp bookmarks
Look familiar? It should.

Now you will have a folder in your application called bookmarks that contains:
your new bookmarks folder

Open the views.py in PyCharm (or whatever you’re using) and drop this code into it:

# Create your views here.
from django.http import HttpResponse
def main_page(request):
    output=u'''
        <html>
            <head><title>%s</title></head>
            <body>
                <h1>%s</h1><p>%s</p>
            </body>
        </html>
    ''' % (
        u'Django Bookmarks',
        u'Welcome to Django Bookmarks',
        u'Where you can store and share bookmarks! Seriously.'
    )
    return HttpResponse(output)

Important! Python cares a lot about indentation. If your indentation is wrong, your code won’t work.
Now open urls.py
Add an import line for your bookmarks
Add a url pattern to your main page.
r’’ means it’s a raw string. The ^$ is a regular expression which means “empty string”. In English I’m saying we just told the website what to do when the website address is just the base URL with nothing else appended.

from django.conf.urls.defaults import patterns, include, url
from bookmarks.views import *
urlpatterns = patterns('',
     (r'^$', main_page),
)

Go back and start your server and browse to your page.
Your temporary template
Hooray.

Designing an initial database (or Model) For this bookmarks website we’ll need three tables: Users, Links and a cross reference table Bookmarks Open the bookmarks/models.py page Add this:

from django.db import models
# Create your models here.
class Link(models.Model):
   url = models.URLField(unique=True)

Now open the settings.py and locate the INSTALLED_APPS section and add:

 'django_bookmarks.bookmarks',

Then pop into a command window and execute:

python manage.py syncdb

You can then validate the SQL genereated with:

python manage.py sql bookmarks

You should see this:

CREATE TABLE “bookmarks_link” (
“id” integer NOT NULL PRIMARY KEY,
“url” varchar(200) NOT NULL UNIQUE
)
;
COMMIT;

Cool? Yes, it is.
Now execute:

pyhton manage.py shell
from bookmarks.models import *
link1 = Link(url=u’http://michaeldukehall.com’)
link1.save()
link2 = Link(url=u’http://hak5.org)
link2.save()

Now you have some data in your Link table/model and you can view it with:

link2.url

or

links = Link.objects.all()

for link in links:

print link.url

or

Link.objects.get(id=1)

and

Link2.delete()

and

Link.objects.count()

Okay, well, that was a lot of fun. SQLLite via Python shell. No SQL necessary because of the Object Relationship Manager in Django. If you switch to another db, the ORM does the heavy lifting for you. So, in .Net you have to know C# and SQL. In Python you have to know Python. Win.

The User model is already created, so, we move onto the Bookmarks model.
Go back to models.py and drop this in:

from django.db import models
from django.contrib.auth.models import User
# Create your models here.
    class Link(models.Model):
    url = models.URLField(unique=True)
class Bookmark(models.Model):
    title=models.CharField(max_length=200)
    user=models.ForeignKey(User)
    link=models.ForeignKey(Link)

That imports the built in User table/model and builds the Bookmark table with foreign keys in Link and User.

Fun stuff!

In part 3 we’ll do the template properly.

This entry was posted in Uncategorized and tagged , . Bookmark the permalink.

5 Responses to Django & Python Adventure Part 2

  1. SUPER DAVE says:

    When I type in “python manage.py sql bookmarks” from a command prompt, I am not getting the SQL Table results, it just pauses for a moment then returns me to my command prompt. Any ideas as to why this is not working?

    python manage.py sql bookmarks

    You should see this:

    CREATE TABLE “bookmarks_link” (
    “id” integer NOT NULL PRIMARY KEY,
    “url” varchar(200) NOT NULL UNIQUE
    )
    ;
    COMMIT;

    Cool? Yes, it is.

    • mdukehall says:

      SuperDave, can you give me a few more details leading up to the command line call not working?
      I am sort of assuming you already got through the first post without any trouble: http://mdukehall.wordpress.com/2011/12/05/django-python-adventure-part-1/
      Is that the case?

      • SUPER DAVE says:

        I finally got it working… I had several “notepad” files open from the book and had not saved it apparantly. I still think this book is very difficult for a beginner learing DJANGO, he says now modify this or that file, but he fails to show us a “completed picture” of what the file should look like after the modification. I never know if I am suppoosed to delete current code and replace completely, or just add the “modified” code. again… if that is the case, a beginner sometimes does not know where the modifed code would go. Anyway I will keep pulling my hair out and try to get through the book. I also have his second edition on the book and it looks better…

Leave a Reply

Your email address will not be published. Required fields are marked *