Django从DB保存自动生成的表单

时间:2012-04-03 14:35:26

标签: django django-forms autosave

我有课程模型,课程包含多个文件(仅存储文件链接,文件未上传到服务器)。文件数量未知,用户可以使用JS添加新文件链接。此链接可以采用以下格式进行编辑:

我通过以下方式接收并添加新课程链接:

links  = request.POST.getlist('course-dl-links') 

for link in links:
    CourseFile.objects.create(
        link   = link,
        course = course
    )

并且可以动态生成编辑表单:

class CourseForm(forms.Form):
    # fields...

    def __init__(self, data = None, *args, **kwargs):
        super(CourseForm, self).__init__(data, *args, **kwargs)
        files = CourseFile.objects.filter(course__id=data.course_id).all()

        for course_file in files:
            self.fields['course-dl-links-%d' % (course_file.id, )] = forms.CharField(initial=course_file.path)

但是以这种形式保存表单很困难。 怎么用Django方式呢?

1 个答案:

答案 0 :(得分:1)

添加额外的模型:

class CourseLink(models.Model):
    course = models.ForeignKey(Course)
    link = models.CharField(max_length=255)

# Add a course link
CourseLink.objects.create(course=course, link='http://www.google.nl')

# Add another course link
CourseLink.objects.create(course=course, link='http://www.stackoverflow.com')