我在保存内联表单时遇到问题。它确实保存默认表单。但每当我添加新的内联表单时,它都不会保存。我错过了什么?有人能告诉我这个错误吗?谢谢。
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})
和jquery-formset.js
答案 0 :(得分:1)
我看不出任何错误,但也许您可以使用更简单的解决方案来添加新表单,这样您就不必使用jquery formset了。
Formset类有一个名为empty_form的nice属性: https://docs.djangoproject.com/en/1.4/topics/forms/formsets/#empty-form
您可以将其作为“empty_form”上下文变量传递,并将此脚本添加到模板中:
<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>
没有必要使用jquery formset :)这是我正在做的唯一更改,我没有添加任何额外的代码,django会处理所有事情。