django - 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 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>
推荐阅读
- docker - 将 docker 应用程序从我的主机笔记本电脑备份和还原到另一台笔记本电脑
- c# - C# 与 PowerShell。如何获取详细的异常信息?
- javascript - 如何将文本从 html 输入写入 json 文件?
- python - 如何对 Pandas Pivot 表中的值进行排序?
- python - 获取熊猫中基于查询的选择的对应列的简洁方法
- r - 线性模型结果写入 excel 文件
- android - 以编程方式设置 BubbleTextView 对齐
- ios - 尝试在 Moya 中将 [JSON] 作为参数值发送时出错
- windows - 适用于 Windows 10 和卷的 Docker
- c# - 如何在c#中通过反射更新数据库