Pierce O'Neill
Pierce O'Neill

Reputation: 383

column "user_id" of relation "checkout_order" does not exist

Full traceback Message

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...

I am trying to attribute orders to particular user accounts which I have already created.I have gone through the process I did on a previous app but it is not working and keeps throwing up the following error.

enter image description here

I think it is something to do with the placement of the user foreignkey but I cant figure it out or find any other posts on here related to it.

My model.py file is as follows.

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)

My forms.py is

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 is

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

                
         

Can somebody help me or show me where I am going wrong with this? It is the last part of a project I am working on and it is wrecking my head.

Upvotes: 1

Views: 2796

Answers (1)

A. J. Parr
A. J. Parr

Reputation: 8026

This error indicates that the database doesn't have the "user_id" column, so you probably haven't created your latest migrations or haven't run them against the database. I'd recommend running these commands in your project folder:

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

Upvotes: 2

Related Questions