Issue
This fails for me. It gives me a "405 Method not allowed error." It is referring to the POST method yes? How does one check for a POST? Or should I do something totally differently?
class StuffList(ListView):
template_name = "list.html"
queryset = Stuff.objects.all().order_by('-whatever')
context_object_name = 'stuff'
def get(self, request, *args, **kwargs):
if request.POST:
q = request.POST.get('q')
stuff = Stuff.objects.filter(user__icontains=stuff)
return render(request, self.template_name, {'stuff': stuff, 'q': q })
In my form, I have the token placed right inside the form action, like so:
<form action="/stuff/" method="post" name="q">
{% csrf_token %}
Solution
It's because you're making a POST request but you've only defined a GET method. If you add a POST method, it should do the trick :
def post(self, request, *args, **kwargs):
stuff = request.POST.get('q')
stuff = self.get_queryset().filter(user__icontains=stuff)
return render(request, self.template_name, {'stuff': stuff, 'q': q })
However, if you're only filtering the list, using the get is a correct solution, in this case, you have to change your form tag method="post"
to method="get"
and make you're GET method something like this:
def get(self, request, *args, **kwargs):
stuff = self.get_queryset()
if request.GET.get('q'):
q = request.GET.get('q')
stuff = stuff.filter(user__icontains=q)
return render(request, self.template_name, {'stuff': stuff, 'q': q })
Maybe you should look at the Django forms which can do data validation, form generation and much more.
https://docs.djangoproject.com/fr/1.8/topics/forms/
Answered By - Antoine Fontaine
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.