Django如何在一个表单上输入多个记录

时间:2015-07-14 20:23:29

标签: django django-forms django-templates django-admin modelform

我正在编写一个包含以下模型的日历应用程序:

class CalendarHour(models.Model):
    '''
    Each day there are many events, e.g. at 10 am, the framer orders
    material, etc.
    '''
    day_id = models.ForeignKey(CalendarDay)
    time = models.TimeField()
    work = models.TextField()

    def __unicode__(self):
        return 'work that took place at {work_time}'.format(work_time = self.time)

class CalendarDay(models.Model):
    '''
    Each project has so many daily logs.  But, each daily log belongs to     only one project (OneToMany relationship)
    '''
    company_id = models.ForeignKey(CompanyCalendar)
    day_date = models.DateField(auto_now_add = True) # Recording the date each log is entered in
    deadline = models.DateField() # The date for the daily log

现在,我想基于这些模型创建一个表单,其中包含有关当天的信息,但有24行条目实例,每行代表一个小时。所以,在forms.py中:     #forms.py     来自django.forms import ModelForm

class HourForm(ModelForm):
    class Meta:
         model = CalendarHour
        fields = ['entry_id', 'day_date', 'deadline']

class DayForm(ModelForm):
    class Meta:
        model = CalendarDay
        fields = ['company_id', 'day_date', 'deadline']

# In views.py:
...
class CalendarSubmit(View):
    template_name = 'calendar/submit.html'
    today_calendar = CalendarDay
    each_hour_calendar = CalendarHour

    def get(self, request):
        return render(request, self.template_name, {'form1': self.toady_calendar, 'form2':self.each_hour_calendar })

    def post(self, request):
        today = self.today_calendar(request.POST)
        each_hour = self.each_hour_calendar(request.POST)

        if today.is_valid():          
            today_calendar.save()

        if each_hour.is_valid():
            each_hour_calendar.save()

现在,我可以在模板中显示两种不同的表单,form_day和form_hour。我甚至可以重复使用form2字段24次,但是当它被发布时,第一个小时最终会在数据库中结束,其他小时将被忽略。我知道在管理员中,有一个添加多个实例的添加按钮,但我不知道如何在我的情况下实现这一点:如何在一个表单上显示两个相关模型,其中需要多次填充引用模型。 / p>

感谢任何帮助。

0 个答案:

没有答案