Question

I have Course's model and the course consist of several file (stored only link to file, file not uploaded to the server). Number of files is unknown, user can add new links to file using JS. And this links can be edited in the form:

I receive and add new course links in the following way:

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

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

And can dynamically generate the edit form:

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)

But to save the form in this form is difficult. How to do it in the Django way?

Was it helpful?

Solution

Add an extra model:

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')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top