关系“ checkout_order”的列“ user_id”不存在

时间:2018-12-04 02:17:40

标签: python django

完整的追溯消息

Request Method: POST
Request URL: http://milestone-project-05-minder-finder-pierceoneill.c9users.io/admin/checkout/order/add/

Django Version: 1.11
Python Version: 3.4.3
Installed Applications:
['django.contrib.admin',
 'django.contrib.humanize',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django_forms_bootstrap',
 'bootstrap_datepicker_plus',
 'home',
 'about',
 'accounts',
 'blog',
 'bookings',
 'babysitters',
 'contact',
 'django_gravatar',
 'checkout',
 'storages']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 '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']



Traceback:

File "/usr/local/lib/python3.4/dist-packages/django/db/backends/utils.py" in execute
  65.                 return self.cursor.execute(sql, params)

The above exception (column "user_id" of relation "checkout_order" does not exist
LINE 1: INSERT INTO "checkout_order" ("user_id") VALUES (2) RETURNIN...
                                      ^
) was the direct cause of the following exception:

File "/usr/local/lib/python3.4/dist-packages/django/core/handlers/exception.py" in inner
  41.             response = get_response(request)

File "/usr/local/lib/python3.4/dist-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/usr/local/lib/python3.4/dist-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/usr/local/lib/python3.4/dist-packages/django/contrib/admin/options.py" in wrapper
  551.                 return self.admin_site.admin_view(view)(*args, **kwargs)

File "/usr/local/lib/python3.4/dist-packages/django/utils/decorators.py" in _wrapped_view
  149.                     response = view_func(request, *args, **kwargs)

File "/usr/local/lib/python3.4/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func
  57.         response = view_func(request, *args, **kwargs)

File "/usr/local/lib/python3.4/dist-packages/django/contrib/admin/sites.py" in inner
  224.             return view(request, *args, **kwargs)

File "/usr/local/lib/python3.4/dist-packages/django/contrib/admin/options.py" in add_view
  1508.         return self.changeform_view(request, None, form_url, extra_context)

File "/usr/local/lib/python3.4/dist-packages/django/utils/decorators.py" in _wrapper
  67.             return bound_func(*args, **kwargs)

File "/usr/local/lib/python3.4/dist-packages/django/utils/decorators.py" in _wrapped_view
  149.                     response = view_func(request, *args, **kwargs)

File "/usr/local/lib/python3.4/dist-packages/django/utils/decorators.py" in bound_func
  63.                 return func.__get__(self, type(self))(*args2, **kwargs2)

File "/usr/local/lib/python3.4/dist-packages/django/contrib/admin/options.py" in changeform_view
  1408.             return self._changeform_view(request, object_id, form_url, extra_context)

File "/usr/local/lib/python3.4/dist-packages/django/contrib/admin/options.py" in _changeform_view
  1448.                 self.save_model(request, new_object, form, not add)

File "/usr/local/lib/python3.4/dist-packages/django/contrib/admin/options.py" in save_model
  979.         obj.save()

File "/usr/local/lib/python3.4/dist-packages/django/db/models/base.py" in save
  806.                        force_update=force_update, update_fields=update_fields)

File "/usr/local/lib/python3.4/dist-packages/django/db/models/base.py" in save_base
  836.             updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)

File "/usr/local/lib/python3.4/dist-packages/django/db/models/base.py" in _save_table
  922.             result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)

File "/usr/local/lib/python3.4/dist-packages/django/db/models/base.py" in _do_insert
  961.                                using=using, raw=raw)

File "/usr/local/lib/python3.4/dist-packages/django/db/models/manager.py" in manager_method
  85.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "/usr/local/lib/python3.4/dist-packages/django/db/models/query.py" in _insert
  1060.         return query.get_compiler(using=using).execute_sql(return_id)

File "/usr/local/lib/python3.4/dist-packages/django/db/models/sql/compiler.py" in execute_sql
  1099.                 cursor.execute(sql, params)

File "/usr/local/lib/python3.4/dist-packages/django/db/backends/utils.py" in execute
  80.             return super(CursorDebugWrapper, self).execute(sql, params)

File "/usr/local/lib/python3.4/dist-packages/django/db/backends/utils.py" in execute
  65.                 return self.cursor.execute(sql, params)

File "/usr/local/lib/python3.4/dist-packages/django/db/utils.py" in __exit__
  94.                 six.reraise(dj_exc_type, dj_exc_value, traceback)

File "/usr/local/lib/python3.4/dist-packages/django/utils/six.py" in reraise
  685.             raise value.with_traceback(tb)

File "/usr/local/lib/python3.4/dist-packages/django/db/backends/utils.py" in execute
  65.                 return self.cursor.execute(sql, params)

