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 ...
随机推荐
- anaconda安装失败
2019.10版本怎么安装都不行换了2018.10安装ok
- 解决Javaweb中HTTP500的问题
当我们新建一个Web项目后,运行时可能出现HTTP-500的错误如下图所示 一般是由于路径配置出错 即你电脑上的Tomcat版本与代码本身版本不一致或没有配置路径造成的 解决方法如下 一.鼠标右击你 ...
- Nginx解析PHP
刚安装完PHP后,nginx是无法解析的,如果输入地址会直接下载文件,需要进行如下的设置 步骤 修改/etc/nginx/sites-available/default和cat /etc/nginx/ ...
- C# checkedlistbox 控件 有bug
加入集合 private void Form2_Load(object sender, EventArgs e) { DataTable dt = new DataTable(); dt.Column ...
- 11、LineEdit与setCompleter自动补全
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QDebug>//引入打印 ...
- 需求-java web 能够实现整个文件夹的上传下载吗?
我们平时经常做的是上传文件,上传文件夹与上传文件类似,但也有一些不同之处,这次做了上传文件夹就记录下以备后用. 这次项目的需求: 支持大文件的上传和续传,要求续传支持所有浏览器,包括ie6,ie7,i ...
- HGOI20190810 省常中互测3
Problem A 夏洛特 若当前处在点$(x,y)$下一时刻可以向该点四周任意方向走动一步, 初始在$(0,0)$是否存在一条合法的路线满足下列$n$个限制: 每一个限制形如$t_i , x_i ...
- Pod初始化容器之Init Container
Init 容器的介绍 Pod能够具有多个容器,应用运行在容器里面,但是它也可能有一个或多个先于应用容器启动的 Init容器Init 容器与普通的容器非常像,除了如下两点: c Init 容器总是运行 ...
- 【BZOJ4259】 残缺的字符串
Description 很久很久以前,在你刚刚学习字符串匹配的时候,有两个仅包含小写字母的字符串A和B,其中A串长度为m,B串长度为n.可当你现在再次碰到这两个串时,这两个串已经老化了,每个串都有不同 ...
- [LOJ3120][CTS2019|CTSC2019]珍珠:生成函数+NTT
分析 容易发现\(D \leq n - 2m\)时,任意数列都满足要求,直接判掉,下文所讨论的均为\(D > n - 2m\)的情况. 考虑把两个数列合并,显然可以认为是两个带标号对象的合并,可 ...