【问题标题】:Django: avoid data type limitationDjango:避免数据类型限制
【发布时间】:2019-04-08 13:13:28
【问题描述】:

我有一个具有IntegerField attr 的类。 在它的ModelForm,在这个属性的字段中,我需要发送一个String,稍后在视图中处理它后将存储一个Integer。 问题是 Django 不允许这样做,当我使用 form.cleaned_data.get('myattr') 时,它说这是错误的,因为它应该是一个整数。

class Student(models.Model):
    teacher = models.IntegerField(null=False) # I'm saving teacher's key here


class Teacher(models.Model:
    name = models.CharField(max_length= 50, null=False)
    key = models.IntegerField(null=False)


class StudentForm(forms.ModelForm):
    teacher = forms.ModelChoiceField(queryset=Teacher.objects.all(), label='Select the teacher')

因此,当用户选择学生的教师时,该选择字段将显示可用教师的姓名。但在模型中它将存储他们的密钥,我在视图中管理。

views.py:

teacher = form.cleaned_data.get('teacher') # it has the name
teacher = Teacher.objects.get(name=teacher).key # getting the key in order to store an Integer, but Django is banning my code before anyway.

如何在不改变模型数据类型的情况下处理这个问题?

我什至在表单字段中添加了to_field_name 和教师键的值。

【问题讨论】:

  • a ModelChoiceField 用于选择模型中由ForeignKey 引用的对象。所以它需要Teacher 实例的pk(主键)作为输入。为什么不将ForeignKey 用于teacher 字段?你现在的代码太复杂了。
  • 因为我正在将桌面应用程序迁移到 Web 应用程序,并且我必须保留表格的结构。工作的东西
  • 然后确保您的 HTML 表单将 pk 作为值发布(
  • 好吧,如果我检查元素,在
  • 您遇到的错误究竟是什么?向我们展示您的模板、错误回溯以及request.POST 的内容。请注意,所有内容始终以字符串形式发布,甚至是整数。当表单字段获取值(并清理它)时,它们会被转换回所需的任何内容

标签: python django forms validation


【解决方案1】:

这里一个更好的方法是在你的学生和老师之间建立一个关系(使用外键)。

根据您的应用程序的需要,这里是如何做的:

如果一个学生可以有几个老师,一个老师可以有几个学生:https://docs.djangoproject.com/en/2.1/topics/db/examples/many_to_many/

如果一个学生只能有一个老师,但一个老师可以有多个学生: https://docs.djangoproject.com/en/2.1/topics/db/examples/many_to_one/

如果一个学生只能有一个老师,而一个老师只能有一个学生: https://docs.djangoproject.com/en/2.1/topics/db/examples/one_to_one/

这是管理此问题的最佳方法。 然后你只需要在 Student 表单中映射 Student 模型,例如:

class StudentForm(forms.ModelForm):
    class Meta:
        model = Student
        #you can add the list of all the fields you want there
        fields = ['teacher']

一个额外的步骤是定义模型的 str 方法,以便 Django 将您的模型的字符串表示形式关联到您的表单中(这里有一个在学生表单中显示教师的好方法)。

class Teacher(models.Model):
    name = models.CharField(max_length= 50, null=False)
    #place other fields here ...

    def __str__(self):
        #if you print a Teacher django will return the string corresponding to the teacher name
        return self.name

【讨论】:

  • 非常感谢您的回答。这很有用,但在这种情况下不是,因为我正在将桌面应用程序迁移到 Web 应用程序,并且公司希望保留其表格的结构。这就是为什么我试图以其他方式来管理它。如果我可以让代码忽略数据类型...
  • 如果在学生表单中添加学生的元描述会怎样。然后使用 Select 作为表单小部件并在 init 中填充数据库查询中的选择?
猜你喜欢
  • 2011-11-08
  • 2011-03-20
  • 2021-04-27
  • 1970-01-01
  • 2011-03-04
  • 2017-05-15
  • 2013-12-29
  • 2017-12-26
相关资源
最近更新 更多