如何从Django表单计算平均数据并将其存储在变量中以备后用?

时间:2019-12-20 11:03:37

标签: django django-models django-forms django-views

在readerpage函数的views.py中,我试图计算两个变量的平均值:readability_ratingactionability_rating,并将结果存储在avg_rating

def readerpage(request, content_id):
    content = get_object_or_404(Content, pk=content_id)
    form = ReviewForm(request.POST)
    if form.is_valid():
        review = form.save(commit=False)
        review.content = content
        readability_rating = form.cleaned_data['readability_rating']
        readability = form.cleaned_data['readability']
        actionability_rating = form.cleaned_data['actionability_rating']
        actionability = form.cleaned_data['actionability']
        general_comments = form.cleaned_data['general_comments']
        review.avg_rating = (float(readability_rating) +
                             float(actionability_rating)) / 2
        review.save()
        return redirect('home')
    args = {'content': content, 'form': form}
    return render(request, 'content/readerpage.html', args)

问题在于,使用此设置,两个变量仍然是ChoiceFields-因此上述设置给我带来了错误:

  

float()参数必须是字符串或数字,而不是'ChoiceField'

我尝试将它们转换为没有任何运气的浮点数。 我还尝试将TypedChoiceField与coerce=float一起使用,但仍然没有运气

我不确定最好的计算位置是在函数,表单还是模型中?

models.py

class Review(models.Model):
    content = models.ForeignKey(Content, null=True, on_delete=models.CASCADE)
    readability = models.CharField(null=True, max_length=500)
    readability_rating = models.IntegerField(null=True)
    actionability = models.CharField(null=True, max_length=500)
    actionability_rating = models.IntegerField(null=True)
    general_comments = models.CharField(null=True, max_length=500)
    avg_rating = models.FloatField(null=True)


    def _str_(self):
        return self.title

forms.py

class ReviewForm(forms.ModelForm):
    readability = forms.CharField(widget=forms.Textarea)
    readability_rating = forms.ChoiceField(
        choices=[(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)])
    actionability = forms.CharField(widget=forms.Textarea)
    actionability_rating = forms.ChoiceField(
        choices=[(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)])
    general_comments = forms.CharField(widget=forms.Textarea)


    class Meta:
        model = Review
        fields = ['readability', 'readability_rating',
                  'actionability', 'actionability_rating', 'general_comments']

感谢阅读。

1 个答案:

答案 0 :(得分:0)

变量是ChoiceFields,因为您在视图函数中将它们声明为ChoiceFields。您不应该只是从cleaned_data中获取值吗?

readability_rating = form.cleaned_data['readability_rating']

问题的第二部分:为什么不将其作为@property添加到模型中?