18851

Python/Django TangoWithDjango Models and Databases

I'm currently following http://www.tangowithdjango.com and I'm trying to populate an existing DB with populate_rango.py. When I create the new categories, I'm trying to get the views and likes to be populated with the following:

Python: 128, 64 Django: 64, 32 Other Frameworks: 32, 16

In my admin panel, it keeps showing 0's for both views and likes for all three categories.

Can someone show me what I'm doing incorrectly with the code below?

models.py

from django.db import models class Category(models.Model): name = models.CharField(max_length=128, unique=True) views = models.IntegerField(default=0) likes = models.IntegerField(default=0) def __unicode__(self): return self.name class Page(models.Model): category = models.ForeignKey(Category) title = models.CharField(max_length=128) url = models.URLField() views = models.IntegerField(default=0) def __unicode__(self): return self.title

populate_rango.py

import os import sys def populate(): python_cat = add_cat('Python', 128, 64) add_page(cat=python_cat, title="Official Python Tutorial", url="http://docs.python.org/2/tutorial/") add_page(cat=python_cat, title="How to Think like a Computer Scientist", url="http://www.greenteapress.com/thinkpython/") add_page(cat=python_cat, title="Learn Python in 10 Minutes", url="http://www.korokithakis.net/tutorials/python/") django_cat = add_cat("Django", 64, 32) add_page(cat=django_cat, title="Official Django Tutorial", url="https://docs.djangoproject.com/en/1.5/intro/tutorial01/") add_page(cat=django_cat, title="Django Rocks", url="http://www.djangorocks.com/") add_page(cat=django_cat, title="How to Tango with Django", url="http://www.tangowithdjango.com/") frame_cat = add_cat("Other Frameworks", 32, 16) add_page(cat=frame_cat, title="Bottle", url="http://bottlepy.org/docs/dev/") add_page(cat=frame_cat, title="Flask", url="http://flask.pocoo.org") # Print out what we have added to the user. for c in Category.objects.all(): for p in Page.objects.filter(category=c): print "- {0} - {1}".format(str(c), str(p)) def add_page(cat, title, url, views=0): p = Page.objects.get_or_create(category=cat, title=title, url=url, views=views)[0] return p def add_cat(name, views, likes): c = Category.objects.get_or_create(name=name, views=views, likes=likes)[0] return c # Start execution here! if __name__ == '__main__': print "Starting Rango population script..." os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tango_with_django_project.settings') from rango.models import Category, Page populate()

settings.py

""" Django settings for tango_with_django_project project. For more information on this file, see https://docs.djangoproject.com/en/dev/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/dev/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) PROJECT_PATH = os.getcwd() # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '@&v@6mq6b-4(97c8s^4g((t-&%k&@hi08u$x0w+(mnhre08m!=' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rango', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'tango_with_django_project.urls' WSGI_APPLICATION = 'tango_with_django_project.wsgi.application' # Database # https://docs.djangoproject.com/en/dev/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/dev/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/dev/howto/static-files/ STATIC_PATH = os.path.join(PROJECT_PATH,'static') STATIC_URL = '/static/' # You may find this is already defined as such. STATICFILES_DIRS = ( STATIC_PATH, ) TEMPLATE_PATH = os.path.join(PROJECT_PATH, 'templates') 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. TEMPLATE_PATH, ) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(PROJECT_PATH, 'media')

Answer1:

I didn't know we needed to complete the exercises of CH5 when doing CH6, luckily I came across your question and this helped me get the desired output I wanted from the index.html.

I haven't done any work with the admin side of things though, but it looks like your error is here:

<strong>populate_rango.py</strong>

frame_cat = add_cat("Other Frameworks", 32, 16)

and

def add_cat(name, views, likes): c = Category.objects.get_or_create(name=name, views=views, likes=likes)[0] return c

You need to make the views=0 & likes=0 in this line: def add_cat(name, views, likes):

Then you need to change this:

frame_cat = add_cat("Other Frameworks", 32, 16) to this:

frame_cat = add_cat("Other Frameworks", views=32, likes=16)

Also, you will have a database called DATABASE_PATH (or at least that is what mine is called). You need to <strong>delete</strong> this and run:

python manage.py syncdb

& then just to make sure it worked, I ran:

python populate_rango.py

When you got the error in the admin section, did you first check the /rango page to see if you were getting the correct output? Chances are, you were also either getting an error like me or your categories weren't displaying (I could be wrong though on your output).

I think my solution will display the views and likes now. Try it and let me know.

Answer2:

The following worked for me, when added to populate_rango.py -

def add_cat(name, views, likes): c = Category.objects.get_or_create(name=name)[0] c.views = views c.likes = likes c.save() return c

The difference might be due to c.save()

Answer3:

The following worked for me. I have no idea whether it will cause issues in later chapters, but it allowed the populate_rango.py script to run.

Changes to <strong>populate_rango.py</strong>

def populate(): python_cat = add_cat("Python", views=128, likes=64) django_cat = add_cat("Django", views=64, likes=32) frame_cat = add_cat("Other Frameworks", views=32, likes=16)

and

def add_cat(name, views=0, likes=0): c = Category.objects.get_or_create(name=name, views=views, likes=likes)[0] return c

That resulted in a database IntegrityError so I edited the View fields in my Category and Page classes to ensure they aren't unique:

Changes to <strong>models.py</strong>

class Category(models.Model): views = models.IntegerField(default=0, unique=False) class Page(models.Model): views = models.IntegerField(default=0, unique=False)

Finally, I deleted the database and ran

python manage.py syncdb

and

python populate_rango.py

Recommend

  • Django logging in as anonymous user?
  • How can I extract City, Region, Country from a URL? Django
  • How do I use the Entry API with an expensive key that is only constructed if the Entry is Vacant?
  • How to set initial value in a dynamic Django ModelChoiceField?
  • Refactoring advice: maps to POJOs
  • JavaScriptCore External Arrays
  • Single django queryset to get n adjacent items
  • C function strchr - How to calculate the position of the character?
  • Double dispatch in Java example
  • conditions for accessors in Coldfusion ORM
  • Django return user model id with L
  • In Java, how can I construct a File from a resource?
  • Do query loads all the data in memory
  • Adding elements to a huge XML file
  • Parse a date string in a specific locale (not timezone!)
  • Date Conversion from yyyy-mm-dd to dd-mm-yyyy
  • Debug.DrawLine not showing in the GameView
  • How to define and use opencv mat of user type
  • dc-js disable selecting slices on click for pie chart
  • Can I check if a recipient has an automatic reply before I send an email?
  • CSS Linear-gradient formatting issue accross different browsers
  • Spring security and special characters
  • Fill an image in a square container while keeping aspect ratio
  • Cassandra Data Model
  • How to handle AllServersUnavailable Exception
  • Font Awesome Showing Box instead of Icons
  • Properly structure and highlight a GtkPopoverMenu using PyGObject
  • align graphs with different xlab
  • Return words with double consecutive letters
  • 0x202A in filename: Why?
  • retrieve vertices with no linked edge in arangodb
  • Getting Messege Twice Using IMvxMessenger
  • Turn off referential integrity in Derby? is it possible?
  • Linking SubReports Without LinkChild/LinkMaster
  • Authorize attributes not working in MVC 4
  • Is it possible to post an object from jquery to bottle.py?
  • Busy indicator not showing up in wpf window [duplicate]
  • Reading document lines to the user (python)
  • Python/Django TangoWithDjango Models and Databases
  • Net Present Value in Excel for Grouped Recurring CF