Представления получают значения из шаблона перед выполнением метода post

Я создаю игру odd one out. В основном пользователю предлагаются четыре картинки, одна из которых нечетная, когда пользователь выбирает нечетную картинку, счет увеличивается на 1. Проблема в том, что я отправляю 4 картинки с одной нечетной картинкой в шаблон. Шаблон выбирает одинаковые идентификаторы 3 картинок, но идентификатор нечетной картинки случайный (я хочу, чтобы идентификатор нечетной картинки был таким же, как и идентификатор четной картинки).

view.py is:

def odd_one_out_game(request):
    # Get a random country
    country = random.choice(Country.objects.all())
    print("Selected country:", country)

    # Get three random pictures from the selected country
    pictures = list(Picture.objects.filter(country=country).order_by('?')[:3])
    print("Pictures from selected country:", pictures)

    # Get one random picture from a different country
    other_country = random.choice(Country.objects.exclude(pk=country.pk))
    other_picture = random.choice(Picture.objects.filter(country=other_country))
    other_picture_id = other_picture.id
    print(other_picture_id)
    print("Random picture from other country:", other_picture)

    # Add the other picture to the list of pictures
    pictures.append(other_picture)
    print("All pictures:", pictures)

    # Shuffle the pictures to mix up the order
    random.shuffle(pictures)
    print("Shuffled pictures:", pictures)
    #get the ids of the pictures
    picture_ids = [picture.id for picture in pictures]
    print("Picture IDs:", picture_ids)

    odd_score = request.session.get('odd_score', 0)
    total_guesses = request.session.get('total_guesses', 0)
    message = ""  # Initialize message variable
    print("Initial score:", odd_score, "Initial total guesses:", total_guesses)

    if request.method == 'POST':
        selected_picture_id = request.POST.get('odd_one_out')
        selected_picture = Picture.objects.get(id=selected_picture_id)
        total_guesses += 1
        print("Selected picture ID:", selected_picture_id)
        print("Selected picture:", selected_picture)
        print(selected_picture.country, other_country)
        if selected_picture.country != other_country:
            # Increase score by 1 if the selected picture is the odd one out
            odd_score += 1
            message = "Congratulations! You guessed the right answer."
            print("Score increased:", odd_score)
        else:
            message = "Sorry! You guessed the wrong answer."
            print("Score unchanged:", odd_score)

        # Update session with the new score
        request.session['odd_score'] = odd_score
        request.session['total_guesses'] = total_guesses
        print("Updated score:", odd_score, "Updated total guesses:", total_guesses)

    context = {
        'country': country,
        'pictures': pictures,
        'score': odd_score,
        'total_guesses': total_guesses,
        'message': message,
    }
    return render(request, 'odd_one_out_game.html', context)

odd_one_out_game.html это:

 <form method="post">
        {% csrf_token %}
        {% for picture in pictures %}
            <input type="radio" name="odd_one_out" id="{{ picture.id }}" value="{{ picture.id }}">
            <label for="{{ picture.id }}"><img src="{{ picture.image.url }}" alt="{{ country.name }}"></label>
        {% endfor %}
        <button type="submit">Submit</button>
    </form>

что он делает сейчас, допустим, picture_ids =[1,3,4,6] #lets say 6 is the id of odd picture .When user select the odd picture in template selected_picture_id should 6 but it takes the random ids . when selected that odd picture in template selected_picture_id should be 6 but it selects random ids. Как мне решить эту проблему.

В selected_picture_id он выбирает случайный id еще до отправки выбора пользователя из шаблона. Как мне решить эту проблему.

Вернуться на верх