Django模型FloatField错误'float'对象没有属性'as_tuple'

问题描述 投票:1回答:1

我有一个带FloatField的Django模型,后来我将其作为表单的基础。由于某种原因,我得到了“'float'对象没有属性'as_tuple'”,但是不幸的是,我不知道为什么会得到这个错误或如何解决它。

models.py:

class Course(models.Model):
    title = models.CharField(max_length = 200)
    author = models.ForeignKey(User,default=None, on_delete=models.SET_DEFAULT)
    description = models.TextField(max_length=1000, blank=True)
    tags = models.TextField(blank = True)
    duration = models.FloatField(validators=(MinValueValidator(0.1),MaxValueValidator(12), DecimalValidator(max_digits=3,decimal_places=2)))


    def __str__(self):
            return self.title

forms.py:

class CourseForm(ModelForm):
    class Meta:
        model = Course
        fields = ('title', 'description', 'price', 'duration', 'tags')

views.py:

@login_required
def create_course(request):
    if request.method == "POST":
        form = CourseForm(request.POST)

        if form.is_valid():

            form.save()
            messages.info(request, f"Course created succesfully!")

        else:
            messages.error(request, "Something went wrong, please resubmit!")


    form = CourseForm()
    return render(request, "main/createcourse.html", {"form": form})

html:

{% extends 'main/header.html' %}
<body>

   {% block content%}
<div class="container">

    <form method="POST">
        {% csrf_token %}

        {{form.as_p}}

        <br>
        <button class="btn" type="submit">Create</button>
    </form>

    If you to modify an existing course, click <a href="/modify"><strong>here</strong></a> instead.
</div>
<br><br>
    {% endblock %}



</body>

python django
1个回答
0
投票

floatDecimal之间存在差异。 Decimal通过存储十进制数字对数据进行编码。但是,您可以notDecimalValidation上执行float,因为由于舍入错误,它将添加额外的数字。

因此,您可以改用DecimalField [Django-doc]。请注意,在这种情况下,您需要传递DecimalField对象,not浮点数。

Decimal

您可能想看看class Course(models.Model): title = models.CharField(max_length = 200) author = models.ForeignKey(User,default=None, on_delete=models.SET_DEFAULT) description = models.TextField(max_length=1000, blank=True) tags = models.TextField(blank = True) duration = models.DecimalField(max_digits=3,decimal_places=2, validators=(MinValueValidator(0.1),MaxValueValidator(12), DecimalValidator(max_digits=3,decimal_places=2))) def __str__(self): return self.title来存储持续时间,但是它将自动使用DurationField [Django-doc],并将其存储为整数,以支持not不支持此类类型的数据库。

© www.soinside.com 2019 - 2024. All rights reserved.