This section will continue from our Davinci Django project.
First we'll update our existing models to include additional fields.
Open hello_world/models.py
and add 2 fields to StuffToRate
ex:
color = models.CharField(max_length=100, default='Green')
description = models.TextField()
Since we'd like to know what we're working with we'll update the __unicode__
property of the models as well. By updating this property we'll now see the string that we return rather than StuffToRate Object
when viewing instances of the object.
ie:
def __unicode__(self):
return 'StuffToRate - {} - {}'.format(self.title, self.color)
and
def __unicode__(self):
return 'Rating -- {} -- {} -- {}'.format(self.stuff.title, self.rating,
self.stuff.color)
We can then pull copies of StuffToRate
and get the current rating with the following code in the ipython
console:
python manage.py shell
from hello_world.models import Rating, StuffToRate
objs = StuffToRate.objects.all()
# assumes there are entries already saved
obj = objs[0]
# get the rating of the current StuffToRate instance
obj.get_rating()
if it throws an error about division by zero, then you're probably working with a StuffToRate
instance that does not yet have a Rating
associated with it.
You probably want to add one, but we should also catch that error.
So back in hello_world/models.py
update StuffToRate.get_rating
with
if not self.rating_set.count():
return 'No ratings for {}'.format(self.title)
at the beginning of the function
Now that we're comfortable tinkering with the models in the console, we can plug them into the admin. One of the points of magic in Django.
in hello_world/admin.py
add
from hello_world.models import Rating, StuffToRate
and
admin.site.register(Rating)
admin.site.register(StuffToRate)
then go back into your terminal and start the django development server for this project
python manage.py runserver
then visit
in your browser, and click on the new "StuffToRate" link displayed, from there you can add / edit entries and/or Rating's to work with
once you're feeling comfortable with that section we can go back to our "Views"
In hello_world/views.py
add
from hello_world.models import Rating, StuffToRate
at the top of the file and then replace the contents of def index
with
display = ''
objs = StuffToRate.objects.all()
obj = objs[0]
display += '{} - {} - {}'.format(obj.title, obj.color, obj.get_rating())
return HttpResponse(display)
then visit http://localhost:8000/hello_world/ in you're browser and see the new entry displayed
From there play around, if you're not feeling comfortable with all the steps until now review them, then start a new virtualenv and project and rebuild until this point.
Once you're comfortable please review the HTML videos shared in Slack as preparation for Tuesday's class.