Django 向从模型生成的 ModelForm 添加额外的字段 [英] Django add extra field to a ModelForm generated from a Model

查看:53
本文介绍了Django 向从模型生成的 ModelForm 添加额外的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have to generate a FormSet from a model but I need to insert an "extra value" in to every form.

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

Specifically, I have a JApplet that generates some Markers and Paths on a image, and POST it on the server.

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

In my model lines are composed from two Markers. But when I POST it, because I'm using the id generated from the JApplet and not from the database, I will not know from which Markers a Path will be composed.

于是想到在form上的Marker上插入一个临时id",在保存Path之前在view中做正确的安排.

So I thought to insert a "temporary id" on the Marker on the form, and do the correct arrangements in the view before saving the Path.

我想过为标记定义一个自定义表单,但它似乎不是很 DRY,如果我改变了 Marker 模型,我不想回到这个.

I thought about defining a custom form for the markers, but it not seems to be very DRY, and I don't want to came back to this if I change the Marker model.

表格如下:

  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

当我尝试加载管理页面时生成错误,该页面根本没有与表单的引用.

The error is generated when I try to load the admin page, this page has no references at all with the form.

例外的解决方案

好的,我会在这里写下如何找出 Django 为何做出如此奇怪的事情.

Ok, I'll write here how to find out why Django was doing such a strange thing.

此处是找出问题所在的正确方法.

Here it's a correct way to find out what is the problem.

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

The exception was thrown because I forgot to add forms.py to the from django import forms.

推荐答案

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

You can add a field to a ModelForm. Unless you add a field named temp_id to your model you do not need to change this form when you change you model.

示例(使用名为 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

UPDATE: Forgot self in def save() and changed modelname to Point

这篇关于Django 向从模型生成的 ModelForm 添加额外的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