Django将额外的字段添加到从Model生成的ModelForm中 [英] Django add extra field to a ModelForm generated from a Model

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

问题描述

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



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



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



所以我想在表单上的标记上插入一个临时ID,并在保存路径之前在视图中进行正确的安排。



我想到定义标记的自定义表单,但它似乎不是很干,如果我更改标记模型,我不想回到这里。



这里是形式:

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

def clean(self):
if any(self.errors):
#不要打扰验证表单,除非每个表单都有自己的
return

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

if(ingresso和ascensore)或(ingresso和scala)或(ascensore和scala):
提交form.ValidationError(楼梯不能是电梯或访问权限)
return self

def save(commit = True):
# 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 / 
无法导入buildings.views.getFloors。模块建筑中不存在视图。
请求方法:GET
请求URL:http://127.0.0.1:8000/admin/
Django版本:1.4.1
异常类型:ViewDoesNotExist
异常值:
无法导入buildings.views.getFloors。模块建筑中不存在视图。
异常位置:/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py in get_callable,第101行

当我尝试加载管理页面时,会产生错误,此页面根本不包含表单。



解决方案



好的,我会在这里写信如何找到为什么Django正在做这样一件奇怪的事情。



这里< a>找出问题是正确的方法。



异常被抛出,因为我忘了从django将 forms.py 添加到导入表单

解决方案

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



示例(名为Point的模型) :

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

class Meta:
model = Point

def save(self,commit = True):
#用self.cleaned_data做某事['temp_id']
返回超级(PointForm,self).save(commit = commit)

更新:在def save()中忘记自己,并将modelname更改为Point


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

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

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.

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.

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.

Here is the form:

  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)

And the model:

  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()

The error:

  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.

SOLUTION FOR EXCEPTION

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.

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

解决方案

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.

Example (with a model named 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)

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

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

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