Hi I am doing the djangogirls tutorial and have come across the OperationalError no such table: blog_post. This works perfect on my virtual environment, but I get the OperationalError after pushing to heroku.
I am using Django 1.7.7. More information on the error is available at: https://girlsblog.herokuapp.com/
I have done
python manage.py makemigrations
python manage.py migrate
initially in the beginning of the tutorial. Then I attempted to do it again and there are "No changes detected" and "No migrations to make"
This is my post_list.html
{% extends 'blog/base.html' %}
{% block content %}
{% for post in posts %}
<div class="post">
<div class="date">
{{ post.published.date }}
</div>
<h1>{{ post.title }}</h1>
<p> {{ post.text|linebreaks }}</p>
</div>
{% endfor %}
{% endblock content %}
This is my .gitignore
myvenv
__pycache__
staticfiles
local_settings.py
db.sqlite3
Models.py
from django.db import models
from django.utils import timezone
# Create your models here.
class Post(models.Model):
author = models.ForeignKey('auth.User')
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(
default=timezone.now)
published_date = models.DateTimeField(
blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
Settings.py
"""
Django settings for mysite project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/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__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '1l8)#&q8r_wwev1r9mm8q5ezz8p#)rvg(l4%(t^-t8s4bva2+r'
# 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',
'blog',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'mysite.urls'
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/Chicago'
USE_I18N = True
USE_L10N = True
USE_TZ = False
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/'
import dj_database_url
DATABASES['default'] = dj_database_url.config()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
ALLOWED_HOSTS = ['*']
STATIC_ROOT = 'staticfiles'
DEBUG = False
try:
from .local_settings import *
except ImportError:
pass
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
blog/views.py
from django.shortcuts import render, get_object_or_404
from django.utils import timezone
from .models import Post
from .forms import PostForm
# Create your views here.
def post_list(request):
posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
return render(request, 'blog/post_list.html', {'posts': posts})
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'blog/post_detail.html', {'post': post})
def post_new(request):
form = PostForm()
return render(request, 'blog/post_edit.html', {'form': form})
I am really new to this, so please forgive "simple" mistakes.
Old post, but does not appeared to be answered so I'll take a shot. I was led here via google after having a similar problem.
This issue is probably a missing database on the heroku side. If you are pushing via git, and db.sqlite3 is in your .gitignore, it will definitely be missing there, and will need to be created there. This was exactly my issue when fiddling with a pre-made example (where the db had not yet been created).
$ python manage.py migrate
on your heroku environment should fix it.
This is because on Heroku you've very likely got the postgresql backend installed, not sqlite. You need to configure your production deployment to correctly use postgresql... I'd give instructions on that but I have to figure it out now...
I encountered the same issue and found a solution on reddit. Use
git add -f db.sqlite3
Then commit, push, and finally pull on pythonanywhere.com.
Credits to reddit users elbuckez & jeans_and_a_t-shirt
I did two things to resolve this:
Typed python3 manage.py migrate in server console, as David Nugent above said.
In .gitignore file, I had to comment out db.sqlite3. I then committed and pushed this change, then went back into my server (in my case pythonanywhere, not heroku) and did git pull.
Run this command python manage.py migrate --run-syncdb after these commands
python manage.py migrate
python manage.py makemigrations
Include this statement in your models.py:
from django.contrib.auth.models import User
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'm quite new in django 1.8.
Now, I'm trying to get current logined username.
I wanna do this. When I post some articles it's author automatically saved to database and displayed in template table.
I already know about
from django.contrib.auth.models import User
and request.user.get_username()
and read lots of articles and QNA about this subject and various tries in two days. But I never find why I only can get username in template but not in view.
I did belows
python manage.py makemigrations BTS(This is name of app)
python manage.py migrate
It works well.
In template, Belows all works well:
{{ user.username }}
{{ request.user.username }}
{{ request.user }}
In views.py I use get_username method like this. No error but it's not work.:
form.username = request.user.get_username()
Every other things works fine. But only above one line get anything only empty null value about username, I guess. I need help.
Here is my code. I skip some unnecessary def.
views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.utils import timezone
from django.template import RequestContext, loader
from django.shortcuts import redirect
from .models import BTSinput
from .models import BTSreply
from .forms import BTSinputForm
from .forms import BTSreplyForm
from django.contrib.auth.models import User
def inputvalidate(request):
if request.method == 'POST':
form = BTSinputForm(request.POST or None)
if form.is_valid():
hold = form.save(commit=False)
form.created = timezone.now()
form.updated = timezone.now()
form.username = request.user.get_username()
hold.save()
return redirect('/BTS/list/')
else:
form = BTSinputForm()
return render(request,'BTS/input.html',{'inputform':form})
return render(request,'BTS/input.html',{'inputform':form})
input.html
{% block content %}
{% load widget_tweaks %}
<div class="container">
<div class="starter-template">
<form method="post" action="/BTS/inputvalidate/">
{% csrf_token %}
<div class="form-group">
<p>subject</p>
<p>{{inputform.subject|add_class:"form-control"}}</p>
<p>URLS</p>
<p>{{inputform.urls|add_class:"form-control"}}</p>
<p>text</p>
<p>{{inputform.text|add_class:"form-control"}}</p>
<button type="submit" class="btn btn-default">Confirm</button>
<button type="button" class="btn btn-default">To List</button>
</div>
</form>
</div>
</div>
{% endblock%}
models.py
class BTSinput(models.Model):
subject = models.CharField(max_length=100)
username = models.CharField(max_length=30, blank = True)
text = models.TextField()
urls = models.URLField(max_length = 100)
created = models.DateTimeField(default = datetime.datetime.now)
updated = models.DateTimeField(default = datetime.datetime.now)
forms.py
from django import forms
from django.forms import ModelForm
from BTS.models import BTSinput
from BTS.models import BTSreply
# Create your models here.
class BTSinputForm(ModelForm):
class Meta:
model = BTSinput
fields = ['subject','text','urls']
class BTSreplyForm(ModelForm):
class Meta:
model = BTSreply
fields = ['reply']
I checked my setting.py over and over. But... ^^;;;
Here is my setting.py
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 1.8.4.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'n^63(%(va-3wb9l!!2-vg003f)s(3g=%w1*%tv2(8%l)65g&a2'
# SECURITY WARNING: don't run with debug turned on in production!
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',
'QNA',
'BTS',
'accounts',
'widget_tweaks',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'ko-kr'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
Once you have called save with commit=False, you should update the instance, not the form.
if form.is_valid():
hold = form.save(commit=False)
hold.created = timezone.now()
hold.updated = timezone.now()
hold.username = request.user.get_username() # or request.user.username
hold.save()
Hi Guys I have a blog setup and I want to add the ability for an image or thumbnail to be included in every blog post. I'm having trouble getting the location of the file and the blog template to match up and show the image. I'm also having difficulties integrating the ImageWithThumbnail model to the Entry model.
post.html
{% include 'head.html' %}
{% include 'navbar.html' %}
{% load staticfiles %}
{% load django_markdown %}
<div class="container">
<div class="post">
<h2>{{ object.title }}</h2>
<p class="meta">
{{ object.created }} |
Tagged under {{ object.tags.all|join:", " }} <p> Created by
{{ object.author }} </p>
</p>
{{ object.body|markdown }}
<img src="{% static "{{ STATIC_ROOT }}/media/tableau_public.jpg" %}" alt="My image"/>
{{ object.file }}
</div>
{% include 'footer.html' %}
Settings.py
"""
Django settings for vizualytic project.
Generated by 'django-admin startproject' using Django 1.8.3.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '#ic_*)dw$fxp+p_c=3e=91ujzivxurqf7y7572z9&sfs19aek%'
# SECURITY WARNING: don't run with debug turned on in production!
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',
'django_markdown',
'website',
'blog',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'vizualytic.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(os.path.dirname(BASE_DIR), "static", "templates")],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'vizualytic.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/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/1.8/howto/static-files/
STATIC_URL = '/static/'
if DEBUG:
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "static-only")
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "media")
STATICFILES_DIRS = (
os.path.join(os.path.dirname(BASE_DIR), "static", "static"),
)
view.py
from django.views import generic
from . import models
class BlogIndex(generic.ListView):
queryset = models.Entry.objects.published()
template_name = "blog.html"
paginate_by = 3
class BlogDetail(generic.DetailView):
model = models.Entry
template_name = "post.html"
models.py
from django.db import models
from django.core.urlresolvers import reverse
from django.conf import settings
class Tag(models.Model):
slug = models.SlugField(max_length=200, unique=True)
def __str__(self):
return self.slug
class EntryQuerySet(models.QuerySet):
def published(self):
return self.filter(publish=True)
class Entry(models.Model):
title = models.CharField(max_length=200)
name = models.CharField(max_length = 255)
file = models.ImageField()
thumbnail = models.ImageField(upload_to=settings.MEDIA_ROOT+"/%Y/%m/%d",max_length=500,blank=True,null=True)
author = models.CharField(max_length=200, null=True)
body = models.TextField()
slug = models.SlugField(max_length=200, unique=True)
publish = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
tags = models.ManyToManyField(Tag)
objects = EntryQuerySet.as_manager()
def filename(self):
return os.path.basename(self.file.name)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("entry_detail", kwargs={"slug": self.slug})
class Meta:
verbose_name = "Blog Entry"
verbose_name_plural = "Blog Entries"
ordering = ["-created"]
class ImageWithThumbnail(models.Model):
name = models.CharField(max_length = 255)
image = models.ImageField(upload_to="/%Y/%m/%d",max_length=500,blank=True,null=True)
thumbnail = models.ImageField(upload_to="/%Y/%m/%d",max_length=500,blank=True,null=True)
def create_thumbnail(self):
# original code for this method came from
# http://snipt.net/danfreak/generate-thumbnails-in-django-with-pil/
# If there is no image associated with this.
# do not create thumbnail
if not self.image:
return
from PIL import Image
from cStringIO import StringIO
from django.core.files.uploadedfile import SimpleUploadedFile
import os
# Set our max thumbnail size in a tuple (max width, max height)
THUMBNAIL_SIZE = (200,200)
DJANGO_TYPE = self.image.file.content_type
if DJANGO_TYPE == 'image/jpeg':
PIL_TYPE = 'jpeg'
FILE_EXTENSION = 'jpg'
elif DJANGO_TYPE == 'image/png':
PIL_TYPE = 'png'
FILE_EXTENSION = 'png'
# Open original photo which we want to thumbnail using PIL's Image
image = Image.open(StringIO(self.image.read()))
# Convert to RGB if necessary
# Thanks to Limodou on DjangoSnippets.org
# http://www.djangosnippets.org/snippets/20/
#
# I commented this part since it messes up my png files
#
#if image.mode not in ('L', 'RGB'):
# image = image.convert('RGB')
# We use our PIL Image object to create the thumbnail, which already
# has a thumbnail() convenience method that contrains proportions.
# Additionally, we use Image.ANTIALIAS to make the image look better.
# Without antialiasing the image pattern artifacts may result.
image.thumbnail(THUMBNAIL_SIZE, Image.ANTIALIAS)
# Save the thumbnail
temp_handle = StringIO()
image.save(temp_handle, PIL_TYPE)
temp_handle.seek(0)
# Save image to a SimpleUploadedFile which can be saved into
# ImageField
suf = SimpleUploadedFile(os.path.split(self.image.name)[-1],
temp_handle.read(), content_type=DJANGO_TYPE)
# Save SimpleUploadedFile into image field
self.thumbnail.save('%s_thumbnail.%s'%(os.path.splitext(suf.name)[0],FILE_EXTENSION), suf, save=False)
def save(self):
# create a thumbnail
self.create_thumbnail()
super(ImageWithThumbnail, self).save()
Any help would be greatly appreciated.
Thanks
you just need:
<img src="{{ object.thumbnail.url }}" alt="My image"/>
note that the {% static 'file.extension' %} is used only to render static files.
I would suggest to use Django Filer with Easy Thumbnails.
You will only need one image field in your model and leave making the thumbnail to Easy Thumbnails on rendering of the template.
I'm working on a very basic Django app in hopes of teaching myself the framework, and I've hit a small snag. The app is intended to take user input, store it in a mysqlite database, and display the contents of the database on receiving a request. I have everything working properly when the app is run locally (manage.py runserver), however it's misbehaving once it's deployed. For some reason, the storage logic is malfunctioning on the live site (Windows Server 2012 via MS Azure).
Here is the code in question:
from django.http import HttpResponse
from django.shortcuts import render
from django.shortcuts import render_to_response
from helloworld.models import Registry
def home(request):
return render_to_response("home.html")
def register(request):
return render_to_response("register.html")
def view(request):
entries = Registry.objects.all()
args = {}
args["entries"] = entries
return render_to_response("registry.html", args)
def submit(request):
nameIn = request.GET.get('name')
ageIn = request.GET.get('age')
monthIn = request.GET.get('month')
try:
Registry(name=nameIn, age=ageIn, month=monthIn).save()
except:
pass
return view(request)
I've done a fair amount of debugging, and tried several approaches to storing the data. I've checked that the method is receiving valid values. I can't, for the life of me, figure out why that call to save() is throwing an error. Hopefully it will be obvious to one of you Django-pros! THanks in advance, any help will be greatly appreciated! P.s. I'm attaching my settings file, as i have a sneaking suspicion that poor configuration is the source of my troubles.
"""
Django settings for cny_solar project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/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__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 's7xv#m=5h=mjrdg_7-$=7kr8kx4np9$#6qzlg+m4xt&6-#-zi2'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS=['127.0.0.1','localhost']
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'helloworld',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'helloworld.urls'
WSGI_APPLICATION = 'helloworld.wsgi.application'
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
)
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.7/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/1.7/howto/static-files/
STATIC_ROOT = BASE_DIR
STATIC_URL = '/static/'
STATICFILES_DIRS = (
('assets', os.path.join(BASE_DIR, 'static')),
)
When I run python populate_rango.py it gives this
Starting Rango population script...
- Python - Page object
- Python - Page object
- Python - Page object
- Django - Page object
- Django - Page object
- Django - Page object
- Other Frameworks - Page object
- Other Frameworks - Page object
Why it does not read the titles correctly like this?
Starting Rango population script...
- Python - Official Python Tutorial
- Python - How to Think like a Computer Scientist
- Python - Learn Python in 10 Minutes
- Django - Official Django Tutorial
- Django - Django Rocks
- Django - How to Tango with Django
- Other Frameworks - Bottle
- Other Frameworks - Flask
So it does not work. my populate_rango.py is:
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sarpedon33.settings')
import django
django.setup()
from rango.models import Category, Page
def populate():
python_cat = add_cat('Python')
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")
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")
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)[0]
p.url=url
p.views=views
p.save()
return p
def add_cat(name):
c = Category.objects.get_or_create(name=name)[0]
return c
# Start execution here!
if __name__ == '__main__':
print "Starting Rango population script..."
populate()
my project folder name is sarpedon33 that is why it is like that.
Models:
from django.db import models
# Create your models here.
class Category(models.Model):
name = models.CharField(max_length=128, unique=True)
def __unicode__(self): #For Python 2, use __str__ on Python 3
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.name
class Ox(models.Model):
horn_length = models.IntegerField()
class Meta:
ordering = ["horn_length"]
verbose_name_plural = "categories"
def __unicode__(self): #For Python 2, use __str__ on Python 3
return self.title
Ok I have added Page Model however this time I get AttributeError: 'Page' object has no attribute 'name'.
Here is my settings.py :
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_PATH = os.path.join(BASE_DIR,'static')
STATIC_URL = '/static/' # You may find this is already defined as such.
STATICFILES_DIRS = (STATIC_PATH,)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # Absolute path to the media directory
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '&9(_icx1*u8l0ulfa_vx1d0=oq9%*1jjw-1zl3t8b20_)5-nny'
# SECURITY WARNING: don't run with debug turned on in production!
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.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'sarpedon33.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'sarpedon33.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/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/1.8/howto/static-files/
STATIC_URL = '/static/'
Your models most likely lack the
def __unicode__(self):
return self.name
functions. When printing it calls these functions, which you override in the models. Refer to 5.3. Creating Models in http://www.tangowithdjango.com/book/chapters/models.html.
As the error message says, the Page model does not have an attribute called name, but you are trying to access it in the __unicode__ method. Change the method definition like this:
def __unicode__(self):
return self.title
I have been following along with a YouTube tutorial and even though I follow along exactly as he does it, I get the 404 error below. I have also been having no luck getting data from models into my templates. Even if the template loads, it will just come through as blank. ( I can upload an example of this as well) It loads static content but not dynamic content from the database. Anyone know why this may be? I have a guess it might be something in my settings.py? Thank you!
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/band/
My project is setup like this:
atmos_v4/
atmos_v4/
init__.py
settings.py
urls.py
wsgi.py
band/
__init__.py
admin.py
models.py
urls.py
views.py
db.sqlite3
manage.py
static/
css/
...
img/
...
js/
...
media/
...
templates/
band/
band.html
My band/models.py file:
from django.db import models
import datetime
class Band(models.Model):
name = models.CharField(max_length=100, unique=True)
date_added = models.DateTimeField(default=datetime.datetime.now())
date_founded = models.DateTimeField(null=True, blank=True)
image = models.CharField(max_length=1000, null=True, blank=True)
My band/view.py file:
from django.shortcuts import render_to_response
from django.template import RequestContext
from band.models import Band
def band(request, band_id):
band = Band.objects.get(pk=band_id)
return render_to_response('band/band.html', {'band':band}, RequestContext(request))
My band/urls.py file:
from django.conf.urls import *
urlpatterns = patterns('',
url(r'^(?P<band_id>\d+)/$', 'band.views.band'),
)
my atmos_v4/urls.py file:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.views.generic import TemplateView
urlpatterns = patterns('',
url(r'^$', TemplateView.as_view(template_name="index.html")),
.
.
.
(r'^band/', include('band.urls')),
)
My band.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
</head>
<h1>{{ band }}</h1>
<body>
</body>
</html>
My settings.py file:
"""
Django settings for atmos_v4 project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/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__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'y=3ey3sv8lm1j358(2bgthtx0bzy_cjaxug#2npx029nfs#5i%'
# 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',
'beer',
'band',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'atmos_v4.urls'
WSGI_APPLICATION = 'atmos_v4.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.7/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/1.7/howto/static-files/
STATIC_URL = '/static/'
from os.path import join
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
)
STATIC_PATH = os.path.join(BASE_DIR,'static')
STATICFILES_DIRS = (
STATIC_PATH,
)
You're going to the URL "/band/" in your browser, but you haven't defined a urlpattern for that URL: you've defined "/" and "/band/<id>/". Either go to the root page, or find the ID of an existing band object and go to that page.
You would almost certainly be better off doing the official Django tutorial, rather than following a random YouTube video.