/关系“ products_product”不存在ProgrammingError第1行:... votes_total”,“ products_product”。“ hunter_id”来自“ products_

时间:2020-10-02 13:31:54

标签: python django

错误:

位于/的ProgrammingError 关系“ products_product”不存在 第1行:... votes_total“,” products_product“。” hunter_id“来自” products _...

我的views.py

from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from .models import Product
from django.utils import timezone

def home(request):
    products = Product.objects
    return render(request, 'products/home.html',{'products':products})

@login_required(login_url="/accounts/login")
def create(request):
    if request.method == 'POST':
        if request.POST['title'] and request.POST['body'] and request.POST['url'] and request.FILES['icon'] and request.FILES['image']:
            product = Product()
            product.title = request.POST['title']
            product.body = request.POST['body']
            if request.POST['url'].startswith('http://') or request.POST['url'].startswith('https://'):
                product.url = request.POST['url']
            else:
                product.url = 'http://' + request.POST['url']
            product.icon = request.FILES['icon']
            product.image = request.FILES['image']
            product.pub_date = timezone.datetime.now()
            product.hunter = request.user
            product.save()
            return redirect('/products/' + str(product.id))
        else:
            return render(request, 'products/create.html',{'error':'All fields are required.'})
    else:
        return render(request, 'products/create.html')

def detail(request, product_id):
    product = get_object_or_404(Product, pk=product_id)
    return render(request, 'products/detail.html',{'product':product})

@login_required(login_url="/accounts/login")
def upvote(request, product_id):
    if request.method == 'POST':
        product = get_object_or_404(Product, pk=product_id)
        product.votes_total += 1
        product.save()
        return redirect('/products/' + str(product.id))

我的模型。py:

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

class Product(models.Model):
    title = models.CharField(max_length=255)
    pub_date = models.DateTimeField()
    body = models.TextField()
    url = models.TextField()
    image = models.ImageField(upload_to='images/')
    icon = models.ImageField(upload_to='images/')
    votes_total = models.IntegerField(default=1)
    hunter = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.title

    def summary(self):
        return self.body[:100]

    def pub_date_pretty(self):
        return self.pub_date.strftime('%b %e %Y')

urls.py:

from django.urls import path, include
from . import views

urlpatterns = [
    path('create', views.create, name='create'),
    path('<int:product_id>', views.detail, name='detail'),
    path('<int:product_id>/upvote', views.upvote, name='upvote'),
    

]

TraceBack:

Traceback (most recent call last):
  File "C:\Users\daghe\anaconda3\envs\env\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)

The above exception (relation "products_product" does not exist
LINE 1: ...votes_total", "products_product"."hunter_id" FROM "products_...
                                                             ^
) was the direct cause of the following exception:
  File "C:\Users\daghe\anaconda3\envs\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\daghe\anaconda3\envs\env\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\daghe\Desktop\Osama-Da-master\products\views.py", line 8, in home
    return render(request, 'products/home.html',{'products':products})
  File "C:\Users\daghe\anaconda3\envs\env\lib\site-packages\django\shortcuts.py", line 19, in render
    content = loader.render_to_string(template_name, context, request, using=using)
  File "C:\Users\daghe\anaconda3\envs\env\lib\site-packages\django\template\loader.py", line 62, in render_to_string
    return template.render(context, request)
  File "C:\Users\daghe\anaconda3\envs\env\lib\site-packages\django\template\backends\django.py", line 61, in render
    return self.template.render(context)
  File "C:\Users\daghe\anaconda3\envs\env\lib\site-packages\django\template\base.py", line 170, in render
    return self._render(context)
  File "C:\Users\daghe\anaconda3\envs\env\lib\site-packages\django\template\base.py", line 162, in _render
    return self.nodelist.render(context)
  File "C:\Users\daghe\anaconda3\envs\env\lib\site-packages\django\template\base.py", line 938, in render
    bit = node.render_annotated(context)
  File "C:\Users\daghe\anaconda3\envs\env\lib\site-packages\django\template\base.py", line 905, in render_annotated
    return self.render(context)
  File "C:\Users\daghe\anaconda3\envs\env\lib\site-packages\django\template\loader_tags.py", line 150, in render
    return compiled_parent._render(context)
  File "C:\Users\daghe\anaconda3\envs\env\lib\site-packages\django\template\base.py", line 162, in _render
    return self.nodelist.render(context)
  File "C:\Users\daghe\anaconda3\envs\env\lib\site-packages\django\template\base.py", line 938, in render
    bit = node.render_annotated(context)
  File "C:\Users\daghe\anaconda3\envs\env\lib\site-packages\django\template\base.py", line 905, in render_annotated
    return self.render(context)
  File "C:\Users\daghe\anaconda3\envs\env\lib\site-packages\django\template\loader_tags.py", line 62, in render
    result = block.nodelist.render(context)
  File "C:\Users\daghe\anaconda3\envs\env\lib\site-packages\django\template\base.py", line 938, in render
    bit = node.render_annotated(context)
  File "C:\Users\daghe\anaconda3\envs\env\lib\site-packages\django\template\base.py", line 905, in render_annotated
    return self.render(context)
  File "C:\Users\daghe\anaconda3\envs\env\lib\site-packages\django\template\defaulttags.py", line 168, in render
    len_values = len(values)
  File "C:\Users\daghe\anaconda3\envs\env\lib\site-packages\django\db\models\query.py", line 269, in __len__
    self._fetch_all()
  File "C:\Users\daghe\anaconda3\envs\env\lib\site-packages\django\db\models\query.py", line 1303, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "C:\Users\daghe\anaconda3\envs\env\lib\site-packages\django\db\models\query.py", line 53, in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
  File "C:\Users\daghe\anaconda3\envs\env\lib\site-packages\django\db\models\sql\compiler.py", line 1156, in execute_sql
    cursor.execute(sql, params)
  File "C:\Users\daghe\anaconda3\envs\env\lib\site-packages\django\db\backends\utils.py", line 98, in execute
    return super().execute(sql, params)
  File "C:\Users\daghe\anaconda3\envs\env\lib\site-packages\django\db\backends\utils.py", line 66, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "C:\Users\daghe\anaconda3\envs\env\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "C:\Users\daghe\anaconda3\envs\env\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\daghe\anaconda3\envs\env\lib\site-packages\django\db\utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "C:\Users\daghe\anaconda3\envs\env\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)

Exception Type: ProgrammingError at /
Exception Value: relation "products_product" does not exist
LINE 1: ...votes_total", "products_product"."hunter_id" FROM "products_...
               

                                          ^

1 个答案:

答案 0 :(得分:0)

def home应该

def home(request):
  products = Product.objects.all()
  ...

代替

def home(request):
  products = Product.objects
  ...

Product.objects返回实际的类,而不是所有的对象。 您需要使用Product.objects.all()才能获取实际的对象。

django文档在解释queries方面做得很好。