Django一个形式/两个模型 [英] Django one form / two models

查看:155
本文介绍了Django一个形式/两个模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的跟踪事件模型:

I have a very simple model for tracking events:

class Event(models.Model):

    description = models.TextField()
    location = models.ForeignKey(Location)    
    start = models.TimeField()
    duration = models.IntegerField()
    event_date = models.DateField()
    creator = models.ForeignKey(User)

我选择了在单独的表中提取位置,以便能够执行查询:

and I opted to extract the location in a separate table in order to be able to perform queries:

class Location(models.Model):

    city = models.CharField(max_length=20)
    address = models.CharField(max_length=30).

为了插入/更新事件,创建表单的最佳方式是什么,考虑到位置应该单独完成,而不是通过ID在事件实例中链接?我想为某个位置地址和城市设置一些自动填充字段,但为了简单起见,可以将其保存在同一个表单上。

What would be the best way to create a form for inserting/updating events, taking into account that the location should be done separately and than linked via ID in the event instance? I wanted to da maybe some autocomplete field for the location address and city, but to keep it on the same form for simplicity?

推荐答案

ForeignKey生成的 ModelForm 中为 ModelChoiceField 定义自己的小部件, / code>。

Define your own widget for the ModelChoiceField in the ModelForm that is generated for the ForeignKey.

这篇关于Django一个形式/两个模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