【问题标题】:Django populate formset data when editing formDjango在编辑表单时填充表单集数据
【发布时间】:2018-09-06 07:40:00
【问题描述】:

我有两个型号ChapterChapterQuestion

我正在使用formset 创建多个ChapterQuestion 记录,同时创建Chapter 记录,它工作正常。

但是,当我编辑表单时,它不会填充表单集值。

我正在使用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 个空字段集。

如何使用表单集填充已保存的数据?

【问题讨论】:

    标签: django django-forms


    【解决方案1】:

    您需要传递实例,如下所示: https://docs.djangoproject.com/en/1.11/topics/forms/modelforms/#inline-formsets

    在你的情况下:

    context['chapter_questions'] = ChapterQuestionFormSet(instance=self.object)
    

    【讨论】:

      猜你喜欢
      • 2018-12-12
      • 1970-01-01
      • 2021-01-29
      • 1970-01-01
      • 2012-08-14
      • 2022-10-15
      • 2022-10-20
      • 2020-07-25
      • 1970-01-01
      相关资源
      最近更新 更多