0

我无法搜索并获得 404 错误同样的问题出现在创建静态 xml 文件的站点地图视图中,它不返回静态文件的 url,现在搜索出现此问题,因为它无法找到搜索 .html 给此页面不通过搜索页面搜索时发现 (404) 错误引发者:blog.views.blogpost 错误。

搜索_表格

<form method='GET' action="/blog/search/" class="form-inline my-2 my-lg-0">
    <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" name="search" id="search">
    <button class="btn btn-outline-success mx-2 my-1 my-sm-0" type="submit">Search</button>
</form>

搜索views.py

def search(request):
    myposts = Blogpost.objects.all()
    query = request.GET['search']
    if len(query)>78:
        myposts = Blogpost.objects.none()
    else:
        post_title = Blogpost.objects.filter(Q(title__icontains=query))
        posts_content = Blogpost.objects.filter(Q(content__icontains=query))
        posts_slug = Blogpost.objects.filter(Q(slug__icontains=query))
        myposts = post_title | posts_content | posts_slug
    if myposts.count() == 0:
        messages.warning(request, "No search results found. Please enter again.")
    context = {'myposts': myposts,'query':query}
    return render(request, 'blog/search.html', context)

网址.py


urlpatterns = [
    path('', views.index, name='bloglist'),
    path('<slug:post>/', views.blogpost, name='blogpost'),
    path("contact/", views.contact, name="contact"),
    path("search/", views.search, name="search")
]

我的search.html

{% block body %}

<div class="container mt-3">
    <h5> <p> Search Results:</p> </h5>
        {% if myposts|length < 1 %}
        Your Search -<b> {{query}} </b>- did not match any documents please try again. <br>
            <br> Suggestions:
            <ul>
                <li>Make sure that all words are spelled correctly.</li>
                <li>Try more general keywords.</li>
                <li>Try different keywords.</li>
            </ul>
        {% endif %}
        <div class="container mt-3">
            <div class="row my-2">
        
                {% for post in myposts %}
                <div class="col-md-6">
                    <div class="row no-gutters border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-relative">
                        <div class="col p-4 d-flex flex-column position-static">
                            <h3 class="mb-0"><a href="{{ post.get_absolute_url }}">{{post.title}}</a></h3>
                            <div class="mb-1 text-muted"></div>
                            <strong class="d-inline-block mb-2 text-primary"><a>{{post.author}} | {{post.created_on}}</a></strong>
                            <p class="card-text mb-auto">{{post.content|safe}}</p>
                            <a href="{{ post.get_absolute_url }}" class="stretched-link">Continue reading</a>
                        </div>
                        <div class="col-auto d-none d-lg-block">
                            <img src="/media/{{post.thumbnail}}" class="bd-placeholder-img" width="200" height="250" aria-label="Placeholder: Thumbnail">
                            <title>Placeholder</title></img>
                        </div>
                    </div>
                </div>
                {% if forloop.counter|divisibleby:2%}
            </div>
            <div class="row my-2">
                {% endif %}
                {% endfor %}</div>
        </div>
</div>

{% endblock %}

项目网址.py

from django.contrib.sitemaps.views import sitemap

from blog.sitemaps import StaticViewsSitemap
from blog.sitemaps import BlogSitemap

sitemaps ={
    'blogpost': BlogSitemap(),
    'static': StaticViewsSitemap(),
}

urlpatterns = [
    path('admin/', admin.site.urls),
    path('shop/', include('shop.urls')),
    path('blog/', include('blog.urls', namespace='blog')),
    path('', views.index),
    path('register/', views.registerPage),
    path('login/', views.loginPage),
    path('logout/', views.logoutUser),
    path('sitemap.xml/', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

模型.py

class Blogpost(models.Model):
    STATUS_CHOICES= ( ('0', 'Draft'), ('1', 'Publish'),)


    post_id = models.AutoField(primary_key= True)
    title = models.CharField(max_length=50, unique=True)
    slug = models.SlugField(max_length=50, unique=True)
    content = models.TextField(max_length=5000, default="")
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    thumbnail = models.ImageField(upload_to='shop/images', default="")
    created_on = models.DateTimeField(default=timezone.now)
    categories = models.ManyToManyField(Category)
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft')
    objects = models.Manager()
    featured = models.BooleanField()

    def get_absolute_url(self):
        return reverse('blog:blogpost',
        args=[self.slug])

    class Meta:
        ordering = ('-created_on',)

    def __str__(self):
        return self.title
4

1 回答 1

0

尝试将您的表单重写为以下内容:

<form method="POST" action="{% url 'search' %}" class="form-inline my-2 my-lg-0">         
    <input class="form-control mr-sm-2" type="search" placeholder="Search" arialabel="Search" name="search" id="search">
    <button class="btn btn-outline-success mx-2 my-1 my-sm-0" type="submit">Search</button>       
</form> 

你的搜索视图是这样的:

def search(request):
    myposts = Blogpost.objects.all()
    if request.method == 'POST'
        query = request.POST.get('search')
        if len(query) > 78:
            myposts = Blogpost.objects.none()
        else:
            myposts = Blogpost.objects.filter(Q(title__icontains=query))
            myposts = Blogpost.objects.filter(Q(content__icontains=query))
            myposts = Blogpost.objects.filter(Q(slug__icontains=query))
        if myposts.count() == 0:
            messages.warning(request, "No search results found. Please enter again.")
        context = {'myposts': myposts, 'query': query}
    return render(request, 'blog/search.html', context)

更新

因此,在浏览了您的GitHub存储库后,我看到了几个问题,首先是您的应用程序中没有urls.py或没有,它要么没有添加到 repo 中,要么就是不存在,这可以解释路由器找不到您的任何路径意见,但是问题中有一个,所以我不确定这里的问题是什么,请再次检查,以便该文件位于您的应用程序文件夹的根目录中的正确目录中。views.pyblogblog

其次,在您的主项目目录中有名为urls.py,views.py和的文件forms.py,这不应该是这种情况,而是创建一个单独的应用程序并将它们放在那里。

于 2021-01-09T15:39:26.310 回答