Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
341 views
in Technique[技术] by (71.8m points)

django - Page not found (404) error while searching through search page Raised by: blog.views.blogpost

i am unable to search and get 404 error same problem occur in sitemap views for creating static xml file, it does not return the url for static file and now have this problem with search as it is unable to find search .html gives this Page not found (404) error while searching through search page Raised by: blog.views.blogpost error.

Search_Form

<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>

Search 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)

url.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")
]

My 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 %}

Project urls.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)

models.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
question from:https://stackoverflow.com/questions/65643929/page-not-found-404-error-while-searching-through-search-page-raised-by-blog-v

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try rewriting your form to something like this:

<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> 

And your search view like this:

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)

UPDATE

So, after going through your GitHub repository I saw a couple of issues, first off there is no urls.py or views.py in your blog app, its either not added in the repo or just doesn't exist, which would explain the router not finding any paths for your views, hovewer there is one in the question so I'm not sure whats the issue here, please check again so that the file is in the right directory in the root of your blog app folder.

Second off in your main project directory there are files called urls.py, views.py and forms.py, that shouldn't be the case, instead create a seperate app and place them there.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...