list the unicode array separately in template in python - python

The Following is my view.py
def UpdatePage(request):
templatevar = {}
user_name = request.session['login_user_email']
update_form = Update_Page()
if user_name:
home_page_form = Home_Page
templatevar['varobj']=models.ProfileDetail.objects.filter(email=user_name)
if request.method=='POST':
update_name=request.POST['name']
update_age=request.POST['age']
update_gender=request.POST.get('gender')
update_interested_in=request.POST.getlist('interested_in')
for i in update_interested_in:
print i
update_dob=request.POST.get('dob')
update_country=request.POST['country']
update_about_you=request.POST['about_you']
update_profile_detail=models.ProfileDetail.objects.filter(email=user_name).update(name=update_name,age=update_age,gender=update_gender,
interested_in=update_interested_in,dob=update_dob,country=update_country,about_you=update_about_you)
if update_profile_detail:
details_updated="Your Profile Details are Updated"
return HttpResponseRedirect('homepage',{'details_updated':details_updated})
return render(request,'update.html',{'user_name':user_name,'update_form':update_form,'templatevar':templatevar})
The Following is my Template View
<html>
<head>
<title>Update Here</title>
</head>
<body style="text-align:center">
<h3 style="text-align:right"><div>Home</div><div>Log Out</div></h3>
{{user_name}}
<h3>Update Here</h3>
<!--{{update_form.as_p}}-->
{% for all in templatevar.varobj %}
<p>Age:{{all.age}}<br></p>
<p>Gender:{{all.gender}}<br></p>
<p>Interested In:{{all.interested_in}}<br></p>
{%for i in all.interested_in%}
{{i}}
{%endfor%}
<p>DOB:{{all.dob}}<br></p>
<p>Country:{{all.country}}<br></p>
<p>About You:{{all.about_you}}<br></p>
{% endfor %}
<form action="" method="post">
{% csrf_token %}
{% for all in templatevar.varobj %}
<p><label for="id_name">People Call You As:</label> <input id="id_name" name="name" type="text" value="{{all.name}}" /></p>
<p><label for="id_email">Your Email:</label> <input id="id_email" name="email" type="email" value="{{user_name}}" readonly /></p>
<p><label for="id_age">Age:</label> <input id="id_age" name="age" type="number"value="{{all.age}}" /></p>
<p><label for="id_gender_0">Gender:</label> <ul id="id_gender">
<li><label for="id_gender_0"><input id="id_gender_0" name="gender" type="radio" value="Male" {% if all.gender == "Male" %}checked="checked"{% endif %} /> Male</label></li>
<li><label for="id_gender_1"><input id="id_gender_1" name="gender" type="radio" value="Female" {% if all.gender == "Female" %}checked="checked"{% endif %} /> Female</label></li>
<p><label for="id_interested_in_0">Interested In:</label>
<ul id="id_interested_in">
<li><label for="id_interested_in_0">
<input id="id_interested_in_0" name="interested_in" type="checkbox" value="Sports" {% if all.interested_in == "Sports" %}checked="checked"{% endif %}/> Sports</label></li>
<li><label for="id_interested_in_1"><input id="id_interested_in_1" name="interested_in" type="checkbox" value="Music" {% if all.interested_in == "Music" %}checked="checked"{% endif %} /> Music</label></li>
<li><label for="id_interested_in_2"><input id="id_interested_in_2" name="interested_in" type="checkbox" value="Gardening" {% if all.interested == "Gardening" %}checked="checked"{% endif %}/> Gardening</label></li>
<p><label for="id_dob">Date Of Birth:</label> <input id="id_dob" name="dob" type="text" value="{{all.dob}}" placeholder = "YYYY-MM-DD" /></p>
<p><label for="id_country">Your From:</label> <select id="id_country" maxlength="3" name="country">
<option value="India">India</option>
<option value="Australia">Australia</option>
<option value="America">America</option>
</select></p>
<p><label for="id_about_you">About You:</label> <textarea cols="40" id="id_about_you" name="about_you" rows="10" value="">{{all.about_you}}
</textarea></p>
{% endfor %}
<input type="submit" value="Update" />
</form>
</body>
</html>
The following is my model view:
class ProfileDetail(models.Model):
name = models.CharField(max_length=100,null=True)
email = models.EmailField(max_length=50,unique=True,null=True)
age = models.IntegerField(max_length=3,null=True)
gender = models.CharField(max_length=10,null=True)
interested_in = models.CharField(max_length=10,null=True)
dob = models.DateField(null=True)
country = models.CharField(max_length=25,null=True)
about_you = models.CharField(max_length=200,null=True)
def __str__(self):
return self.interested_in
I need to display the check box value separately as
Sports
Music
Gardening
and not the following
Interested In:[u'Sports', u'Music', u'Gardening']
How to display separately and check the values

