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. springboot jpa 创建数据库以及rabbitMQ分模块扫描问题

    在使用jpa过程中,如果没有在配置中加入自动创建实体对于的sql,则需要提前创建建表语句 spring.jpa.properties.hibernate.show_sql=true spring.jp ...

  2. HihoCoder1076 与链(数位DP)

    时间限制:24000ms 单点时限:3000ms 内存限制:256MB 描述 给定 n 和 k.计算有多少长度为 k 的数组 a1, a2, ..., ak,(0≤ai) 满足: a1 + a2 +  ...

  3. BZOJ1787 [Ahoi2008]Meet 紧急集合[结论题]

    location. 求到树上三点距离和最短的点及此距离. 这个不还是分类讨论题么,分两类大情况,如下图. 于是乎发现三个点对的lca中较深的那个lca是答案点.距离就是两两点对距离加起来除以2即可.这 ...

  4. Unity3D资源

    1.ShareSDK 地址:https://github.com/MobClub/New-Unity-For-ShareSDK 文档:产品集成步骤 2.Protobuf https://github. ...

  5. CF1155 E.Guess the Root

    题目链接:Click here 题目大意:现在有一个至多11项的多项式\(F(x)\),你可以询问至多50个\(x\),黑盒子会告诉你\(F(x)\)的值,你现在要找到一个\(x\)使得\(F(x)= ...

  6. Haystack全文检索框架

    一.什么是Haystack Haystack是django的开源全文搜索框架(全文检索不同于特定字段的模糊查询,使用全文检索的效率更高 ),该框架支持Solr,Elasticsearch,Whoosh ...

  7. Jmeter(五)关联之正则表达式提取器

    我们在用Jmeter做接口或者性能测试时,经常会碰到第二个请求提交的的参数要从第一个请求返回的参数中获取,而这些参数值并不是固定的,是动态变化的,这种场景就要用到关联 Jmeter提供了一种叫做正则提 ...

  8. week6 作业

    week6 作业 1.每12小时备份并压缩/etc/目录至/backup目录中,保存文件名称格式为"etc-年-月-日-时-分.tar.gz" crontab -e */1 * * ...

  9. R_Studio(贷款)数据规范化处理[最小-最大规范化、零-均值规范化、小数定标规范化]

    农场申请贷款.csv 对“农场申请贷款.csv”中农场大小.降雨量.农场质量.农场收入进行数据规范化处理 行数[4 5 6 7] “农场申请贷款.csv”中存在缺失值,已对数据进行预处理 setwd( ...

  10. [CSP-S模拟测试]:打表(猜测题意+结论)

    题目传送门(内部题139) 输入格式 第一行两个整数$k,ans$,表示内存地址$A$的位数,以及答案所在的内存地址. 接下来一行$2^k$个整数,分别表示内存地址$0...2^k-1$上的值. 输出 ...