[Answer]-Django forms processing dynamic field labels

1👍

✅

Classes.objects.filter(class_name=field)

returns a queryset, but you want a Classes instance.

Classes.objects.get(class_name=field)

will do that.

0👍

I’ve done this previously by creating an array attached to the form with the dynamically generated fields and then just iterate over that.

Alternatively you could put the objects.get(…) in a try/except block:

try:
    Classes.objects.get(class_name=field)
except:
    pass
else:
    newentry = Entry(
        athlete = athlete,
        event = event,
        athlete_class = Classes.objects.filter(class_name=field)
        )

The reason why the if statement doesn’t work is that the following block is not indented correctly. This should work also (note the parenthesis after the count):

if Classes.objects.get(class_name=field).count() > 0:
    newentry = Entry(
        athlete = athlete,
        event = event,
        athlete_class = Classes.objects.filter(class_name=field)
        )

Leave a comment