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. 背包 || NOIP 2018 D1 T2 || Luogu P5020 货币系统

    题面:P5020 货币系统 题解: 显然要求的货币系统是当前货币系统的子集时答案会更优,于是考虑从当前货币系统中删数 一个大数如果能被其他小数表示出来,它就可以去掉 把数据排个序去个重,然后直接背包 ...

  2. constant read 和 current read

    来自网络,并且在本机实验完成: onsistent read :我的理解,就是通过scn来读取.  读取的过程中要保证 scn是一致的.举个例子,一个SELECT 语句在SCN=100的时刻开始读取一 ...

  3. JavaScript基础——JavaScript常量和变量(笔记)

    JavaScript常量和变量(笔记) Javascript代码严格区分大小写. javascript暂不支持constant关键字,不允许用户自定义常量. javascript使用var关键字声明变 ...

  4. Phaserjs V2的state状态解析及技巧

    用phaserjs开发了好多游戏了,但是对phaser还是了解不深,只知道怎么去用,今天就特意花点时间研究下phaser的状态管理到底是怎么回事. 首先,new Phaser.Game,以下是Phas ...

  5. react -搭建服务

    import 'whatwg-fetch'; import 'es6-promise'; require('es6-promise').polyfill(); import * as common f ...

  6. mysql 递归查找所有子节点

    select dept_id from ( select t1.dept_id,t1.parent_id, if(find_in_set(parent_id, @pids) > 0, @pids ...

  7. Java多线程和并发(八),synchronized底层原理

    目录 1.对象头(Mark Word) 2.对象自带的锁(Monitor) 3.自旋锁和自适应自旋锁 4.偏向锁 5.轻量级锁 6.偏向锁,轻量级锁,重量级锁联系 八.synchronized底层原理 ...

  8. THUSC2016 成绩单

    题目链接:Click here Solution: 我们设\(f[l][r][x][y]\)表示在原区间\(l\sim r\) 内还未被取走的值最大为\(x\)最小为\(y\)时的代价,这里我们只考虑 ...

  9. python学习之路(12)

    迭代 如果给定一个list或tuple,我们可以通过for循环来遍历这个list或tuple,这种遍历我们称为迭代(Iteration). 在Python中,迭代是通过for ... in来完成的,而 ...

  10. 4000余字为你讲透Codis内部工作原理

    一.引言 Codis是一个分布式 Redis 解决方案,可以管理数量巨大的Redis节点.个推作为专业的第三方推送服务商,多年来专注于为开发者提供高效稳定的消息推送服务.每天通过个推平台下发的消息数量 ...