Exception Type: ProgrammingError at /admin/checkout/order/add/
Exception Value: column "user_id" of relation "checkout_order" does not exist
LINE 1: INSERT INTO "checkout_order" ("user_id") VALUES (2) RETURNIN...

我正在尝试将订单归因于我已经创建的特定用户帐户。我已经完成了我在上一个应用程序上执行的过程,但是它无法正常工作,并不断引发以下错误。

enter image description here

我认为这与用户外键的位置有关,但我无法弄清楚或在此处找到与其相关的任何其他帖子。

我的model.py文件如下。

from django.db import models
from babysitters.models import Babysitter
from django.contrib.auth.models import User

class Order(models.Model):
    user = models.ForeignKey(User)
    def __str__(self):
        return "{0}".format(self.date)
        
        
class OrderLineItem(models.Model):
    
    order = models.ForeignKey(Order, null=False)
    babysitter = models.ForeignKey(Babysitter, null=False)
    quantity = models.IntegerField(blank=False)
    price = models.IntegerField(blank=False)
    def __str__(self):
        return "{0} {1} {2} @ {3}".format(self.quantity, self.babysitter.firstName, self.babysitter.quantity, self.babysitter.price)

我的forms.py是

from django import forms
from .models import Order

class MakePaymentForm(forms.Form):

    MONTH_CHOICES = [(i, i,) for i in range(1, 13)]
    YEAR_CHOICES = [(i, i,) for i in range(2018, 2036)]

    
    credit_card_number = forms.CharField(widget=forms.TextInput(attrs= 
    {'placeholder':'Credit card number'}),
    max_length=16, label='Credit card number', required=True)
    expiry_month = forms.ChoiceField(label="Month", choices=MONTH_CHOICES)
    expiry_year = forms.ChoiceField(label="Year", choices=YEAR_CHOICES)
    cvv = forms.CharField(widget=forms.TextInput(attrs= 
    {'placeholder':'cvv'}),
    max_length=3, label='Security code (CVV)', required=True)
    stripe_id = forms.CharField(widget=forms.HiddenInput)
    
    class OrderForm(forms.ModelForm):
    class Meta:
        model = Order
        fields = ('user',)

and views.py是

from django.contrib import messages, auth
from django.contrib.auth.decorators import login_required
from checkout.forms import MakePaymentForm, OrderForm
from django.shortcuts import render, get_object_or_404, redirect, reverse
from django.template.context_processors import csrf
from django.conf import settings
from django.utils import timezone
from babysitters.models import Babysitter
from .models import OrderLineItem
import stripe

# stripe.api_key = settings.STRIPE_SECRET


@login_required(login_url="/accounts/login")
def buy_now(request, id):
    if request.method == 'POST':
        order_form = OrderForm(request.POST)
        payment_form = MakePaymentForm(request.POST)
        if order_form.is_valid() and payment_form.is_valid():
            order = order_form.save(commit=False)
            order.date = timezone.now()
            order.save()
            
            bookings = request.session.get('bookings', {})
            total = 0
            for id, quantity in bookings.items():
                babysitter = get_object_or_404(Babysitter, pk=id)
                total += quantity * babysitter.price
                order_line_item = OrderLineItem(
                    order = order, 
                    babysitter = babysitter, 
                    quantity = quantity
                    )
                order_line_item.save()
                
            try:
                customer = stripe.Charge.create(
                    amount = int(total * 100),
                    currency = "EUR",
                    description = request.user.email,
                    card = payment_form.cleaned_data['stripe_id'],
                )
            except stripe.error.CardError:
                messages.error(request, "Your card was declined!")
                
            if customer.paid:
                messages.error(request, "You have successfully paid")
                request.session['cart'] = {}
                return redirect(reverse('products'))
            else:
                messages.error(request, "Unable to take payment")
        else:
            print(payment_form.errors)
            messages.error(request, "We were unable to take a payment with that card!")
    else:
        payment_form = MakePaymentForm()
        order_form = OrderForm()
        
    return render(request, "checkout.html", {'order_form': order_form, 'payment_form': payment_form, 'publishable': settings.STRIPE_PUBLISHABLE})
    
    stripe.api_key = settings.STRIPE_SECRET

                
         

有人可以帮助我还是告诉我我要怎么做?这是我正在研究的项目的最后一部分,令人头疼。

1 个答案:

答案 0 :(得分:1)

此错误表明数据库没有“ user_id”列,因此您可能尚未创建最新迁移或未针对数据库运行它们。我建议在您的项目文件夹中运行以下命令:

$ python manage.py makemigrations
$ python manage.py migrate