How do I add a Foreign Key Field to a ModelForm in Django?
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 theUserDefinedCode
model) - Type in a
unique_code
(stored in theCode
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
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?的更多相关文章
- MySQL添加foreign key时出现1215 Cannot add the foreign key constraint
引言: MySQL中经常会需要创建父子表之间的约束,这个约束是需要建立在主外键基础之上的,这里解决了一个在创建主外键约束过程中碰到的一个问题. mysql中添加外键约束遇到一下情况: cannot a ...
- MySQL Foreign Key
ntroduction to MySQL foreign key A foreign key is a field in a table that matches another field of a ...
- MySQL系列(十一)--外键约束foreign key的基本使用
有些时候,为了保证数据的完整性,我们会选择的使用外键约束,例如教师对应的表和课程表中老师的id,这种时候就要使用外键约束了. PS:这里不考虑表结构设计,三范式与反范式等设计问题,基于MySQL8.0 ...
- MySQL添加外键时报错 ERROR 1215 (HY000): Cannot add foreign key constraint
1.数据类型 2.数据表的引擎 数据表 mysql> show tables; +------------------+ | Tables_in_market | +--------- ...
- can't add foreign key in mysql?
create table department (dept_name ), building ), budget numeric(,) ), primary key (dept_name) ); cr ...
- 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 ...
- 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`.` ...
- 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 ...
- Cannot add foreign key constraint @ManyToMany @OneToMany
最近在使用shiro做权限管理模块时,使用的时user(用户)-role(角色)-resource(资源)模式,其中user-role 是多对多,role-resource 也是多对多.但是在使用sp ...
随机推荐
- centos swap分区
swap分区 通常memory是机器的物理内存,读写速度低于cpu一个量级,但是高于磁盘不止一个量级.所以,程序和数据如果在内存的话,会有非常快的读写速度.但是,内存的造价是要高于磁盘 ...
- nginx反向代理原理及配置详解
nginx概述nginx是一款自由的.开源的.高性能的HTTP服务器和反向代理服务器:同时也是一个IMAP.POP3.SMTP代理服务器:nginx可以作为一个HTTP服务器进行网站的发布处理,另外n ...
- 胡昊—第6次作业—static关键字、对象
#题目1:编写一个类Computer,类中含有一个求n的阶乘的方法.将该类打包,并在另一包中的Java文件App.java中引入包,在主类中定义Computer类的对象,调用求n的阶乘的方法(n值由参 ...
- 从收发消息能力来理解TCP建立连接时的三次握手
TCP是一个全双工协议,意味着在Client和Server都可以接收和发送数据. 所以,从另一个角度理解建立连接的目的就是要确保双方都要知道对端的收发消息的能力是正常的
- 关于Environment类的使用
import org.springframework.core.env.Environment; EnvironmentAware 如何引用这个类1.可以通过 @Autowired织入Environm ...
- fiddler https
fiddler 里面的action 点选remove的那个 手机端清理凭据 在重新添加(在手机浏览器先输入代理的地址 下载证书 之后再安装)
- web文件夹上传下载方案
第一点:Java代码实现文件上传 FormFile file = manform.getFile(); String newfileName = null; String newpathname = ...
- POJ 3692 幼儿园做游戏 最大团 模板题
Kindergarten Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 6191 Accepted: 3052 Desc ...
- [LOJ2538][PKUWC2018]Slay the Spire:DP
分析 学会新姿势!我们可以通过调整DP顺序来体现选取物品的优先顺序! 显然选取强化牌的最优策略是倍数从高到低,能选就选,最多选\(k-1\)张,选取攻击牌的最优策略是伤害从高到低,尽量少选,但最少选\ ...
- Unity3D_(网格导航)简单物体自动寻路
NavMesh(导航网络)是3D游戏世界中用于实现动态物体自动寻路的一种技术,它将游戏场景中复杂的结构组织关系简化为带有一定信息的网格,进而在这些网格的基础上通过一系列的计算来实现自动寻路. 实现Ca ...