Your error is that you are trying to store a list into a char field, that's why you are seeing the repr of the list.
First, in your view, change the line:
update_interested_in=request.POST.getlist('interested_in')
to
update_interested_in = ','.join(request.POST.getlist('interested_in'))
Then add a method to your model.py that splits the string:
class ProfileDetail(models.Model):
...
def interested_in_list(self):
return self.interested_in.split(',')
You can then use the join template filter:
{{ all.interested_in_list|join:"<br/>"|safe }}
If you have to construct the checkboxes yourself, you can use something like:
{% for interest in all.interested_in_list %}
<input name="interested_in" type="checkbox" value="{{ interest }}"> {{ interest }}
{% endfor %}

Related

In Django I have written the html to edit a form this during retrieving the values from database by value={{ i.full_name}} it shows only first name

enter image description hereenter image description here This is my edit.html code and during retrieving the values from database and showing in this html form it shows only first name when I am writing value={{ i.full_name}} why not the full name during filling up form I have included the full name I think there is some mistake after white space it cant read the characters anymore For example when filling the form I have written Rowan Atkinson but during editing the form I am getting only Rowan. You can see in the image which I have attached.
<section class="site-section">
<div class="container">
<div class="row">
<div class="col-lg-12 mb-5">
<h2 class="mb-4 text-center">Update Candidate Details</h2>
<form method="POST" action="/update/ {{i.id}}/" enctype="multipart/form-data" class="p-4 border rounded" onsubmit="myFunction()" >
{% csrf_token %}
{% comment %} <input type="hidden" name="csrfmiddlewaretoken" value="UabxqpD8HGPOu1ZSFnIHAPbMtRgWBAnVHEs8bLDx0HnxN6uhG3LyYvZShvcx1ekn"> {% endcomment %}
<div class="row form-group">
<div class="col-md-12 mb-3 mb-md-0">
<label class="text-black" for="full_name">Full Name :</label>
<input type="text" class="form-control" value ={{ i.full_name}} name="full_name" id="id_full_name" placeholder="Enter First Name">
</div>
</div>
<div class="row form-group">
<div class="col-md-12 mb-3 mb-md-0">
<label class="text-black" for="recruiter_name">Recruiter Name :</label>
<input type="text" class="form-control" value ={{ i.recruiter_name }} name="recruiter_name" id="id_recruiter_name" placeholder="Enter Recruiter Name">
</div>
</div>
{% comment %} <div class="row form-group">
<div class="col-md-12 mb-3 mb-md-0">
<label class="text-black" for="id_last_name">Last Name :</label>
<input type="text" class="form-control" name="last_name" id="id_last_name" placeholder="Enter Last Name">
</div>
</div> {% endcomment %}
<div class="row form-group">
<div class="col-md-12 mb-3 mb-md-0">
<label class="text-black" for="email">Email :</label>
<input type="email" class="form-control" value ={{i.email }} name="email" id="id_email" placeholder="Enter Email">
</div>
</div>
<div class="row form-group">
<div class="col-md-12 mb-3 mb-md-0">
<label class="text-black" for="noticeperiod">Notice Period (in Days) :</label>
<input type="text" class="form-control" value ={{i.noticeperiod }} name="noticeperiod" id="notice_period" placeholder="Notice Period">
</div>
</div>
<div class="row form-group">
<div class="col-md-12 mb-3 mb-md-0">
<label class="text-black" for="preferredlocation">Current Location :</label>
<input type="text" class="form-control" value ={{i.preferredlocation}} name="preferredlocation" id="preferred_location" placeholder="Enter Current Location">
</div>
</div>
<div class="row form-group">
<div class="col-md-12 mb-3 mb-md-0">
<label class="text-black" for="expectedlocation">Expected Location :</label>
<input type="text" class="form-control" value ={{i.expectedlocation}} name="expectedlocation" id="expected_location" placeholder="Enter Multiple Locations seperated by comma">
</div>
</div>
<div class="row form-group">
<div class="col-md-12 mb-3 mb-md-0">
<label class="text-black" for="currentctc">Current CTC (Per Annum) :</label>
<input type="text" class="form-control" value ={{i.currentctc }} name="currentctc" id="current_ctc" placeholder="Current CTC">
</div>
</div>
<div class="row form-group">
<div class="col-md-12 mb-3 mb-md-0">
<label class="text-black" for="expectedctc">Expected CTC (Per Annum) : </label>
<input type="text" class="form-control" value ={{i.expectedctc }} name="expectedctc" id="expected_ctc" placeholder="Expected CTC">
</div>
</div>
<div class="row form-group">
<div class="col-md-12 mb-3 mb-md-0">
<label class="text-black" for="status">Status : </label> </br>
<select name="status" id="status" class="form-control" value ={{i.status }}>
<option value="CV Received">CV Received</option>
<option value="Submitted to Client">Submitted to Client</option>
<option value="Rejected">Rejected</option>
<option value="Offered">Offered</option>
<option value="Joined">Joined</option>
<option value="Closed">Closed</option>
<option value="Payment Received">Payment Received</option>
</select>
{% comment %} <input type="text" class="form-control" name="status" id="status1" placeholder="Enter Application Status"> {% endcomment %}
</div>
</div>
<div class="row form-group">
<div class="col-md-12 mb-3 mb-md-0">
<label class="text-black" >Upload CV</label></br>
<input type="file" name="cv" id="cv1" value ={{ i.cv}} >
</div>
</div>
<div class="row form-group mb-4">
<div class="col-md-12 mb-3 mb-md-0">
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" id="male" value={{i.gender}}>
<label class="form-check-label" for="male">Male</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" id="female" value={{i.gender}}>
<label class="form-check-label" for="female">Female</label>
</div>
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<input type="submit" value="Update" id ="submit" class="btn px-4 btn-primary text-white">
{% comment %} Sign Up {% endcomment %}
</div>
</div>
This is my views.py
#delete
def delete(request, id):
i = ApplyForm.objects.get(id = id)
i.delete()
return redirect('account:dboard')
#edit
def edit(request, id):
i = ApplyForm.objects.get(id = id)
context = {
'i' : i
}
return render(request, 'account/edit.html', context)
#update
def update(request, id):
i = ApplyForm.objects.get(id = id)
i.full_name = request.POST['full_name']
i.email = request.POST['email']
i.noticeperiod = request.POST['noticeperiod']
i.preferredlocation = request.POST['preferredlocation']
i.expectedlocation = request.POST['expectedlocation']
i.currentctc = request.POST['currentctc']
i.expectedctc= request.POST['expectedctc']
i.recruiter_name = request.POST['recruiter_name']
i.status = request.POST['status']
i.gender = request.POST['gender']
i.cv = request.FILES['cv']
i.save()
return redirect('account:dboard')
And my models.py
class ApplyForm(models.Model):
full_name = models.CharField(max_length=300)
email = models.EmailField(max_length=300)
noticeperiod = models.CharField(max_length = 300)
preferredlocation = models.CharField(max_length=300)
expectedlocation = models.CharField(max_length=300)
currentctc = models.CharField(max_length=300)
expectedctc = models.CharField(max_length=300)
recruiter_name = models.CharField(max_length = 300, null=True)
status = models.CharField(max_length = 300, null=True, choices= CATEGORY_CHOICES )
gender = models.CharField(max_length=10, choices=GENDER_CHOICES)
cv = models.FileField(upload_to='')
That means after white space I am not able to retrieve the characters I dont know what to do what's happening also I am not getting data for choice field and file field i.e. Upload Cv , gender , status fields I am getting data from the other fields but after space of any text I am not getting the characters I have attached an image for this.
If your question is still actual you can solve it:
For 'Status' field:
<select name="status" id="status" class="form-control">
<option value="CV Received"{% if i.status == 'CV Received' %} selected {% endif %}>CV Received</option>
<option value="Submitted to Client"{% if i.status == 'Submitted to Client' %} selected {% endif %}>Submitted to Client</option>
<option value="Rejected"{% if i.status == 'Rejected' %} selected {% endif %}>Rejected</option>
<option value="Offered"{% if i.status == 'Offered' %} selected {% endif %}>Offered</option>
<option value="Joined"{% if i.status == 'Joined' %} selected {% endif %}>Joined</option>
<option value="Closed"{% if i.status == 'Closed' %} selected {% endif %}>Closed</option>
<option value="Payment Received"{% if i.status == 'Payment Received' %} selected {% endif %}>Payment Received</option>
</select>
For 'Gender' field:
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" id="male" value="male" {% if i.gender == 'male' %} checked {% endif %}>
<label class="form-check-label" for="male">Male</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" id="female" value="female" {% if i.gender == 'female' %} checked {% endif %}>
<label class="form-check-label" for="female">Female</label>
</div>
For uploaded CV:
<div class="col-md-12 mb-3 mb-md-0">
{% if i.cv %}
{{ i.cv }}
{% endif %}
<label class="text-black" >Upload CV</label></br>
<input type="file" name="cv" id="cv1">
</div>

