首页 > 解决方案 > django 在 Listview 中编辑记录

问题描述

我有一个 ListView 列出了 Question 模型中的所有问题。models.py是:

class Question(models.Model):
    question_text = models.CharField(max_length=200, unique=True)
    pub_date = models.DateField(verbose_name='date published')

    def __str__(self):
        return self.question_text

现在我希望用户可以编辑 question_text。我在views.py中试过这个:

class UpdateDirectry(generic.list.ListView, generic.edit.FormMixin):
    model = Question
    template_name = 'accounts/editable_directory.html'
    form_class = forms.EditListForm

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super(UpdateDirectry, self).get_context_data()
        context['object_list'] = Question.objects.filter(question_text__startswith='Who')
        return context

并在模板中:

<form method="post">
                {% csrf_token %}
                <table class="table">
                    <thead>
                    <tr>
                        <th scope="col">#</th>
                        <th scope="col">Q</th>
                        <th scope="col">D</th>
                    </tr>
                    </thead>
                    <tbody>
                    {% for object in object_list %}
                        <tr>
                            <th scope="row">{{ forloop.counter }}</th>
                            <td><input type="text" value="{{ object.question_text }}"></td>
                            <td>{{ object.pub_date }}</td>
                        </tr>
                    {% endfor %}
                    </tbody>
                </table>
                <input type="submit" value="Submit">
            </form>

我可以编辑 question_text 但是当我单击提交按钮时没有任何反应(只是一个白页)并且数据库中没有记录更改。如何使用提交按钮真正编辑记录?这是模板显示的内容:

在此处输入图像描述

更新 1:## 这正是我想要看到的(这张图片在 admin 中,带有 list_editable):

在此处输入图像描述

如何才能在视图中做确切的事情?

标签: django

解决方案


只需使用Django Extra Views中的 ModelFormSetView :

from extra_views import ModelFormSetView

class UpdateDirectry(ModelFormSetView):
    model = Question
    template_name = 'accounts/editable_directory.html'
    form_class = forms.EditListForm

并在您的模板中:

<form method="post">
   {{ formset }}
   <input type="submit" value="Submit" />
</form>

推荐阅读