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
Documentmodel) - Select one of their
user_defined_codechoices from a drop down list (populated by theUserDefinedCodemodel) - Type in a
unique_code(stored in theCodemodel)
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 ...
随机推荐
- SpringBoot项目多模块打包与部署【pom文件问题】
[bean的pom] [user的pom] 特别注意,user模块因为有返回jsp页面和web相关,所以需要加入web依赖. chapter23 com.yuqiyu 1.0.0 4.0.0 com. ...
- Java介绍、环境的搭建及结构化程序
一.Java 简介及环境配置: JDK和JRE的区别:JRE(Java Runtime Environment)Java运行时环境有些程序运行需要Java环境,因此JRE只是给客户端使用的. JDK( ...
- 在JavaScript中,++在前和++在后有什么区别
一.++可以与输出语句写在一起,++写在变量前和写在变量后不是一个意思++ i 和 i ++ 区别在于运算顺序和结合方向. 在JavaScript中有两种自加运算,其运算符均为 ++,功能为将运算符自 ...
- 如何在输入命令行npm run dev 之后vue项目自动在浏览器打开
使用代码编辑器打开vue项目代码,在config文件夹里面找到index.js 将里面的:autoOpenBrowser: false, 修改为 :autoOpenBrowser: true, 这个方 ...
- http学习--常用请求方法和响应状态码
常用的http请求方法: GET方法:请求服务器资源,并返回 POST方法:向指定资源提交数据进行处理请求(比如说表单,上传文件等).数据被包含在请求体中.POST请求可能会导致新的资源建立或已有资源 ...
- yum 安装 mongodb
1 .添加阿里源 vi /etc/yum.repos.d/mongodb.repo [mongodb-org] name=MongoDB Repository baseurl=http://mirro ...
- C# AVI Image 转换
AVI视频库 http://download.csdn.net/download/qc_id_01/9970151 Avi视频文件的编码有很多,这个库只支持部分Avi文件,有些Avi文件不支持,具体哪 ...
- 'vue' 不是内部或外部命令,也不是可运行的程序 或批处理文件
解决方案:找到npm i xxx -g 下载后存放的路径,将路径添加到环境变量中,即可.1.npm config list 查看一下npm 的配置信息 2.打开路径看看里面的命令.window用户wi ...
- Python3学习笔记(十二):闭包
闭包定义: 在一个外函数中定义了一个内函数,内函数里引用了外函数的临时变量,并且外函数的返回值是内函数的引用.这样就构成了一个闭包. 我们先来看一个简单的函数: def outer(a): b = 1 ...
- STS插件_ springsource-tool-suite插件各个历史版本
目前spring官网(http://spring.io/tools/sts/all)上可下载的spring插件只有:springsource-tool-suite-3.8.4(sts-3.8.4).但 ...