我有一个带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>
float
和Decimal
之间存在差异。 Decimal
通过存储十进制数字对数据进行编码。但是,您可以not在DecimalValidation
上执行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不支持此类类型的数据库。