createsuperuser命令中的django + heroku + postgres错误,给出错误“ psycopg2.errors.UndefinedTable:关系“ users_profile”不存在”

时间:2019-07-08 05:19:45

标签: python django postgresql heroku psycopg2

我想用PostgreSQL在heroku中部署我的django应用,一切顺利进行makemigrations和migration运行正常,但是当我尝试创建superuser时,它给我错误

(youngmindsenv) E:\young_minds\heroku\youngminds>heroku run bash
Running bash on ? youngminds... up, run.8229 (Free)
~ $ python manage.py createsuperuser
Username (leave blank to use 'u21088'): johnson
Email address: johnson@gmail.com
Password:
Password (again):
Traceback (most recent call last):
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils
.py", line 85, in _execute
    return self.cursor.execute(sql, params)
psycopg2.errors.UndefinedTable: relation "users_profile" does not exist
LINE 1: INSERT INTO "users_profile" ("user_id", "image", "descriptio...
                    ^


The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/_
_init__.py", line 371, in execute_from_command_line
    utility.execute()
  File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/_
_init__.py", line 365, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/b
ase.py", line 288, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/mana
gement/commands/createsuperuser.py", line 59, in execute
    return super().execute(*args, **options)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/b
ase.py", line 335, in execute
    output = self.handle(*args, **options)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/mana
gement/commands/createsuperuser.py", line 179, in handle
    self.UserModel._default_manager.db_manager(database).create_superuser(**user
_data)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/mode
ls.py", line 161, in create_superuser
    return self._create_user(username, email, password, **extra_fields)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/mode
ls.py", line 144, in _create_user
    user.save(using=self._db)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/base
_user.py", line 73, in save
    super().save(*args, **kwargs)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/base.py
", line 729, in save
    force_update=force_update, update_fields=update_fields)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/base.py
", line 769, in save_base
    update_fields=update_fields, raw=raw, using=using,
  File "/app/.heroku/python/lib/python3.6/site-packages/django/dispatch/dispatch
er.py", line 178, in send
    for receiver in self._live_receivers(sender)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/dispatch/dispatch
er.py", line 178, in <listcomp>
    for receiver in self._live_receivers(sender)

  File "/app/users/signals.py", line 9, in create_profile
    Profile.objects.create(user=instance) ####problem in this line

  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/manager
.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.p
y", line 417, in create
    obj.save(force_insert=True, using=self.db)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/base.py
", line 729, in save
    force_update=force_update, update_fields=update_fields)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/base.py
", line 759, in save_base
    updated = self._save_table(raw, cls, force_insert, force_update, using, upda
te_fields)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/base.py
", line 842, in _save_table
    result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/base.py
", line 880, in _do_insert
    using=using, raw=raw)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/manager
.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.p
y", line 1125, in _insert
    return query.get_compiler(using=using).execute_sql(return_id)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/sql/com
piler.py", line 1281, in execute_sql
    cursor.execute(sql, params)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils
.py", line 100, in execute
    return super().execute(sql, params)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils
.py", line 68, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._e
xecute)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils
.py", line 77, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils
.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/utils.py", lin
e 89, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils
.py", line 85, in _execute
    return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "users_profile" does not exist
LINE 1: INSERT INTO "users_profile" ("user_id", "image", "descriptio...

我可以看到我的signal.py文件中有问题,但是我不知道是什么原因导致了这个问题以及如何解决

signals.py

from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from . models import Profile

@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)
    else:
        pass

@receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
    instance.profile.save()

views.py

from django.shortcuts import render,redirect
from django.contrib import messages
from .forms import UserRegistrationForm,UserUpdateForm,ProfileUpdateForm
from django.contrib.auth.decorators import login_required
from django.views.generic import ListView
from .models import Profile
from blog.views import *
from django.contrib.auth import authenticate, login
from django.http import JsonResponse

# Create your views here.
def register(request):
    if request.method == "POST":
        form = UserRegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')

            new_user = authenticate(username=form.cleaned_data['username'],
                                    password=form.cleaned_data['password1'])
            login(request, new_user)

        p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)
        if form.is_valid():

            if  p_form.is_valid:

                p_form.save()
                messages.success(request,f'Account created! Welcome Young Minds family!')
                return redirect('blog-home')
    else:
        form = UserRegistrationForm()
        form_profile = ProfileUpdateForm()
    response = common_info()
    categories =  response["categories"]

    return render(request,"users/registration.html",{"form":form ,"form_profile":form_profile,"categories":categories})

def validate_username(request):
    username = request.GET.get('username', None)
    data = {
        'is_taken': User.objects.filter(username__iexact=username).exists()
    }
    if data['is_taken']:
        data['error_message'] = 'A user with this username "{}" already exists !'.format(username)

        return JsonResponse(data)

    email = request.GET.get('email', None)
    if email != "":
        data = {
            'is_taken': User.objects.filter(email__iexact=email).exists()
        }
        if data['is_taken']:
            data['error_message'] = '"{}" email id is already registered!'.format(email)
        return JsonResponse(data)



'''@login_required
def profile(request):

    user_post = Post.objects.filter(author__username=request.user)
    context = {}
    response = common_info()
    context["user_posts"] = user_post
    context['categories'] =  response["categories"]
    context['popular_posts'] =  response["popular_post"]

    return render(request,"users/profile.html",context)'''

class ProfileListView(ListView):
    model = Post
    template_name = 'users/profile.html'
    context_object_name = 'user_posts'
    ordering = ['-date_posted']
    paginate_by = 5

    def get_queryset(self):
        return Post.objects.filter(author__username=self.kwargs.get('username'))

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        response = common_info()
        context['categories'] =  response["categories"]
        context['popular_posts'] =  response["popular_post"]
        user = self.kwargs.get('username')
        context["description"] = Profile.objects.get(user__username__iexact=self.kwargs.get('username'))
        context['title'] = user.title() +"'s Profile"
        return context

@login_required
def profile_update(request):
    if request.method == 'POST':
        u_form = UserUpdateForm(request.POST, instance=request.user)
        p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)
        if u_form.is_valid and p_form.is_valid:
            u_form.save()
            p_form.save()
            messages.success(request,f'Your account has been updated successfully!.')
            return redirect('profile' ,request.user)

    else:
        u_form = UserUpdateForm(instance=request.user)
        p_form = ProfileUpdateForm(instance=request.user.profile)
    response = common_info()
    categories =  response["categories"]
    context = {"u_form":u_form,"p_form":p_form,"categories":categories,"title":"Update Profile"}
    return render(request,"users/profile_update.html",context)

请帮帮我!如何解决此问题,如有需要,我会更新任何其他信息。

更新


问题解决了,我要做的是解决

1)删除了我的生产表,因为我那里没有任何数据。 2)在本地运行makemigrations命令 3)直接在heroku bash中运行migration命令,而无需运行makemigrations

这样做可以解决问题!

希望这会在将来对某人有所帮助!感谢所有抽出时间对此发表评论和回答的人

1 个答案:

答案 0 :(得分:0)

正如shafik所说,您的错误可能是由于您跑步

  

python manage.py makemigrations

创建迁移跟踪文件,但您没有运行

  

python manage.py migration

它根据上一个命令创建的迁移历史文件来创建/更改数据库。