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. CUDA warning C4819的消除

    问题描述:在使用VS2010编译CUDA程序时,有很多C4819警告: warning C4819:The file contains a character that cannot be repre ...

  2. ffmpeg函数05__vcodec_decode_video2()

    vcodec_decode_video2()的作用是解码一帧视频数据

  3. PHP设置Redis key在当天有效

    本文援引自:https://blog.csdn.net/zpf_nevergiveup/article/details/81066500 $redis->set($key,$value); $e ...

  4. thinkPHP5.0.22初体验---路由,url访问

    “豪情卷起万重浪,吼吼哈哈-”一学thinkPHP才知道这是个国内研究的php web开发框架,瞬间自豪感如电流一般传遍全身 这就不多不说说 一.控制器 所谓MVC编程,无外乎函数(sometimes ...

  5. 【leetcode】1272. Remove Interval

    题目如下: Given a sorted list of disjoint intervals, each interval intervals[i] = [a, b] represents the ...

  6. Ajax异步传值总结

    Ajax异步传值 将数据从前台传向后台: 1:通过get方式,将参数在链接中,配合“?”进行传值. 实例: //前台传值方法 //触发该方法调用ajax function testAjax(yourD ...

  7. <image>的src属性的使用

    刚接触前端不久.怎么用image显示图片是个问题,怎么使用数据流还是base64呢?小小的研究一下 <image src="url"> 1.接口返回数据流,src可以直 ...

  8. 分布式-信息方式-ActiveMQ的静态网络连接

                           ActiveMQ的静态网络连接 在一台服务器上启动多个Broker步骤如下:1:把整个conf文件夹复制一份,比如叫做conf22:修改里面的 activ ...

  9. .item布局设置分割线

    <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android=" ...

  10. spring的AOP基本原理

    一.什么是AOP AOP(Aspect Oriented Programming),意思是面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术.AOP基于IoC基础,是对OOP ...