Django return none when y try to save in vars by POST method

I'm trying to save the data from a form by POST method. When i try to save in vars at views.py it put inside none
here i show important parts of my code:
add.html:
<form method="POST">
{% csrf_token %}
<h5>AÑADIR PEDIDO</h5>
<div class="form-group">
<label for="cliente">Nombre del Cliente</label>
<input type="text" class="form-control" id="cliente" placeholder="pepito" />
</div>
<div class="form-group">
<label for="producto">Codigo del Producto</label>
<select class="form-control" id="producto">
{% for cantidades in cantidad_pedido %}
<option value="{{cantidades.Cproducto}}">
{{cantidades.Cproducto}}
</option>
{% endfor %}
</select>
</div>
<div class="form-group">
<label for="cantidad">Cantidad de dicho producto</label>
<input type="number" class="form-control" id="cantidad" placeholder="cantidad" />
</div>
<button type="submit" class="btn btn-dark" style="margin-bottom: 1%;">Añadir!</button>
</form>
models.py:
class Stock(models.Model):
Cproducto = models.CharField(max_length=50, primary_key=True)
cantidad = models.IntegerField()
class Pedido(models.Model):
Cpedido = models.CharField(max_length=50, primary_key=True)
Ccliente = models.CharField(max_length=50)
FechaPedido = models.DateField(default=datetime.now)
class detallePedido(models.Model):
Cpedido = models.ForeignKey(Pedido, on_delete=models.CASCADE)
Cproducto = models.ForeignKey(Stock, on_delete=models.CASCADE)
Cantidad = models.IntegerField()
views.py :
def add(request):
cantidad_pedido = Stock.objects.all()
if request.POST:
client = request.POST.get('cliente')
producto = request.POST.get('producto')
cantidad = request.POST.get('cantidad')
stock_producto = Stock.objects.get(Cproducto=producto)
if(cantidad > stock_producto.cantidad):
messages.error(request, 'Error, la cantidad es mayor')
return render(request, 'add.html', {'cantidad_pedido': cantidad_pedido})
and here one picture of the vars:
You are missing as mention above in comment
I think you are making request with id attribute but instead of id you need to do with name attribute like this
form method="POST">
{% csrf_token %}
<h5>AÑADIR PEDIDO</h5>
<div class="form-group">
<label for="cliente">Nombre del Cliente</label>
<input type="text" class="form-control" name="cliente" placeholder="pepito" />
</div>
<div class="form-group">
<label for="producto">Codigo del Producto</label>
<select class="form-control" name="producto">
{% for cantidades in cantidad_pedido %}
<option value="{{cantidades.Cproducto}}">
{{cantidades.Cproducto}}
</option>
{% endfor %}
</select>
</div>
<div class="form-group">
<label for="cantidad">Cantidad de dicho producto</label>
<input type="number" class="form-control" name="cantidad" placeholder="cantidad" />
</div>
<button type="submit" class="btn btn-dark" style="margin-bottom: 1%;">Añadir!</button>
</form>
and you can use both id and name but for making request you need to name attribute

