Wednesday, July 5, 2017

count the selected chechboxes in multipleselectfield

I need your help with a problem I'm trying to solve
I'm making a questionnaire and I have to count the selected choices that the user have checked in a certain question with 5 possible answers(choices)
The model I'm using is:

class Reuse(models.Model):
    REUSE_OPTIONS = (
        ('1', 'first choice'),
        ('2', 'second choice'),
        ('3', 'third choice'),
        ('4', 'fourth choice'),
        ('5', 'none of the above'),
    )
   
    user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True)
    reuse = MultiSelectField(max_length=250, choices= REUSE_OPTIONS, max_choices=4, null=True)
    m = models.DecimalField(max_digits=5, decimal_places=3, default=0)
    numchoices = models.IntegerField()
    def numchoices(self):                                       (I tried this but it didn't work)
        self.choices_count = self.choice_set.count()
        self.save()

I wrote this view:
def reuse (request):
    if request.method == "POST":
        form = ReuseForm(request.POST)
        if form.is_valid():
            reuse = form.save(commit=False)
           # if reuse.get_choices.count() == 1 : reuse.m=0.075        (this doesn't work either)
          #  elif reuse.get_choices.count() == 2 : reuse.m=0.15
           # elif reuse.get_choices.count() == 3 : reuse.m=0.225
         #   elif reuse.get_choices.count() == 4 : reuse.m=0.3
            reuse.save()
            return redirect('../22')
    else:
        form = ReuseForm()
    return render(request, 'questionnaire/reuse.html', {'form':form})

And the form I'm using is:

class ReuseForm(forms.ModelForm):

    class Meta:
        model = Reuse
        fields = ('reuse',)
 
Please, have you got any suggestions;



--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/ca1f528d-903a-428f-b781-6506dff69e0f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment