【问题标题】:Django -- Checking input type, display error message if wrongDjango - 检查输入类型,如果错误则显示错误消息
【发布时间】:2021-10-07 03:10:25
【问题描述】:

我是学习 Django/Python 的新手,希望能得到一些帮助。这是一项任务,我对最后一部分感到困惑。我们需要从用户那里获取输入(名称为字符串;体重、身高英寸和身高英尺为整数)并计算 bmi,显示 {{name}} 的 bmi 为 {{bmi}}

我的那部分工作正常,但我要做的第二部分是检查输入是否有效,这不是一个字符串,它应该是一个 int,而不是一个负数。我应该把这个放到课堂上。我正在阅读有关 is_valid() 的信息,但我还没有使用过它,也不完全确定该怎么做。我猜它必须是一个 if else 语句。

views.py

class Home(View):
  def get(self, request):
      return render(request, 'home.html')
  def post(self, request):
      n = str(request.POST["name"])
      w = int(request.POST["weight"])
      hi = int(request.POST["heightinches"])
      hf = int(request.POST["heightfeet"])
      h = (hf*12) + hi
      bmi = (703*w) / (h*h)
      return render(request, 'response.html',{"name":n,"heightinches":hi,"heightfeet":hf,"weight":w,"height":h,"bmi":bmi}

home.html

{% load static %}
<html>
  <head><title>Home</title></head>
  <body>
    <h1>Hello Repl.it</h1>
  <form action="" method="post">
    {% csrf_token %}
  name: <input type="text" name="name" id="name"/> <br>
  weight: <input type="text" name="weight" id="weight"/> pounds<br>
  height: <input type="text" name="heightinches" id="heightinches"/> inches<br>
  <input type="text" name="heightfeet" id="heightfeet"/> feet<br>
  <input type="submit"/>

  
  </form>
  </body>
</html>

response.html

{% load static %}
<html>
  <head><title>Home</title></head>
  <body>
  {{name}}'s BMI is {{bmi|floatformat:2}}

  <p><a href="home.html">Back</a></p>
  </body>
</html>

提前感谢您的帮助!我的导师不是最容易找到的,所以我希望我在这里能有更好的运气:S

【问题讨论】:

标签: python django input


【解决方案1】:

我使用 Django 已经有一段时间了。 Django 在基础 Django 库中提供了一个深入的表单库。

我强烈建议您按照本指南进行设置。 https://docs.djangoproject.com/en/3.2/topics/forms/

如果您需要自定义验证,您可以在 InputForm 类的底部添加一个函数来检查这一点,如果未通过,则引发 ValidationError:

def check_google_url(self):
    url = self.cleaned_data['url']
    if "https://google.com" not in url:
        raise forms.ValidationError("URL does not match Google! Please copy and paste the full google.com URL.")
    else:
        return url

一旦您设置了表单,您就可以使用清晰的表单来定义此页面的“错误”和“必需”css 类。脆皮表格 - https://django-crispy-forms.readthedocs.io/en/latest/

self.helper.layout = Layout(
    Div(
    'negatives',
    'positives',
    'learnings',
    'rating',
    css_class="final-feedback",
    required_css_class="error",
    error_css_class="error",
    title="Final Comments",
    ),
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-24
    • 1970-01-01
    相关资源
    最近更新 更多