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

时间:2012-11-25 11:16:21

标签: django japplet django-forms

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

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

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

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

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

以下是表格:

  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

2 个答案:

答案 0 :(得分:61)

您可以向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()中忘记自我,并将模型名更改为Point

答案 1 :(得分:5)

为了跟进relekang的回答,我还必须提醒return如图所示的最后一行,以便在提交表单时可以自动调用对象的get_absolute_url()方法:

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