samedi 25 février 2023

How to randomize key objects in model form and successfully submit in Django

I am trying to save user response (choice) in my Django application out of a set of values in the source model. The user is expected to select one of the many choices presented on the form (as radio buttons). The source model looks like this:

class Emotion(models.Model):
    emote_id = models.AutoField(primary_key=True, ...)
    emote_state_grp = models.ForeignKey(EmotGroup, ...)     # Grouping of Emotion State
    emote_state = models.CharField(max_length=55, ...)

The response/s will be saved in the following model:

class EmoteStateResponse(models.Model):
    emote_state_test = models.AutoField(primary_key=True, ...)
    emote_state_selected = models.ForeignKey(Emotion, ...)

Using a model form I am able to successfully save user choice (i.e. the "emote_state" value) in table "EmoteStateResponse".

However, as the choices might run into a number of instances of field "emote_state" (individual emotions) of table "Emotion", I am trying to select "at random" only a minimal number to display.

To do that, I am trying to randomize the choices in my form that goes like the following:

import random

class EmoteTestForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(EmoteTestForm, self).__init__(*args, **kwargs)
        self.auto_id = True

    class Meta:
        model = EmoteStateResponse
        # ...
        fields = ('emote_state_selected', ...)

    def __init__(self, *args, **kwargs):
        super(EmoteTestForm, self).__init__(*args, **kwargs)

        qs_emot_state = Emotion.objects.all().values_list('emot_state_grp__emotion_grp_id', 'emote_id') # "emotion_grp_id": Key Field model "EmotGroup"
        list_qs_emot_state = list(qs_emot_state)
        rand_emot_state_list = list(dict(random.sample(list_qs_emot_state, len(list_qs_emot_state))).values()) # Random values

    # And finally...
    self.fields['emote_state_selected'].queryset = Emotion.objects.filter(emote_id__in=rand_emot_state_list)

However, on submit I come across the following error:

Select a valid choice. That choice is not one of the available choices.

May somebody please point out what I am doing wrong? How may I display the choice field "emote_state_selected" with random values from table "Emotion" and save it?




Aucun commentaire:

Enregistrer un commentaire