1
votes

I have troubles extracting multiple “pk” data from the request.POST Cant get my head around this but I feel like answer should be easy and/or question is dumb(optionally :)).

I have following method in my view:


def post(self, request, *args, **kwargs):
    form = self.get_form()
    if form.is_valid():
        articles = Article.default.filter(id__in=self.request.POST["pk"])
        article_titles = [article.title for article in articles]
        message = article_titles
        messages.add_message(request, messages.SUCCESS, message=message, fail_silently=True)
        return self.form_valid(form)
    else:
        return self.form_invalid(form)


# what is defaul  - default = models.Manager() ,that is equal to objects

Technical it should extract list of PK’s from post data, then filter query-set and get list of articles, then extract their titles and message them to user via messaging framework. Quite straightforward. List of PK is sent to POST data by ModelMultipleChoiceField in form

What I have in POST data:

'csrfmiddlewaretoken'

['DxrzPApYhtxh6ZCqszkvBkywbBTPIaXtpTZTjdJQEFCTqR0vSNXycAcJJnh3jnRC']

'pk'

['34', '32', '25', '24', '22', '11']

'submit'

['']

and surprisingly on this POST data I have following query set:

SELECT ••• FROM "articles_article" WHERE "articles_article"."id" IN (1) ORDER BY "articles_article"."created_at" DESC 

question is :

-why IN(1)?

-how to get list of pk’s in POST data to query-set filter?

when i have singular pk -it works fine. Problem when i have multiple PKs only

1
request.POST.getlist('pk'). - Daniel Roseman
@Daniel Roseman . Daniel, you are as aslways brilliant. Thank you for the help again! - Aleksei Khatkevich

1 Answers

1
votes

You can use getlist() method:

pks = request.POST.getlist('pk')

This should work based on your data but if you ended up using jQuery you probably need to do this:

pks = request.POST.getlist('pk[]')

Also there is the get() method to get only one data. It's a better choice than using direct keys since it wont through an error and instead it will return None or a default value if you set one:

request.POST.get('pk') # returns one pk or None if there is not pk

With default value:

request.POST.get('pk', 0) # returns one pk or 0 if there is not pk

get() and getlist() are the same with the difference that getlist() returns a list.