【问题标题】:view.py got an unexpected keyword argument topic_id #pview.py 有一个意外的关键字参数 topic_id #p
【发布时间】:2021-04-09 01:13:55
【问题描述】:

我正在尝试修复此视图,不断收到此错误消息, ''' 异常类型:TypeError 异常值:
主题()有一个意外的关键字参数'topic_id' 异常位置:/home/draco/shola/learning_log/lib/python3.8/site-packages/django/core/handlers/base.py,第 181 行,在 _get_response '''

view.py

def topics(request):

    topics = TopicModel.objects.order_by('date_added')
    context = {'topics' : topics}
    return render(request, 'learning_logs/topics.html',context)

def topic(request, topic_id):
    topic = TopicModel.objects.get(id=topic_id)
    entries = topic.entry_set.order_by('date_added')
    context = {'topic':topic, 'entries': entries}
    return render(request,'learning_logs/topic.html',context)

urls.py

url(r'^$', views.index, name='index.html'),


url(r'^topics/$',views.topics, name='topics.html'),
url(r'^topics/(?P<topic_id>\d+)\$',views.topics,name='topic.html')

models.py

    from django.db import models

class Topic(models.Model):

    text = models.CharField(max_length=200)
    date_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):

        return self.text

class Entry(models.Model):

    topic = models.ForeignKey(Topic,
                              on_delete = models.DO_NOTHING)
    text = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)


    class Meta:
        verbose_name_plural = 'entries'

    def __str__(self):
        if len(self.text) >50:

            return  self.text[:50]+"....."

        else:
            return self.text

模板

    <!DOCTYPE html>
{% extends "learning_logs/base.html" %}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{% block content%}
<p>Topics</p>

<ul>
    {%for topic in topics%}
    <li>
        <a href="{% url 'learning_logs:topic.html' topic.id %}">{{topic}}</a>
    </li>
    {%empty%}
    <li>no topic have been added yet</li>
    {%endfor%}
    
</ul>
{%endblock content%}
</body>
</html>

【问题讨论】:

  • urls.py 中的最后一行应该是 views.topic,而不是 topics

标签: python-3.x django django-views


【解决方案1】:

这行代码出错:

 url(r'^topics/(?P<topic_id>\d+)\$',views.topics,name='topic.html')

 url(r'^topics/(?P<topic_id>\d+)\$',**views.topics**,name='topic.html')

应该更正

 url(r'^topics/(?P<topic_id>\d+)\$',**views.topic**,name='topic.html')

【讨论】:

  • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 2017-09-26
  • 1970-01-01
  • 2016-09-12
  • 2018-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-06
相关资源
最近更新 更多