带有表单的 django ListView

Dic*_*mbo 3 python django django-templates django-views

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

class InventoryListView(ListView):
    context_object_name = 'inventorys'
    model = models.Inventory
Run Code Online (Sandbox Code Playgroud)

这里是我的 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 %}
Run Code Online (Sandbox Code Playgroud)

它按预期返回所有数据。

但我需要用它添加表单。然后将一些代码添加到我的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)
Run Code Online (Sandbox Code Playgroud)

这里是我的 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')
Run Code Online (Sandbox Code Playgroud)

这里是我的 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>
Run Code Online (Sandbox Code Playgroud)

现在表单完美运行并检查了我提交的数据库。但是数据列表没有像以前那样显示,因为我添加了:

    def get(self, request):
        form = InventoryForm()
        return render(request, self.template_name, {'form': form})
Run Code Online (Sandbox Code Playgroud)

给我的 views.py

那么如何使两者都有效,数据列表和表单。

Ala*_*air 7

尽量避免覆盖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

    ...
Run Code Online (Sandbox Code Playgroud)