Robert Garcia
Robert Garcia

Reputation: 35

How do i save all inline forms that adding by javascript?

I am having problem saving inline forms. It does save default forms. But whenever i add new inline forms, It doesnt save. What am i missing? can anyone show me the mistake? Thank you.

models.py

class Student(models.Model):

    name = models.CharField(max_length=20)

    def __unicode__(self):
        return self.name

class Course(models.Model):

    student = models.ForeignKey(Student)
    course = models.CharField(max_length=18)

forms.py

class StudentForm(forms.ModelForm):


    class Meta:
        model = Student

class CourseForm(forms.ModelForm):

    class Meta:
        model = Course


CourseFormset = inlineformset_factory(Student,Course, extra=1)

views.py

class CourseCreateView(View):

    def post(self,request, *args, **kwargs):
        form = StudentForm(request.POST)


        if form.is_valid():
            std = form.save(commit=False)

            formset = CourseFormset(request.POST, instance=std)
            if formset.is_valid():
                    std.save()
                    formset.save()


        return HttpResponseRedirect("/course/list")


    def get(self, request,*args, **kwargs):

        studentform = StudentForm()
        formset = CourseFormset()
        return render(request,'example/course_form.html', {'formset': formset, 'studentform': studentform})

and the jquery-formset.js

https://dpaste.de/sVPT0/

Upvotes: 1

Views: 812

Answers (1)

mariodev
mariodev

Reputation: 15549

Well I can't see any mistakes, but maybe you can use easier solution to add new form, so that you won't have to use jquery formset at all.

Formset class has nice attribute called empty_form: https://docs.djangoproject.com/en/1.4/topics/forms/formsets/#empty-form

You can pass it as "empty_form" context variable and add this script inside template:

<script type="text/template" id="row-template">
  <tr>
    {% for field in empty_form %}
      <td>{{ field }}</td>
    {% endfor %}
  </tr>
</script>

<script type="text/javascript">
  var formset = {};

  $(function() {
    $('.btn-add-extra-form').click(function() {
      formset.$total = $('#id_rows-TOTAL_FORMS');
      formset.$initial = $('#id_rows-INITIAL_FORMS');
      formset.templateRowStr = $('#row-template').html();

      formset.newTotal = parseInt(formset.$total.val());
      formset.appendRowStr = formset.templateRowStr.replace(/__prefix__/g, formset.newTotal);
      formset.$total.val(formset.newTotal + 1);
      $('.table-inline-rows tbody').append(formset.appendRowStr);
    });
  });
</script>

There.. no need to use jquery formset :) and that's the only changes I'm making, I'm not adding any extra code, django takes care of everything.

Upvotes: 1

Related Questions