My search form:
<form method=POST action="{% url 'memes:all' %}" >
{% csrf_token %}
<button type="submit">Search</button>
<input name="search" placeholder="Search" aria-label="Search">
</form>
My List View:
class MemeListView(ListView):
model = Meme
paginate_by = 100
ordering = ['-created_at']
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['now'] = timezone.now()
search_value = self.request.GET.get("search", False)
if search_value:
memes = Meme.objects.filter(name_contains=search_value)
objects = Meme.objects.filter(memes).select_related().distinct().order_by('-created_at')[:10]
context['meme_list'] = objects
context['search'] = search_value
return context
My url:
path('', MemeListView.as_view(), name='all'),
error: "GET / HTTP/1.1" 200 4455
Method Not Allowed (POST): /all/
Method Not Allowed: /all/
[01/Feb/2022 19:23:22] "POST /all/ HTTP/1.1" 405 0
I've done almost identical search functionality in my other crud and it seems to work. What's the issue?
CodePudding user response:
A search is normally done through a GET request, not a POST request: POST requests are usually used to create, update and delete entities.
So your form should have method="GET":
<form method="GET" action="{% url 'memes:all' %}">
…
</form>
Since this is a GET request, it is not necessary to use {% csrf_token %} since cross-site request forgery will not result in creating, updating or removing an entity.
