count the selected checkboxes in a multipleselectfield

8 views
Skip to first unread message

elloy

unread,
Jul 5, 2017, 6:55:58 AM7/5/17
to Django users
Please, I need your help because I'm trying to solve a problem
I'm making a questionnaire and I want to count the number of the selected choices in a certain question
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, '../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;
Thank you in advance


Reply all
Reply to author
Forward
0 new messages