所以我正在研究Django / Postgres项目。
当我运行docker-compose时,项目将在一个容器中启动Django而在另一个容器中启动Postgres。我可以查看我的项目的某些URL,但查询MyProfile模型的URL都会导致以下错误:
docker@postgres ERROR: relation "accounts_myprofile" does not exist
我跑了两个:
docker-compose run web python manage.py makemigrations
和
docker-compose run web python manage.py migrate
我不确定这是否重要,但这回复于:
Operations to perform:
Apply all migrations: admin, auth, cities, contenttypes, django_messages, easy_thumbnails, guardian, sessions, sites, userena
Running migrations:
No migrations to apply.
Your models have changes that are not yet reflected in a migration, and so won't be applied.
Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them.
在下面附加我的docker-compose和Django设置。
搬运工-撰写
web:
restart: always
build: ./web
expose:
- "8000"
links:
- postgres:postgres
volumes:
- /usr/src/app
- /usr/src/app/static
env_file: .env
environment:
DEBUG: 'true'
command: python manage.py runserver 0.0.0.0:8000
postgres:
restart: always
image: kartoza/postgis:9.4-2.1
ports:
- "5432:5432"
volumes:
- pgdata:/var/lib/postgresql/data/
models.py
from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext as _
from userena.models import UserenaBaseProfile
from django.conf import settings
from PIL import Image
from django_resized import ResizedImageField
import datetime
class MyProfile(UserenaBaseProfile):
user = models.OneToOneField(User,
unique=True,
verbose_name=_('user'),
related_name='my_profile')
storename=models.CharField(null=True, blank=True, max_length=20)
streetaddress=models.CharField(null=True, blank=True, max_length=30)
city = models.CharField(null=True, blank=True, max_length=20)
state = models.CharField(null=True, blank=True, max_length=20)
zipcode = models.IntegerField(_('zipcode'),
null=True, blank=True)
nearbyzips1=models.IntegerField(null=True, blank=True)
nearbyzips2=models.IntegerField(null=True, blank=True)
nearbyzips3=models.IntegerField(null=True, blank=True)
nearbyzips4=models.IntegerField(null=True, blank=True)
nearbyzips5=models.IntegerField(null=True, blank=True)
nearbyzips6=models.IntegerField(null=True, blank=True)
phone=models.CharField(null=True, blank=True, max_length=16)
websiteurl=models.CharField(null=True, blank=True, max_length=38)
deliveryoption=models.BooleanField(default=False)
storebio=models.CharField(null=True, blank=True, max_length=100)
storespecials=models.CharField(null=True, blank=True, max_length=65)
reviewavg=models.FloatField(null=True, blank=True, max_length=5)
coverpic = ResizedImageField(max_width=350, upload_to="site_media/media/covers/", null=True, blank=True)
def __unicode__(self):
return u'%s %s %s %s %s %s %s %s' % (self.user, self.storename, self.streetaddress, self.city, self.state, self.zipcode, self.storebio, self.reviewavg)
class Entry(models.Model):
headline= models.CharField(max_length=200,)
body_text = models.TextField()
author=models.ForeignKey(settings.AUTH_USER_MODEL, related_name='entryauthors')
pub_date=models.DateTimeField(auto_now_add=True)
zipcode =models.IntegerField(null=True)
entrytype = models.IntegerField(null=True)
price1 = models.CharField(max_length=20)
price2 = models.CharField(max_length=20)
price3 = models.CharField(null=True, blank=True, max_length=20)
price4 = models.CharField(null=True, blank=True, max_length=20)
price5 = models.CharField(null=True, blank=True, max_length=20)
item_picture = ResizedImageField(max_width=400, upload_to="site_media/media/items/")
def __str__(self):
return u'%s %s %s %s %s %s %s' % (self.headline, self.body_text, self.author, self.pub_date, self.zipcode, self.price1, self.price2)
views.py(仅包含触发错误的查询的函数)
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.db import models
from django.contrib.auth.models import User
from accounts.forms import UserReviewForm
from accounts.forms import SellForm
from accounts.models import Entry
from accounts.models import UserReview
from accounts.models import MyProfile
from django.conf.urls import include, url
from django.template.loader import render_to_string
import json as simplejson
from django.core.serializers.json import DjangoJSONEncoder
from django.http import HttpResponse
import datetime
from userena import settings as userena_settings
from django.shortcuts import redirect, get_object_or_404
from userena.utils import signin_redirect, get_profile_model, get_user_model
from userena.views import ExtraContextTemplateView
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from django_messages.models import inbox_count_for
from django.contrib.auth.views import login
from accounts.serializers import EntrySerializer
def storefront(request):
if request.user.is_authenticated():
if request.user.my_profile.zipcode:
latest_entries = Entry.objects.filter(zipcode__in=[request.user.my_profile.nearbyzips1,
request.user.my_profile.nearbyzips2,
request.user.my_profile.nearbyzips3,
request.user.my_profile.nearbyzips4,
request.user.my_profile.nearbyzips5]).order_by('-pub_date')[:16]
unread_list = inbox_count_for(request.user)
context = {'latest_entries': latest_entries, 'unread_list': unread_list}
else:
latest_entries = Entry.objects.order_by('-pub_date')[:16]
context = {'latest_entries': latest_entries}
else:
latest_entries = Entry.objects.order_by('-pub_date')[:16]
context = {'latest_entries': latest_entries}
if request.is_ajax():
if request.GET.get('filter') == 'new':
latest_entries = latest_entries.filter(entrytype=1)
context = {'latest_entries': latest_entries}
return render(request, 'storefrontload.html', context)
if request.GET.get('filter') == 'old':
latest_entries = Entry.objects.filter(entrytype=2)
context = {'latest_entries': latest_entries}
return render(request, 'storefrontload.html', context)
if request.GET.get('filter') == 'oklder':
latest_entries = Entry.objects.filter(entrytype=3)
context = {'latest_entries': latest_entries}
return render(request, 'storefrontload.html', context)
return render(request, 'storefront.html', context)
settings.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
PACKAGE_ROOT = os.path.abspath(os.path.dirname(__file__))
PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
ALLOWED_HOSTS=['*']
DEBUG=True
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': os.environ['DB_NAME'],
'USER': os.environ['DB_USER'],
'PASSWORD': os.environ['DB_PASS'],
'HOST': os.environ['DB_SERVICE'],
'PORT': os.environ['DB_PORT'],
}
}
TIME_ZONE = "UTC"
LANGUAGE_CODE = "en-us"
SITE_ID = int(os.environ.get("SITE_ID", 1))
USE_I18N = True
USE_L10N = True
USE_TZ = True
MEDIA_ROOT = os.path.join(PACKAGE_ROOT, "media")
MEDIA_URL = "/media/"
STATIC_ROOT = os.path.join(PACKAGE_ROOT, "static1")
STATIC_URL = "/static/"
STATICFILES_DIRS = [
os.path.join(PACKAGE_ROOT, "static"),
]
STATICFILES_FINDERS = [
"django.contrib.staticfiles.finders.FileSystemFinder",
"django.contrib.staticfiles.finders.AppDirectoriesFinder",
]
MIDDLEWARE_CLASSES = [
"django.middleware.common.CommonMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'templates'),
],
'APP_DIRS': True,
'OPTIONS': {
'debug': DEBUG,
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
答案 0 :(得分:0)
出于某种原因跑步:
docker-compose run web python manage.py makemigrations accounts
docker-compose run web python manage.py migrate accounts
返回此
Running migrations:
No migrations to apply.
Your models have changes that are not yet reflected in a migration, and so won't be applied
但实际进入Django容器并直接运行
python manage.py makemigrations accounts
python manage.py migrate accounts
这很有效,我的项目现在完全没有数据库错误。
所以我的问题已经解决但我无法告诉你为什么用docker-compose运行这个命令对我来说似乎不起作用。