[Fixed]-Django – dynamic form creation from random db entries

1👍

Random ordering:

questions = Question.objects.all().order_by('?')[:3]

To validate form, it hink, you need restore same queryset with something like:

questions = Question.objects.filter(pk__in=request.POST.getlist('ids'))

and put it to form. Think you need also save same ordering — then you can sort out this list in form.

Update:

You should save state between requests some way. You can add hidden field, add URL parameters, set cookie, save info in user’s profile — is up to your choice. Tipical way is set hidden inputs (generally it’s default django ModelForm behavior).

So on first request, when you show form — you get queryset, sort it by pk for example, put to form and add hidden fields with IDs. When user made POST request with answer — you’ll restore your queryset with this IDs, sort it again same way and put to form to validate.

👤qnub

Leave a comment