What I would like to do is to display a single form that lets the user:

  • Enter a document title (from Document model)
  • Select one of their user_defined_code choices from a drop down list (populated by the UserDefinedCode model)
  • Type in a unique_code (stored in the Code model)

I'm not sure how to go about displaying the fields for the foreign key relationships in a form. I know in a view you can use document.code_set (for example) to access the related objects for the current document object, but I'm not sure how to apply this to a ModelForm.

My model:

class UserDefinedCode(models.Model):
name = models.CharField(max_length=8)
owner = models.ForeignKey(User) class Code(models.Model):
user_defined_code = models.ForeignKey(UserDefinedCode)
unique_code = models.CharField(max_length=15) class Document(models.Model):
title = models.CharField(blank=True, null=True, max_length=200)
code = models.ForeignKey(Code)
active = models.BooleanField(default=True)

My ModelForm

class DocumentForm(ModelForm):
class Meta:
model = Document
asked Apr 18 '11 at 20:42
Ben S

5891720

In regards to displaying a foreign key field in a form you can use the forms.ModelChoiceField and pass it a queryset.

so, forms.py:

class DocumentForm(forms.ModelForm):
class Meta:
model = Document def __init__(self, *args, **kwargs):
user = kwargs.pop('user','')
super(DocumentForm, self).__init__(*args, **kwargs)
self.fields['user_defined_code']=forms.ModelChoiceField(queryset=UserDefinedCode.objects.filter(owner=user))

views.py:

def someview(request):
if request.method=='post':
form=DocumentForm(request.POST, user=request.user)
if form.is_valid():
selected_user_defined_code = form.cleaned_data.get('user_defined_code')
#do stuff here
else:
form=DocumentForm(user=request.user) context = { 'form':form, } return render_to_response('sometemplate.html', context,
context_instance=RequestContext(request))

from your question:

I know in a view you can use document.code_set (for example) to access the related objects for the current document object, but I'm not sure how to apply this to a ModelForm.

Actually, your Document objects wouldn't have a .code_set since the FK relationship is defined in your documents model. It is defining a many to one relationship to Code, which means there can be many Document objects per Code object, not the other way around. Your Code objects would have a .document_set. What you can do from the document object is access which Code it is related to using document.code.

edit: I think this will do what you are looking for. (untested)

forms.py:

class DocumentForm(forms.ModelForm):
class Meta:
model = Document
exclude = ('code',) def __init__(self, *args, **kwargs):
user = kwargs.pop('user','')
super(DocumentForm, self).__init__(*args, **kwargs)
self.fields['user_defined_code']=forms.ModelChoiceField(queryset=UserDefinedCode.objects.filter(owner=user))
self.fields['unique_code']=forms.CharField(max_length=15)

views.py:

def someview(request):
if request.method=='post':
form=DocumentForm(request.POST, user=request.user)
if form.is_valid():
uniquecode = form.cleaned_data.get('unique_code')
user_defined_code = form.cleaned_data.get('user_defined_code')
doc_code = Code(user_defined_code=user_defined_code, code=uniquecode)
doc_code.save()
doc = form.save(commit=False)
doc.code = doc_code
doc.save()
return HttpResponse('success')
else:
form=DocumentForm(user=request.user) context = { 'form':form, } return render_to_response('sometemplate.html', context,
context_instance=RequestContext(request))

actually you probably want to use get_or_create when creating your Code object instead of this.

doc_code = Code(user_defined_code=user_defined_code, code=uniquecode)

