ValueError:字段“ id”需要一个数字,但得到了“ index.html”

时间:2020-09-27 12:12:30

标签: python html django

我正在尝试使用Django创建一个简单的待办事项列表应用程序。但是面对此错误将运行服务器 ValueError:字段“ id”应为数字,但得到了“ index.html”。

models.py

from django.db import models

class List(models.Model):
    item = models.CharField(max_length=200)
    completed = models.BooleanField(default=False)

    def __str__(self):
        return self.item + '|' + str(self.completed)

urls.py

from . import views

urlpatterns = [
    path("index",views.index, name="home"),
    path("delete/<list_id>/", views.delete , name="delete"),
]

views.py

from django.http import HttpResponse
from django.shortcuts import render, redirect
from .models import List
from .forms import ListForm
from django.contrib import messages

# Create your views here.

def index(request):
    if request.method == 'POST':
        form = ListForm(request.POST or None)

        if form.is_valid():
            form.save()
            all_items = List.objects.all
            messages.success(request,('Items has been Added to List !!'))
            return render(request,'home.html', {'all_items': all_items})
    else:
        all_items = List.objects.all
        return render(request,'index.html',{'all_items': all_items})

def delete(request, list_id):
    item = List.objects.get(pk=list_id)
    item.delete()
    messages.success(request,('Item has been deleted'))
    return redirect('index')

index.html

{% extends 'home.html' %}

{% block content %}
    {% if messages %}
        {% for message in messages %}
            <div class="alert alert-warning alert-dismissable" role="alert">
                <button class="close" data-dismiss="alert">
                    <small><sup>x</sup></small>
                </button>
                {{ message }}
            </div>
        {% endfor %}
    {% endif %}
    {% if all_items %}
    <table class="table table-bordered">
        {% for things in all_items %}
            <tr>
                <td>{{ things.item }}</td>
                <td><center>{{ things.completed }}</center></td>
                <td><center><a href="{% url 'delete' things.id %}">Delete</a></center></td>
            </tr>
        {% endfor %}
    </table>
    {% endif %}


{% endblock content %}

home.html

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    <title>Home</title>
  </head>
  <body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
  <a class="navbar-brand" href="{% url 'home' %}">To-Do Lists</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>

  <div class="collapse navbar-collapse" id="navbarSupportedContent">
    <ul class="navbar-nav mr-auto">
    </ul>
    <form class="form-inline my-2 my-lg-0" method="POST">
        {% csrf_token %}
      <input class="form-control mr-sm-2" type="search" placeholder="Add Items" aria-label="Search" name="item">
      <button class="btn btn-outline-secondary my-2 my-sm-0" type="submit">Add To List</button>
    </form>
  </div>
</nav>
    <br/>
    <div class="container">
   {% block content %}
   {% endblock content %}
    </div>
    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
  </body>
</html>

迁移文件0001_intial.py

# Generated by Django 3.1.1 on 2020-09-27 05:07

from django.db import migrations, models


class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='List',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('item', models.CharField(max_length=200)),
                ('completed', models.BooleanField(default=False)),
            ],
        ),
    ]

here is my note app page

Error that I getting

有人可以告诉我我哪里做错了吗? 预先感谢

1 个答案:

答案 0 :(得分:1)

尝试将"{% url 'delete' things.id %}"替换为"{% url '<appname>:delete' things.id %}",应用名称应替换为您的应用名称。相同的格式在Django 2.x中对我有效。