Django how to enter multiple records on one form

冷暖自知 提交于 2021-02-07 08:00:27

问题


I am writing a calendar app with the following models:

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

Now, I want to create a form based on these models that has the information about the day, but 24 rows of entry instances, each representing one hour. So, in 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()

Now, I can show two different forms in the template, form_day and form_hour. I can even repeat the form2 fields 24 times, but when it is posted, the first hour ends up in the database and the others are ignored. I know in the admin, there is an add buttom that adds multiple instances, but I do not know how to achieve this in my case: how to display two relating models on one form where the referring model needs to be populated multiple times.

Any help is appreciated.

来源:https://stackoverflow.com/questions/31416565/django-how-to-enter-multiple-records-on-one-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!