首页 > 解决方案 > 教程 4 中的 Django 教程错误(/polls/1/ 处的操作错误)

问题描述

我是编码和网络开发的新手,但我渴望学习和进步。

我在模板渲染过程中遇到了这个错误。检查过的问题,但找不到任何答案,任何人都可以帮助解决这个问题。无法理解什么是操作错误。

屏幕上显示的错误如下

OperationalError at /polls/1/
no such column: polls_choice.id
Request Method: GET
Request URL:    http://127.0.0.1:8000/polls/1/
Django Version: 3.2.1
Exception Type: OperationalError
Exception Value:    
no such column: polls_choice.id
Exception Location: /Users/rishipalsingh/Projects/notes/mysite_dj1/venv/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py, line 423, in execute
Python Executable:  /Users/rishipalsingh/Projects/notes/mysite_dj1/venv/bin/python3
Python Version: 3.9.0
Python Path:    
['/Users/rishipalsingh/Projects/notes/mysite_dj1/mysite',
 '/Library/Frameworks/Python.framework/Versions/3.9/lib/python39.zip',
 '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9',
 '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload',
 '/Users/rishipalsingh/Projects/notes/mysite_dj1/venv/lib/python3.9/site-packages']
Server time:    Fri, 07 May 2021 10:20:59 +0530
Error during template rendering
In template /Users/rishipalsingh/Projects/notes/mysite_dj1/mysite/polls/templates/polls/detail.html, error at line 10

no such column: polls_choice.id
1   
2   <!--Option 3-->
3   
4   <h1>{{ question.question_text }}</h1>
5   
6   {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
7   
8   <form action="{% url 'polls:vote' question_id=question.id %}" method="post">
9   {% csrf_token %}
10  {% for choice in question.choice_set.all %}
11      <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}">
12      <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br>
13  {% endfor %}
14  <input type="submit" value="Vote">
15  </form>
16  
17  <!--
18  {{ question }}
19  
20  -->

民意调查/views.py

def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the question voting form.
        return render(request, 'polls/detail.html', {
            'question': question,
            'error_message': "You didn't select a Choice",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        # Always return an HttpResponseRedirect after successfully dealing
        # with POST data. This prevents data from being posted twice if a
        # user hits the Back button.
        return HttpResponseRedirect(reverse('polls:results', kwargs={'pk': question.id}))

民意调查/模板/民意调查/detail.html

<h1>{{ question.question_text }}</h1>

{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

<form action="{% url 'polls:vote' question_id=question.id %}" method="post">
{% csrf_token %}
{% for choice in question.choice_set.all %}
    <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}">
    <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br>
{% endfor %}
<input type="submit" value="Vote">
</form>

投票/urls.py

from django.urls import path

from polls import views

app_name = 'polls'

urlpatterns = [
    # ex: /polls/
    path("", views.index, name="index"),
    # ex: /polls/5/
    path("<int:question_id>/", views.detail, name="detail"),
    # ex: /polls/5/results/
    path("<int:question_id>/results/", views.results, name="results"),
    # ex: /polls/5/vote/
    path("<int:question_id>/vote/", views.vote, name="vote"),
]

投票/models.py

import datetime

from django.db import models
from django.utils import timezone

# Create your models here.

class Question(models.Model):
    id = models.BigAutoField(primary_key=True)
    question_text = models.CharField(max_length=208)
    pub_date = models.DateTimeField('date published')

    def __str__(self):
        return self.question_text
    
    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)


class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=208)
    votes = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text

标签: pythondjango

解决方案


推荐阅读