我有两个模型Chapter
和ChapterQuestion
。
我正在使用formset
创建多个ChapterQuestion
记录,同时创建Chapter
记录并且工作正常。
但是,当我编辑表单时,它不会填充formset值。
我正在使用UpdateView
来更新记录
class EditChapter(UpdateView):
model = Chapter
form_class = ChapterForm
template_name = 'courses/chapter/edit_chapter.html'
def get_context_data(self, **kwargs):
context = super(EditChapter, self).get_context_data(**kwargs)
course = Course.objects.get(pk=self.kwargs['course_id'])
if course is None:
messages.error(self.request, 'Course not found')
return reverse('course:list')
context['course'] = course
if self.request.POST:
context['chapter_questions'] = ChapterQuestionFormSet(self.request.POST)
else:
context['chapter_questions'] = ChapterQuestionFormSet()
return context
def form_valid(self, form):
context = self.get_context_data()
chapter_questions = context['chapter_questions']
with transaction.atomic():
self.object = form.save()
if chapter_questions.is_valid():
chapter_questions.instance = self.object
# chapter_questions.instance.created_by = self.request.user
chapter_questions.save()
return super(EditChapter, self).form_valid(form)
def get_success_url(self):
return reverse('course:detail', kwargs={'pk': self.kwargs['course_id']})
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(self.__class__, self).dispatch(request, *args, **kwargs)
urls.py
包含
path('<course_id>/chapter/<uuid:pk>/edit', EditChapter.as_view(), name='edit_chapter'),
在模板中,我正在使用crispy form
<form method="POST" role="form" class="form">
{% csrf_token %}
<h3 class="panel-title">Chapter Detail</h3>
<label for="chapter-name">Chapter Name</label>
<input name="name"
placeholder="Chapter Name"
value="{{ chapter.name }}"
id="chapter-name">
<h3 class="panel-title">Add Question to Chapter</h3>
{{ chapter_questions|crispy }}
</form>
{{ chapter_questions|crispy }}
呈现表单字段,但字段为空。
forms.py
from django.forms import ModelForm, inlineformset_factory
from courses.models import Chapter, ChapterQuestion
class ChapterForm(ModelForm):
class Meta:
model = Chapter
fields = ['name']
class ChapterQuestionForm(ModelForm):
class Meta:
model = ChapterQuestion
fields = ['word', 'definition']
ChapterQuestionFormSet = inlineformset_factory(Chapter, ChapterQuestion,
form=ChapterQuestionForm, extra=2)
这会为ChapterQuestion
呈现2个空字段。
如何使用formset填充已保存的数据?
答案 0 :(得分:0)
您需要传递实例,如下所示: https://docs.djangoproject.com/en/1.11/topics/forms/modelforms/#inline-formsets
在你的情况下:
context['chapter_questions'] = ChapterQuestionFormSet(instance=self.object)