经过几天的研究,我仍然对创建一个涉及4个表格的表格感到困惑,这些表格都是通过ForiegnKey连接的。我甚至不确定我是否使用了正确的方法。
我应该使用forms.Form还是ModelForm?我正在寻找的我确信很常见,但我的所有尝试都是徒劳的。由于所有4个表都是相关的,所以我觉得这比它应该更复杂。
要点:要创建工作订单,请选择一个建筑物,然后在该建筑物内挑选一个单元,然后从该单元内的租户中选择一个调用者。然后在视图中收集所有数据并保存WorkOrder。
使用Django 1.6
# models.py
class Building(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=200)
...
def __unicode__(self):
return self.name
class Unit(models.Model):
name = models.ForeignKey(Building)
unit = models.CharField(max_length=30)
...
def __unicode__(self):
return self.unit
class Tenant(models.Model):
unit = models.ForeignKey(Unit)
name = models.ForeignKey(Building)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
...
def __unicode__(self):
return u'%s %s' % (self.first_name, self.last_name)
class WorkOrder(models.Model):
name = models.ForeignKey(Building)
unit = models.ForeignKey(Unit)
ordernum = models.AutoField(primary_key=True)
...
def __unicode__(self):
return self.unit
forms.py
# forms.py
class WorkOrderForm(forms.Form):
building_choice = forms.ModelChoiceField(queryset=Building.objects.all(),
empty_label='Pick a building',
)
def __init__(self, *args, **kwargs):
super(WorkOrderForm, self).__init__(*args, **kwargs)
self.fields['building_choice'].label = 'Building'
unit_choice = forms.ModelChoiceField(queryset=Unit.objects.(????),
empty_label='Pick a unit',
)
def __init__(self, *args, **kwargs):
super(WorkOrderForm, self).__init__(*args, **kwargs)
self.fields['unit_choice'].label = 'Unit'
caller_choice = forms.ModelChoiceField(queryset=Tenant.objects.(????),
empty_label='Who called',
)
def __init__(self, *args, **kwargs):
super(WorkOrderForm, self).__init__(*args, **kwargs)
self.fields['caller_choice'].label = 'Tenant'
views.py(不完整)
#views.py
def create(request):
if request.method == 'POST':
form = WorkOrderForm(request.POST)
if form.is_valid():
workorder = WorkOrder(name=form.cleaned_data['name'],
unit=form.cleaned_data['unit'],
call_date=form.cleaned_data['call_date'],
caller=form.cleaned_data['caller'],
problem_desc=form.cleaned_data['problem_desc'])
workorder.save()
return HttpResponseRedirect('/workorder/')
else:
form = WorkOrderForm()
return render(request, 'workorder_form.html', {'form': form})
如果有人能让我知道正确的方法,我将永远感激不尽。
答案 0 :(得分:1)
自从我发布这个问题以来已经有一段时间了,但我找到了满足我需求的django包django-clever-selects。文档和示例项目得到了很好的评论。感谢早先帮助过的所有人。