问题描述
我在保存内联表单时遇到问题。它会保存默认表单。但是当我添加新的内联表单时,它不会保存。我失踪了什么有人能告诉我这个错误吗?谢谢。
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})
和jquery-formset.js
推荐答案
我看不到任何错误,但也许你可以使用更简单的解决方案来添加新的表单,这样就可以完全不需要使用jquery formset。
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类有好的attri bute称为empty_form:
Formset class has nice attribute called empty_form:https://docs.djangoproject.com/en/1.4/topics/forms/formsets/#empty-form
您可以将其作为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>
有..不需要使用jquery formset :)这是我正在做的唯一的变化,我不添加任何额外的代码,django照顾一切。
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.
这篇关于如何保存所有通过JavaScript添加的内联表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!