【发布时间】:2020-02-01 22:22:16
【问题描述】:
我有一个带有 FloatField 的 Django 模型,我稍后会基于它创建一个表单。出于某种原因,我得到“'float' object has no attribute '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>
【问题讨论】:
-
你不能对
FloatField执行DecimalValidation,你应该使用DecimalField。