Django: Intro

I found some of the documentation for Django very confusing to me, the beginner.  The steps in retrospect are very straightforward.  In fact, a version of the Lynda.com tutorial is missing the instructions on establishing a virtualenv, so I had to embark on a voyage of discovery

pip install virtualenv

 

to make sure it’s installed or install if it isn’t.

The basic command

virtualenv venv

where venv is the name of your virtual environment.

Then either CD into the venv folder\Scripts or add the path and issue:

activate

Your prompt will now change from a standard command prompt to:

(venv) C:\Python36\web\venv\Scripts>

Indicating that  your virtualenv “(venv)” is active.

Super-handy batch file to activate your venv and leave the prompt open to do work.

@echo off
cmd /k "cd /d C:\python36\venv\Scripts & activate & cd /d C:\python36\"

I dropped this nugget on the desktop with name venv.bat

The django documentation tutorial gets a little confusing now because of the doubled mysite/mysite site structure.

Migrations:

 

Pitfall:  If your code editor is not correctly configured for python and using the tab character instead of the python standard (4 spaces), your django files will throw this error.  Took a little while and a bit of frustration to figure that one out.  I’m using notepad++ and had to override the tab settings to put in 4 spaces.  

return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
^
TabError: inconsistent use of tabs and spaces in indentation

To manipulate the DB through the API/Shell

python manage.py shell

QueryStrings

Question.objects.get(pub_date__year=current_year)
Question.objects.filter(question_text__startswith='What')
Question.objects.filter(id=1)

PrimaryKey lookup is the most common QueryString (pk=x)

Question.objects.get(pk=1)

Create choices for the question QuerySet

q = Question.objects.get(pk=1)
q.choice_set.create(choice_text='Not much', votes=0)

More QuerySet Mojo

Question.objects.get(pk=1).choice_set.all()
<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>,
<Choice: Just hacking again>]>
c = q.choice_set.create(choice_text='Just hacking again', votes=0)
c.delete()            #Drops it from the DB

More QuerySet Mojo

c = q.choice_set.create(choice_text='Just hacking again', votes=0)
c.delete()

More QuerySet Mojo

c = q.choice_set.create(choice_text='Just hacking again', votes=0)
c.delete()

 

 

 

 

End

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

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