How do I add a Foreign Key Field to a ModelForm in Django?的更多相关文章

  1. MySQL添加foreign key时出现1215 Cannot add the foreign key constraint

    引言: MySQL中经常会需要创建父子表之间的约束,这个约束是需要建立在主外键基础之上的,这里解决了一个在创建主外键约束过程中碰到的一个问题. mysql中添加外键约束遇到一下情况: cannot a ...

  2. MySQL Foreign Key

    ntroduction to MySQL foreign key A foreign key is a field in a table that matches another field of a ...

  3. MySQL系列(十一)--外键约束foreign key的基本使用

    有些时候,为了保证数据的完整性,我们会选择的使用外键约束,例如教师对应的表和课程表中老师的id,这种时候就要使用外键约束了. PS:这里不考虑表结构设计,三范式与反范式等设计问题,基于MySQL8.0 ...

  4. MySQL添加外键时报错 ERROR 1215 (HY000): Cannot add foreign key constraint

    1.数据类型      2.数据表的引擎 数据表 mysql> show tables; +------------------+ | Tables_in_market | +--------- ...

  5. can't add foreign key in mysql?

    create table department (dept_name ), building ), budget numeric(,) ), primary key (dept_name) ); cr ...

  6. Error 'Cannot add or update a child row: a foreign key constraint fails故障解决

    一大早的,某从库突然报出故障:SQL线程中断! 查看从库状态: mysql> show slave status\G Slave_IO_State: Waiting for master to ...

  7. insert时报Cannot add or update a child row: a foreign key constraint fails (`yanchangzichan`.`productstatusrecord`, CONSTRAINT `p_cu` FOREIGN KEY (`cid`) REFERENCES `customer` (`cid`))错误

    mybatis在insert时报Cannot add or update a child row: a foreign key constraint fails (`yanchangzichan`.` ...

  8. IntegrityError at /admin/users/userprofile/add/ (1452, 'Cannot add or update a child row: a foreign key constraint fails (`mxonline`.`django_admin_log`, CONSTRAINT `django_admin_log_user_id_c564eba6_

    报错现象 在执行 django 后台管理的时候添加数据导致 1452 错误 报错代码 IntegrityError at /admin/users/userprofile/add/ (1452, 'C ...

  9. Cannot add foreign key constraint @ManyToMany @OneToMany

    最近在使用shiro做权限管理模块时,使用的时user(用户)-role(角色)-resource(资源)模式,其中user-role 是多对多,role-resource 也是多对多.但是在使用sp ...

随机推荐

  1. 第五章 动画 50 动画-transition-group中appear和tag属性的作用

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8&quo ...

  2. 使用CreateMetaFile创建WMF文件,并转换为EMF文件

    #include <iostream> #include <stdio.h> #include <WINDOWS.H> #include <shellapi. ...

  3. 如何在某些情况下禁止提交Select下拉框中的默认值或者第一个值(默认选中的就是第一个值啦……)

    群里有个帅哥问了这么个问题,他的下拉框刚进页面时是隐藏起来的,但是是有值的,为啥呢?因为下拉框默认选中了第一个值呗,,, 所以提交数据的时候就尴尬啦,明明没有选,但是还是有值滴.怎么办呢? 一开始看到 ...

  4. grunt-contrib-uglify js压缩

    grunt-contrib-uglify:压缩以及合并JavaScript文件. 插件安装:npm install grunt-contrib-uglify --save-dev 参数: banner ...

  5. dede 调取二级三级菜单栏目

    {dede:channelartlist typeid='} <div class="cate-item"> <div class="cate-item ...

  6. sql2014 日志太大 删除日志

    首先,我们要确认日志的文件名,因为硬盘上的文件名不一定是数据字典里面的文件名,所以要确认下 USE test9572 GO SELECT file_id,name FROM sys.database_ ...

  7. CSS定位——文档流定位

    关于CSS的定位机制Ⅰ ㈠概念 对于盒子模型来说,也就是页面元素,这些盒子究竟在页面的什么位置,怎样排列它,那么找到它的位置,确定它的位置,这个就是定位机制所决定的. ㈡分类 文档流, 浮动定位,层定 ...

  8. jquery die()方法 语法

    jquery die()方法 语法 作用:die() 方法移除所有通过 live() 方法向指定元素添加的一个或多个事件处理程序.直线电机参数 语法:$(selector).die(event,fun ...

  9. 手动升级 Confluence - 规划你的升级

    1. 确定你的升级路径 使用下面的表格来确定最佳的升级路径来让你的Confluence 从当前版本升级到最新的 Confluence 版本. 你的版本 推荐升级到 Confluence 的升级路径 2 ...

  10. HNOI2010 平面图判定(planar)

    题目链接:戳我 我怎么知道平面图有这个性质?? 对于一个平面图,它的边数不超过点数的\(3n-6\) 所以可以直接把边数多的特判掉,剩下的图中边数和点数就是一个数量级的了. 因为这个图存在欧拉回路,所 ...