store date type data into database while user django

i cannot store the date into database. When I use debug, there is:
cleaned data = {'nick_name': 'Leren', 'gender': 'male', 'birday': None, 'address': '617 bridge', 'mobile': '2263408858'}
data = <QueryDict: {'nick_name': ['Leren'], 'birthday': ['2018-04-04'], 'gender': ['male'], 'address': ['617 bridge'], 'mobile': ['2263408858'], 'email': ['1#qq.com'], 'csrfmiddlewaretoken': ['1bzcpBzTOra7yTFBiwXc9sPLw8V6ETf7ciCDNqt1Jo9EtXZ4Q1qVBCIEWVVwPxGi']}>
i do not know why the birday does not exist in cleaned data but it exist in the data.
And how can i store it into my database?
html file:
<form class="perinform" id="jsEditUserForm" autocomplete="off">
<ul class="right">
<li>nickname:
<input type="text" name="nick_name" id="nick_name" value="{{ request.user.nick_name|default_if_none:'' }}" maxlength="10">
<i class="error-tips"></i>
</li>
<li>birthday:
<input type="text" id="birth_day" name="birthday" value="{{ request.user.birday|date:'Y-m-d H:i:s' }}" />
<i class="error-tips"></i>
</li>
<li>gender:
<label> <input type="radio" name="gender" value="male" {% ifequal request.user.gender "male" %}checked="checked"{% endifequal %} >male</label>
<label> <input type="radio" name="gender" value="female" {% ifequal request.user.gender "female" %}checked="checked"{% endifequal %}>female</label>
</li>
<li class="p_infor_city">address:
<input type="text" name="address" id="address" placeholder="" value="{{ request.user.address|default_if_none:'' }}" maxlength="10">
<i class="error-tips"></i>
</li>
<li>phone <input type="text" name="mobile" id="mobile" placeholder="" value="{{ request.user.mobile|default_if_none:'' }}" maxlength="10">
</li>
<li>email:
<input class="borderno" type="text" name="email" readonly="readonly" value="{{ request.user.email }}"/>
<span class="green changeemai_btn">[edit]</span>
</li>
<li class="button heibtn">
<input type="button" id="jsEditUserBtn" value="save">
</li>
</ul>
{% csrf_token %}
</form>
views.py:
class UserInfoView(LoginRequiredMixin,View): #用户个人信息 所以必须登陆才可以访问
def get(self,request):
return render(request,"usercenter-info.html",{
})
def post(self, request):
# 不像用户咨询是一个新的。需要指明instance。不然无法修改,而是新增用户
user_info_form = UserInfoForm(request.POST, instance=request.user)
if user_info_form.is_valid():
user_info_form.save()
return HttpResponse(
'{"status":"success"}',
content_type='application/json')
else:
# 通过json的dumps方法把字典转换为json字符串
return HttpResponse(
json.dumps(
user_info_form.errors),
content_type='application/json')
models.py
class UserProfile(AbstractUser):
nick_name=models.CharField(max_length=50,verbose_name="nickname",default="")
birday=models.DateField(verbose_name="birthday",null=True,blank=True)
gender=models.CharField(choices=(("male","male"),("female","female")),default="",max_length=10)
address=models.CharField(max_length=100,default="")
mobile=models.CharField(max_length=11,null=True,blank=True)
image=models.ImageField(upload_to="image/%Y/%m",default="image/default.png",max_length=100)
email = models.CharField(max_length=50,verbose_name="email",default="")
class Meta:
verbose_name="user profile"
verbose_name_plural=verbose_name
def __str__(self):
return self.username
forms.py:
class UserInfoForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ['nick_name','gender','birday','address','mobile']
there are my code above.
there might be something wrong when turning data into cleaned data

