如何修复 Django 中的搜索栏错误?

How can I fix this searchbar error in django?

我正在尝试在 python 中的博客中创建搜索栏,但收到以下错误:'article-detail' 的反转未找到参数 '('',)' .尝试了 1 种模式:['app1/article/(?P[0-9]+)$'] 我不确定为什么,所以这是代码,以便你们可以看到这里发生了什么:

回溯

Traceback (most recent call last):
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\snin2\Desktop\basura\lapagina\app1\views.py", line 187, in searchbar
    return render(request, 'app1/search.html', {'query':query, 'results':results})
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\shortcuts.py", line 19, in render      
    content = loader.render_to_string(template_name, context, request, using=using)
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\loader.py", line 62, in render_to_string
    return template.render(context, request)
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\backends\django.py", line 61, 
in render
    return self.template.render(context)
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 170, in render 
    return self._render(context)
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 162, in _render
    return self.nodelist.render(context)
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 938, in render 
    bit = node.render_annotated(context)
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 905, in render_annotated
    return self.render(context)
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\loader_tags.py", line 150, in 
render
    return compiled_parent._render(context)
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 162, in _render
    return self.nodelist.render(context)
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 938, in render 
    bit = node.render_annotated(context)
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 905, in render_annotated
    return self.render(context)
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\loader_tags.py", line 62, in render
    result = block.nodelist.render(context)
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 938, in render 
    bit = node.render_annotated(context)
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 905, in render_annotated
    return self.render(context)
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\defaulttags.py", line 312, in 
render
    return nodelist.render(context)
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 938, in render 
    bit = node.render_annotated(context)
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 905, in render_annotated
    return self.render(context)
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\defaulttags.py", line 211, in 
render
    nodelist.append(node.render_annotated(context))
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 905, in render_annotated
    return self.render(context)
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\defaulttags.py", line 446, in 
render
    url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\urls\base.py", line 87, in reverse     
    return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\urls\resolvers.py", line 685, in _reverse_with_prefix
    raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'article-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['app1/article/(?P<pk>[0-9]+)$']

Models.py

class StockNames(models.Model):
    name = models.CharField(max_length=255)
    symbol = models.CharField(max_length=255)

    def __str__(self):
        return self.symbol

        
    

class Post(models.Model):
    title = models.CharField(max_length= 255)
    header_image = models.ImageField(null = True, blank = True, upload_to = 'images/')
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    body = RichTextField(blank = True, null = True)
    #body = models.TextField()
    post_date = models.DateField(auto_now_add=True)
    category = models.CharField(max_length=255, default='coding')
    snippet = models.CharField(max_length=255)
    likes = models.ManyToManyField(User, related_name = 'blog_posts')
    stock = models.ForeignKey(StockNames, null=True, on_delete = models.CASCADE)

    def total_likes(self):
        return self.likes.count()

    def __str__(self):
        return self.title + ' | ' + str(self.author)
    
    def get_absolute_url(self):
        return reverse('app1:article-detail', args=(self.id,))

Views.py

def searchbar(request):
    query = None
    results = []
    if request.method == 'GET':
        query=request.GET.get("search")
        results= Post.objects.filter(Q(title__icontains=query) | Q(stock__symbol__icontains=query))
    return render(request, 'app1/search.html', {'query':query, 'results':results})
    

search.html

{% extends "app1/base.html" %}
    {% block body_block %}
    <div class="container">
        <h1>Search Page</h1>
        {% if query %}
        <h3>{% with results.count as total_results %}
            Found {{total_results}} total results
            {% endwith %}
        </h3>
        {% for x in results %}
        <li><a href="{% url 'app1:article-detail' post.pk %}">{{sym}}</a> -
            {{post.author}} - <small>{{post.post_date}}</small> - 
            {% if user.is_authenticated %}
            <small><a href="{% url 'app1:updatepost' post.pk %}">Edit</a></small><small>
            <a href="{% url 'app1:deletepost' post.pk %}">- Delete</a>  
            </small></li>
            {% endif %}
        </div>
    {% empty %}
    <h1>There's no query</h1>
    {% endfor %}
    {% else %}
    <h3>Error in your query</h3>
    {% endif %}





    {% endblock %}

base.html(特别是搜索输入)

<form action="{% url 'app1:searchbar' %}" class="form-inline my-2 my-lg-0" method="GET">
   <input name="search" class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search", name='search'>
   <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>

urls.py(最后一个)

app_name = 'app1'

urlpatterns = [
    path('post/', PostView.as_view(), name = 'Post'),
    path('article/<int:pk>', ArticleDetailView.as_view(), name = 'article-detail'),
    path('add_post/<str:sym>',AddPostView.as_view(), name='addpost'),
    path('update_post/<int:pk>', UpdatePostView.as_view(), name = 'updatepost'),
    path('delete_post/<int:pk>', DeletePostView.as_view(), name = 'deletepost'),
    path('add_category/', AddCategoryView.as_view(), name = 'add_category'),
    path('category/<str:cats>/', views.CategoryView, name = 'category'),
    path('category-list/', views.CategoryListView, name ='category-list'),
    path('like/<int:pk>/', views.LikeView, name = 'like_post'),
    path('my_posts/', views.MyPostsView.as_view(), name = 'my_posts'),
    path('article/<int:pk>/add_comment/', AddCommentView.as_view(), name = 'add_comment'),
    path('update_comment/<int:pk>', UpdateCommentView.as_view(), name = 'updatecomment'),
    path('delete_comment/<int:pk>', DeleteCommentView.as_view(), name = 'deletecomment'),
    path('stock/<str:sym>/', views.StockView, name = 'stock'),
    path('searchbar/', views.searchbar, name = 'searchbar'),

]

提前致谢!

<a href="{% url 'app1:article-detail' post.pk %}">

这里 'post' 不是 declared/contexted/retrieved 来自 db.thats 为什么你会收到错误。

    {% for post in results %}
    <li><a href="{% url 'app1:article-detail' post.pk %}">{{sym}}</a> -
      {% if user.is_authenticated %}
    <small><a href="{% url 'app1:updatepost' post.pk %}">Edit</a></small><small>
    <a href="{% url 'app1:deletepost' post.pk %}">- Delete</a>  
    </small></li>
    {% endif %}