gpt4 book ai didi

Django 将额外字段添加到从模型生成的 ModelForm

转载 作者:行者123 更新时间:2023-11-28 19:33:59 28 4
gpt4 key购买 nike

我必须从模型生成一个 FormSet,但我需要在每个表单中插入一个“额外值”。

具体来说,我有一个 JApplet,可以在图像上生成一些标记和路径,并将其发布到服务器上。

在我的模型中,线条由两个标记组成。但是当我发布它时,因为我使用的是从 JApplet 而不是从数据库生成的 ID,所以我不知道路径将从哪些标记组成。

所以我想在表单上的Marker上插入一个“临时id”,在保存Path之前在 View 中做正确的排列。

我考虑过为标记定义一个自定义表单,但它似乎不是很 DRY,如果我更改标记模型,我不想再回到这个问题上。

这是表格:

  class PointForm(forms.ModelForm):
temp_id = forms.IntegerField()
class Meta:
model = Point

def clean(self):
if any(self.errors):
# Don't bother validating the formset unless each form is valid on its own
return

ingresso = self.cleaned_data['ingresso']
ascensore = self.cleaned_data['ascensore']
scala = self.cleaned_data['scala']

if (ingresso and ascensore) or (ingresso and scala) or (ascensore and scala):
raise forms.ValidationError("A stair cannot be a elevator or an access!!!")
return self

def save(commit=True):
# do something with self.cleaned_data['temp_id']
super(PointForm).save(commit=commit)

和模型:

  class Point(models.Model):

RFID = models.CharField(max_length=200, blank=True)

x = models.IntegerField()
y = models.IntegerField()

piano = models.ForeignKey(Floor)

ingresso = models.BooleanField()

错误:

  ViewDoesNotExist at /admin/
Could not import buildings.views.getFloors. View does not exist in module buildings.views.
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/
Django Version: 1.4.1
Exception Type: ViewDoesNotExist
Exception Value:
Could not import buildings.views.getFloors. View does not exist in module buildings.views.
Exception Location: /usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py in get_callable, line 101

错误是在我尝试加载管理页面时产生的,该页面根本没有对表单的引用。

异常解决方案

好吧,我会在这里写下如何找出为什么 Django 会做这么奇怪的事情。

Here这是找出问题所在的正确方法。

抛出异常是因为我忘记将forms.py添加到from django import forms中。

最佳答案

您可以将字段添加到 ModelForm。除非您将名为 temp_id 的字段添加到模型中,否则在更改模型时不需要更改此表单。

示例(带有名为 Point 的模型):

class PointForm (forms.ModelForm):
temp_id = forms.IntegerField()

class Meta:
model = Point

def save(self, commit=True):
# do something with self.cleaned_data['temp_id']
return super(PointForm, self).save(commit=commit)

更新:在 def save() 中忘记了 self 并将模型名称更改为 Point

关于Django 将额外字段添加到从模型生成的 ModelForm,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13550515/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com