Reputation: 135
I loop through multiple question stored in my DB each question has 5 answers(openness,conscientiousness,extraversion,agreeableness,neuroticism) and am trying to count how many times each answers is repeated and store the scores
Models :
class Reponses(models.Model):
ScoreOp = models.IntegerField(blank=True,null=True)
ScoreCon = models.IntegerField(blank=True,null=True)
ScoreExt = models.IntegerField(blank=True,null=True)
ScoreAgr = models.IntegerField(blank=True,null=True)
ScoreNeu = models.IntegerField(blank=True,null=True)
Product = models.OneToOneField("Product", on_delete=models.CASCADE,null=True)
class Personalite(models.Model):
Question = models.CharField(max_length=50,blank=True)
openness = models.CharField(max_length=20,blank=True)
conscientiousness = models.CharField(max_length=20,blank=True)
extraversion = models.CharField(max_length=20,blank=True)
agreeableness = models.CharField(max_length=20,blank=True)
neuroticism = models.CharField(max_length=20,blank=True)
models.ForeignKey("Reponses", on_delete=models.CASCADE,null=True)
Views :
def home_views(request):
questions= Personalite.objects.all()
product = Product.objects.get(id=5)
if request.method == 'POST':
try:
reponse = Reponses.objects.create()
reponse = Reponses(Product= product)
allRep = []
allRep = request.POST.getlist('poll')
for Rep in allRep:
print(Rep)
if Rep == 'openness':
reponse.ScoreOp = reponse.ScoreOp + 1
elif Rep == 'conscientiousness':
reponse.ScoreCon += 1
elif Rep == 'extraversion':
reponse.ScoreExt += 1
elif Rep == 'agreeableness':
reponse.ScoreAgr += 1
elif Rep == 'neuroticism':
reponse.ScoreNeu += 1
else :
print('HAHAHAHHAHAAH')
reponse.save()
except NameError:
print("An exception occurred",NameError)
context={
'questions':questions
}
return render(request , "home.html",context)
Upvotes: 0
Views: 518
Reputation: 7330
reponse = Reponses(Product= product)
this doesn't saves the response object you need to call the save()
method so reponse.ScoreOp
is None.
Try this.
First create the response object properly.
reponse = Reponses.objects.create(Product=product)
And also instead of specifying the null=True
to the integer field provide the default value 0
.
ScoreOp = models.IntegerField(default=0) # properly migrate after change in model
Now in the views.
if Rep == 'openness':
reponse.ScoreOp += 1
Upvotes: 1