How to pass form id if there are several forms on page and no submit buttons Django 1.10?

I have a page with list of questions. Each of them has radio button form with "Yes", "Maybe", "No" kind of choices. This form's submits by making a choice.
http://prntscr.com/embo1m
I can't understand how to connect question id with it's form. How to get it in it's view with response?
models.py
class Answer(models.Model):
user = models.ForeignKey(User)
apartment = models.ForeignKey(Apartment)
question = models.ForeignKey(Question)
choice = models.IntegerField(default=2)
def __str__(self):
return str(self.choice)
views.py
def questions_list(request, apartment_pk):
context = {}
context['apartment'] = get_object_or_404(Apartment, pk=apartment_pk)
context['questions'] = get_list_or_404(Question)
context['answer_form'] = AnswerForm
context['username'] = auth.get_user(request).username
if request.method == 'POST':
form = AnswerForm(request.POST or None)
if form.is_valid():
print(form.cleaned_data)
return render(request, 'main/questions.html', context)
forms.py
class AnswerForm(ModelForm):
choice = ChoiceField(label='', widget=RadioSelect, choices=ANSWERS)
question_id = CharField(widget=HiddenInput(), required=False)
class Meta:
model = Answer
fields = ('choice', 'question_id')
template
<h1>{{ apartment.title }}</h1>
{% for question in questions %}
<h3>{{ question.title }}</h3>
<form id="question_{{ question.id }}" name="question_{{ question.id }}" action="/apartments/{{ apartment.id }}/" method="post">
{% csrf_token %}
{% for radio in answer_form.choice %}
<label><input name="choice" type="radio" value="{{ radio.choice_value }}" onchange="question_{{ question.id }}.submit()">{{ radio.choice_label }}</label>
{% endfor %}
{{ answer_form.hidden_field }}
</form>
{% endfor %}
EDIT:
Tried to pass question id as <input type="hidden" name="q_id" value="{{ question.id }}">
<h1>{{ apartment.title }}</h1>
{% for question in questions %}
<h3>{{ question.title }}</h3>
<form id="question_{{ question.id }}" name="question_{{ question.id }}" action="/apartments/{{ apartment.id }}/" method="post">
{% csrf_token %}
<input type="hidden" name="q_id" value="{{ question.id }}">
{% for radio in answer_form.choice %}
<label><input name="choice" type="radio" value="{{ radio.choice_value }}" onchange="question_{{ question.id }}.submit()">{{ radio.choice_label }}</label>
{% endfor %}
</form>
{% endfor %}
And changed my form to
class AnswerForm(Form):
choice = ChoiceField(label='', widget=RadioSelect, choices=ANSWERS)
But there's no hidden input in form from response...
<tr><th></th><td><ul id="id_choice">
<li><label for="id_choice_0"><input id="id_choice_0" name="choice" type="radio" value="0" required /> Точно ні</label></li>
<li><label for="id_choice_1"><input id="id_choice_1" name="choice" type="radio" value="1" required /> Скоріше ні</label></li>
<li><label for="id_choice_2"><input checked="checked" id="id_choice_2" name="choice" type="radio" value="2" required /> Не можу відповісти</label></li>
<li><label for="id_choice_3"><input id="id_choice_3" name="choice" type="radio" value="3" required /> Скоріше так</label></li>
<li><label for="id_choice_4"><input id="id_choice_4" name="choice" type="radio" value="4" required /> Точно так</label></li>
</ul></td></tr>
Cleaned data {'choice': '2'}
Pass the question id as hidden value as shown below:
<input type="hidden" name="q_id" value="{{ question.id }}">
{% for radio in answer_form.choice %}
<label><input name="choice" type="radio" value="{{ radio.choice_value }}" onchange="question_{{ question.id }}.submit()">{{ radio.choice_label }}</label>
{% endfor %}

