Ear*_*der 5 django django-templates django-forms modelform django-admin
我正在编写具有以下模型的日历应用程序:
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
Run Code Online (Sandbox Code Playgroud)
现在,我想基于这些模型创建一个包含当天信息的表单,但有 24 行条目实例,每行代表一个小时。所以,在 forms.py 中:#forms.py from 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()
Run Code Online (Sandbox Code Playgroud)
现在,我可以在模板中显示两种不同的表单,form_day 和 form_hour。我什至可以重复 form2 字段 24 次,但是当它被发布时,第一个小时在数据库中结束,其他的被忽略。我知道在管理员中,有一个添加按钮可以添加多个实例,但在我的情况下我不知道如何实现这一点:如何在一个表单上显示两个相关模型,其中引用模型需要多次填充。
任何帮助表示赞赏。
| 归档时间: |
|
| 查看次数: |
3599 次 |
| 最近记录: |