Django 向从 Model 生成的 ModelForm 添加额外字段

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

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

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

因此,我想在表单上的 Marker 上插入一个“临时 id”,并在保存 Path 之前在视图中进行正确的排列。

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

表格如下:

  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

当我尝试加载管理页面时,会产生错误,该页面对表单没有任何引用。

例外情况的解决方案

好的,我会在这里写出如何找出姜戈为什么做这样一件奇怪的事情。

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

由于忘记将 forms.py添加到 from django import forms,引发了异常。

68017 次浏览

可以向 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,并将 model name 更改为 Point

为了继续关注 RelKang 的回答,我不得不提醒自己还要如图所示的 返回最后一行,这样在提交表单时就可以自动调用对象的 get _ Absol_ url ()方法:

return super(PointForm, self).save(commit=commit)