Mar*_*ele 54 django django-forms japplet
我必须从模型生成一个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)
Run Code Online (Sandbox Code Playgroud)
而型号:
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()
Run Code Online (Sandbox Code Playgroud)
错误:
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
Run Code Online (Sandbox Code Playgroud)
当我尝试加载管理页面时生成错误,此页面根本没有对表单的引用.
解决方案除外
好的,我会在这里写一下如何找出为什么Django做了这么奇怪的事情.
这是找出问题的正确方法.
抛出异常是因为我忘了添加forms.py
到from django import forms
.
小智 68
您可以向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)
Run Code Online (Sandbox Code Playgroud)
更新:在def save()中忘记自己,并将modelname更改为Point
为了跟进relekang的回答,我不得不提醒我也返回如图所示的最后一行,这样在提交表单时可以自动调用对象的get_absolute_url()方法:
return super(PointForm, self).save(commit=commit)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
45953 次 |
最近记录: |