0

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
SLDem
  • 2,065
  • 1
  • 8
  • 28
KhAliq KHan
  • 43
  • 1
  • 6

1 Answers1

0

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.

SLDem
  • 2,065
  • 1
  • 8
  • 28
  • got an error like the one in Sitemap xml, `NoReverseMatch at /blog/ Reverse for 'search' not found. 'search' is not a valid view function or pattern name.` – KhAliq KHan Jan 09 '21 at 15:51
  • try removing `namespace='blog'` in your main `urls.py` file where the path for blog urls is defined – SLDem Jan 09 '21 at 15:54
  • Not working, same error should it suppose to work with get? shows error at `
    ` line
    – KhAliq KHan Jan 09 '21 at 16:01
  • is your `contact` view working as intended? – SLDem Jan 09 '21 at 16:03
  • in your main urls instead of this `path('blog/', include('blog.urls', namespace='blog')),` write this: `path('blog/', include('blog.urls')),` – SLDem Jan 09 '21 at 16:08
  • also check if you imported the correct views file, do you perhaps have a github repo of this project? – SLDem Jan 09 '21 at 16:10
  • No unfortunately i don't have it yet – KhAliq KHan Jan 09 '21 at 16:44
  • create it and share the link here, I don't think we can trace the error with current information here – SLDem Jan 09 '21 at 16:45
  • Ok, sure i will send link in a while – KhAliq KHan Jan 09 '21 at 16:56
  • be back in about 1 hr mate – SLDem Jan 09 '21 at 17:30
  • Im looking at your repo but I dont see the main project folder ( the one with `settings.py` ) Did you perhaps forget to include it or accidentally added it to `gitignore`? – SLDem Jan 09 '21 at 19:04
  • No i added all but in hurry, i did no whats going on. wait i will moved again, i m really sorry these app are part of mywebside (its my main project) – KhAliq KHan Jan 10 '21 at 08:14
  • sorted out, kindly check https://github.com/FazliKhaliq/blog.git – KhAliq KHan Jan 10 '21 at 08:29
  • really appreciate your time, i added it before but dont know why its not their, i added again, plz see – KhAliq KHan Jan 10 '21 at 11:19
  • in your blog `urls.py` you have this line `from .import views` it should be `from . import views` with a spacebar after the `.` – SLDem Jan 10 '21 at 11:30
  • sorted but still get same error mentioned with above `POST` method "NoReverseMatch at /blog/ Reverse for 'search' not found. 'search' is not a valid view function or pattern name." – KhAliq KHan Jan 10 '21 at 11:43
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/227108/discussion-between-sldem-and-khaliq-khan). – SLDem Jan 10 '21 at 11:44