Not getting score in my mcq app- Django

For my MCQ app, I created a view
def process_data(request):
question_set=Question.objects.all()
choice_list=[]
question_set
for k, v in request.POST.items():
if k.startswith('choice'):
choice_list.append(v)
i=0
score=0
print type(question_set)
for question in question_set:
if question.answer1==choice_list[i]:
#print question.answer1
i=i+1
score=score+1
return HttpResponse(score)
html page contains the form look like this.
{% extends 'quiz/base.html' %}
{% block content%}
<h1>You are at quiz page</h1>
<form action="{% url 'quiz:process_data' %}" method="post">
{% csrf_token %}
{% for question in question_set %}
<h3>{{question.question_no}}.{{question.question_text }}</h3>
<input type="radio" name="choice{{ question.question_no}}" value="{{ question.option1 }}">{{ question.option1 }}<br>
<input type="radio" name="choice{{ question.question_no}}" value="{{ question.option2 }}">{{ question.option2 }}<br>
<input type="radio" name="choice{{ question.question_no}}" value="{{ question.option3 }}">{{ question.option3 }}<br>
<input type="radio" name="choice{{ question.question_no}}" value="{{ question.option4 }}">{{ question.option4 }}<br>
<input type="radio" name="choice{{ question.question_no}}" value="{{ question.option5 }}">{{ question.option5 }}<br>
{% endfor %}
<input type="Submit" name="Submit">
</form>
{% endblock%}
and this is the model for Questions
class Question(models.Model):
question_no=models.IntegerField(default=0)
question_text=models.CharField(max_length=1000)
option1=models.CharField(max_length=100)
option2=models.CharField(max_length=100)
option3=models.CharField(max_length=100)
option4=models.CharField(max_length=100)
option5=models.CharField(max_length=100)
answer1=models.CharField(max_length=100)
def __str__(self):
return self.question_text
The problem is that the score is not getting correctly. So that I tested it with the print statement and realized that only first questions answer is getting. How can I get the score correctly? Thank you
The problem is with how you have handled this call request.POST.item. The call to item function returns an unordered dictionary. This is causing your second for-loop to match user inputs against wrong question. Below is a sample code of what I mean:
user_inputs = request.POST.items() # key: choice<question_no> and value: <user_choice>
for question in question_set:
user_choice = user_inputs.get('choice'+question.question_no)
if user_choice == question.answer1:
//count the score

Categories

Resources