如何列出数据库中的所有节点?

问题描述 投票:0回答:1

我正在尝试创建一个简单的模型Node和一个简单的网页,显示列表中的所有节点。但它似乎不起作用,每次我更改代码我都会遇到新的错误。所以我放弃了来到这里。这就是我做的:我创建了一个Node模型:

class Node(models.Model):
    ID = models.DecimalField(max_digits=9, decimal_places=6)
    nb_solenoid = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True)
    connexion = models.CharField(max_length=255)

    def get_absolute_url(self):
        return reverse("node:index", kwargs={"id": self.id})

用这种形式:

class NodeForm(forms.ModelForm):
ID = forms.DecimalField(initial=0)
nb_solenoid = forms.DecimalField(initial=1)
connexion = forms.CharField(required=False,
                            widget=forms.Textarea(
                                  attrs={
                                      "placeholder": "type of connexion"
                                  }))
    class Meta:
        model = Node
        fields = [
            'ID',
            'nb_solenoid',
            'connexion'
        ]

这是我的views.py:

def index(request):
    queryset = Node.objects.all()
    context = {
        "object_list": queryset
    }
    return render(request, "node/index.html", context)

这是我在urls.py中的代码:

urlpatterns = [path('', views.index, name='index')]

当我打电话给这个网址时:http://localhost:8000/node我现在收到此错误:

NoReverseMatch at /node
Reverse for 'index' with keyword arguments '{'id': 1}' not found. 1 pattern(s) tried: ['node$']

什么是NoReverseMatch错误,如何解决我的问题?让我说我是Django的初学者。谢谢。

python-3.x django-2.0
1个回答
0
投票

问题是你的命名url路径node:index没有参数(大概是因为该视图只列出了所有节点,而不是特定节点),但你的模型的get_absolute_url试图用kwarg的id来反转模式。核心问题是你的get_absolute_url方法;但是,您可能也会因为使用基于类的通用视图而受益:

URLs.朋友:

urlpatterns = [
  path('nodes/', NodeList.as_view(), name="node-list"),
  path('node/<id>/', NodeDetail.as_view(), name="node-detail")
]

view.朋友:

from django.views.generic import ListView, DetailView

from .models import Node


class NodeList(ListView):
   model = Node


class NodeDetail(DetailView):
   model = Node

models.朋友:

class Node(models.Model):
  <snip>
    def get_absolute_url(self):
        return reverse("node-detail", kwargs={"id": self.id})

我真的应该提到,基于类的通用视图的文档位于:https://docs.djangoproject.com/en/2.1/topics/class-based-views/generic-display/

© www.soinside.com 2019 - 2024. All rights reserved.