python - 带有表单的 django ListView

标签 python django django-templates django-views

我有一个 CBV,首先在我的 views.py 中使用 ListView

class InventoryListView(ListView):
    context_object_name = 'inventorys'
    model = models.Inventory

这是我的template_list.html

{% for inventory in inventorys %}
<tr>
  <td>{{ inventory.name }}</td>
  <td>{{ inventory.sn }}</td>
  <td>{{ inventory.employee.name }}</td>
  <td>{{ inventory.desc }}</td>
</tr>
{% endfor %}

它按预期返回所有数据。

但我需要添加表单。然后将一些代码添加到我的 views.py

class InventoryListView(ListView):
    template_name ='system/inventory_list.html'
    context_object_name = 'inventorys'
    model = models.Inventory

    def get(self, request):
        form = InventoryForm()
        return render(request, self.template_name, {'form': form})

    def post(self, request):
        form = InventoryForm(request.POST)

这是我的forms.py

class InventoryForm(forms.ModelForm):

    name = forms.CharField(max_length=255)
    sn = forms.DecimalField(max_digits=20, decimal_places=0)
    desc = forms.CharField(widget=forms.Textarea)
    employee = forms.ModelChoiceField(queryset=Employee.objects.all(), to_field_name="id")

    class Meta:
        model = Inventory
        fields = ('name', 'sn', 'desc', 'employee')

这是我的template_list.html

{% for inventory in inventorys %}
<tr>
  <td>{{ inventory.name }}</td>
  <td>{{ inventory.sn }}</td>
  <td>{{ inventory.employee.name }}</td>
  <td>{{ inventory.desc }}</td>
</tr>
{% endfor %}

<form method="post" action="{% url 'system:inventory_create' %}">
  {% csrf_token %}
    {{ form.as_p }}

    <input type="submit" value="Submit">
</form>

现在表单工作正常,并检查了我提交的数据库。但数据列表没有像以前一样显示,因为我添加了:

    def get(self, request):
        form = InventoryForm()
        return render(request, self.template_name, {'form': form})

到我的views.py

那么如何制作这两个作品,数据列表和表单。

最佳答案

尽量避免覆盖通用的基于类的 View 的getpost。很容易最终重复现有功能或不得不重复代码。

在这种情况下,您可以通过重写 get_context_data 方法将表单添加到模板上下文。

class InventoryListView(ListView):
    template_name ='system/inventory_list.html'
    context_object_name = 'inventorys'
    model = models.Inventory

    def get_context_data(self, **kwargs):
        context = super(InventoryListView, self).get_context_data(**kwargs)
        context['form'] = InventoryForm()
        return context

    ...

关于python - 带有表单的 django ListView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50275355/

相关文章:

python - 使用 NLTK 在 Python 中的文件的特定区域中使用 sent_tokenize?

python - Django Form 不从类 HomeForm 渲染 HTML

Django - "Include"几个模板中的一个 block ?模板标签?还有什么?

django - 如何在基于函数的 View 而不是类中使用 Django Hitcount?

python - 从另一个列表中获取项目的边界

python - wxPython:wx.PyControl可以包含wx.Sizer吗?

python - 当我包裹它时,Gtk.Cell 渲染器文本变得非常高

python - 当密码匹配时,内置 UserCreationForm 抛出 "The two password fields didn' t match"。Django==2.2.2

python - 访问 murano 仪表板时 openstack newton keystone 出现 "No module named memcache"错误

django verbose_name 不工作