【问题标题】:How can I Convert TypedChoiceField to Int in Django?如何在 Django 中将 TypedChoiceField 转换为 Int?
【发布时间】:2019-12-19 15:53:40
【问题描述】:

我正在尝试将数据从选择字段转换为 INT,但出现错误:

"int() 参数必须是字符串、类似字节的对象或数字,而不是 'TypedChoiceField'"

但是,我不明白为什么 coerce=int 不会将选择字段中的数据转换为 int。

我的 forms.py 类

class ReviewForm(forms.Form):
readability_rating = forms.TypedChoiceField(
    choices=[(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)], coerce=int)

我的views.py函数

def readerpage(request, content_id):
   form = ReviewForm(request.POST)
   if form.is_valid():
        review.readability_rating = forms.TypedChoiceField(
                        choices=[(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)], coerce=int)
        review.save()
        form = ReviewForm()
        return redirect('home') 

我的模型

class Review(models.Model):
   readability_rating = models.IntegerField(null=True)

感谢阅读本文

【问题讨论】:

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


    【解决方案1】:

    这个分配是一个错误,这不是表单的工作方式:

    if form.is_valid():
        review.readability_rating = forms.TypedChoiceField(
                            choices=[(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)], coerce=int)
    

    请转至forms tutorial

    还要检查这个答案:How to get value from form field in django framework?)

    如果您想深入了解 Django 的工作原理,我还推荐一本书:Apress Pro Django。

    希望对你有帮助。

    【讨论】:

    • 哦...那我的回答完全无关紧要。
    猜你喜欢
    • 2021-01-27
    • 1970-01-01
    • 2014-05-22
    • 1970-01-01
    • 2018-06-20
    • 1970-01-01
    • 1970-01-01
    • 2013-10-11
    • 2020-07-17
    相关资源
    最近更新 更多