Skip to content
Advertisement

How to get Radio Radio Button Data from POST Request Data in an HTML form?

So I’m coding a test platform consisting of Multiple Choice Questions ( MCQs ) in Django. Everything is working fine but somehow I think that the radio button value from my question page is not getting fetch via POST request.

Would appreciate some help!

Here are my models :

from django.db import models
from django.contrib.auth.models import AbstractUser
from .managers import UserManager
from questions.models import Question

class User( AbstractUser ) : 

    email = models.EmailField( verbose_name = 'Email Address', unique = True, null = False )
    username = None

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []
    objects = UserManager()

    def __str__( self ) : return self.get_username()



class Student( models.Model ) :

    user = models.OneToOneField( User, on_delete = models.PROTECT )
    mobile = models.CharField( verbose_name = 'Mobile Number', max_length = 10, unique = True )

    def __str__( self ) : return self.user.get_username()


JAVA='J'
PYTHON='P'
DATABASE='D'
OPERATING_SYSTEM='O'
NETWORKING='N'

SUBJECT_CODE = [
    ( JAVA,'java' ),
    ( PYTHON,'python' ),
    ( DATABASE,'database management' ),
    ( OPERATING_SYSTEM,'operating systems' ),
    ( NETWORKING,'Computer Networks' )
]

class Performance( models.Model ) : 

    global SUBJECT_CODE

    student = models.ForeignKey( Student, on_delete = models.PROTECT )
    question = models.OneToOneField( Question, on_delete = models.PROTECT, null = True )

    score = models.PositiveSmallIntegerField( verbose_name = 'Score', null = True )
    qno = models.PositiveSmallIntegerField( null = True )
    qindex = models.IntegerField( null = True )
    subject_code = models.CharField( verbose_name = 'Subject Code', max_length = 32, choices = SUBJECT_CODE, default = PYTHON, null = False )
    date_appeared = models.DateField( verbose_name = 'Date of Exam', auto_now_add = True, null = False )
from django.db import models



EASY='E'
MEDIUM='M'
HARD='H'
DIFFICULTY_LEVEL=[
    (EASY,'easy'),
    (MEDIUM,'medium'),
    (HARD,'hard')
]

A='A'
B='B'
C='C'
D='D'

CORRECT_ANSWER=[(A,'A'),(B,'B'),(C,'C'),(D,'D')]

JAVA='J'
PYTHON='P'
DATABASE='D'
OPERATING_SYSTEM='O'
NETWORKING='N'



SUBJECT_CODE=[
    (JAVA,'java'),
    (PYTHON,'python'),
    (DATABASE,'database management'),
    (OPERATING_SYSTEM,'operating systems'),
    (NETWORKING,'computer networks')
]



class Question( models.Model ) :

    id=models.AutoField(primary_key=True, null=False)
    subcode=models.CharField(max_length=1, choices=SUBJECT_CODE,default=PYTHON,null=False)
    
    q_string=models.CharField(max_length=512,null=False)
    
    A=models.CharField(max_length=512,null=False)
    B=models.CharField(max_length=512,null=False)
    C=models.CharField(max_length=512)
    D=models.CharField(max_length=512)
    
    correct=models.CharField(max_length=1,choices=CORRECT_ANSWER,default=A,null=False)
    difficulty=models.CharField(max_length=1,choices=DIFFICULTY_LEVEL, default=EASY,null=False) 

    def __str__(self): return self.subcode+" "+str(self.id)

Here are my views :

from django.shortcuts import render, redirect
from profiles.models import User, Student, Performance
from questions.models import Question
from random import randint

subject_codes = {
    'J' : 'Java',
    'P' : 'Python',
    'O' : 'Operating Systems',
    'N' : 'Computer Networks',
    'D' : 'DBMS'
}


def initialise_test_request( request ) : 

    request.student = Student.objects.get( user = request.user )
    if Performance.objects.filter( student = request.student ).exists() is not True : Performance( student = request.student, subject_code = request.subject_code, score = 0, qno = 1 ).save()

    p = Performance.objects.get( student = request.student )
    
    p.subject_code = request.subject_code
    p.qno = 0
    p.score = 0
    p.qindex = randint( 0, 9 )
    p.question = list( Question.objects.filter( subcode = request.subject_code ) )[ p.qindex ]
    p.save()
    
    return request


def instruction( request, subject_code = None ) :

    if subject_code is not None :
        request.subject_code = subject_code
        request.subject = subject_codes[ subject_code ]

    if request.method == 'POST' : 
        
        if 'test_start' in request.POST.keys() : request = initialise_test_request( request )
        return test( request )

    return render( request, 'instructions.html', {} )

def test( request ) :

    try : p = request.p
    except : p = Performance.objects.get( student = Student.objects.get( user = request.user ) )

    if p.qno > 0 :
        if request.POST[ 'option' ] == list( Question.objects.filter( subcode = p.subject_code ) )[ p.qindex ] : 
            p.score = p.score + 1
            p.save()

    if p.qno == 10 : return render( request, 'score.html', { 'score' : p.score } )
    
    p.qno = p.qno + 1
    p.qindex = randint( 0, 9 )
    p.question = list( Question.objects.filter( subcode = p.subject_code ) )[ p.qindex ]
    p.save()

    request.p = p
    return render( request, 'question.html', { 'p' : p } )

Here’s my question page :

{% extends 'common.html' %}

{% load static %}

{% block title %}  TEST {% endblock %}

{% block stylesheet %}

    <script type = "text/javascript">

        function submitAndNext()
        {
            var url = 
        }

    </script>

{% endblock %}



{% block body %}

    <center>

        <div>
            {{ p.qno }}. {{ p.question.q_string }}<br>
        </div>

    </center>

    <br>

    <form action="" method="POST">
        {% csrf_token %}

        <div  style="margin-left: 50px;">

            <input type="radio" id="" name="option" value="A" required>
            <label for="">{{ p.question.A }}</label>
            <br><br>
            
            <input type="radio" id="" name="option" value="B">
            <label for="css">{{ p.question.B }}</label>
            <br><br>
            
            <input type="radio" id="" name="option" value="C">
            <label for="css">{{ p.question.C }}</label>
            <br><br>
            
            <input type="radio" id="" name="option" value="D">
            <label for="css">{{ p.question.D }}</label>
            <br><br><br>
            
            <input type = "hidden" name = "test_started">
            
            <button type="submit" class="btn btn-success rounded-pill">Submit and Next</button>

        </div>

    </form>

    {{ p.score }}

{% endblock %}

I’ve been trying different things so there might be some discrepancies. The score is not getting updated even after clicking the correct Choice.

Advertisement

Answer

When an input box is checked this returns ‘on’. Here is what you need:

in views.py

if request.method =="POST":
    if request.POST.get('the_name', None) == 'on':
        print(request.POST.get('option'))
if request.method =="POST":
    if request.POST.get('the_name2', None) == 'on':
        print(request.POST.get('option'))

in form.html

 <input type="radio" name="the_name"/>

 <input type="checkbox" name="the_name2"/>
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement