表单无效时,Django CreateView重定向到ListView

时间:2018-05-10 16:27:49

标签: django django-views

我有views.py喜欢这个

class InventoryListView(ListView):
    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

class InventoryCreateView(CreateView):
    fields = ('name', 'sn', 'desc', 'employee')
    model = models.Inventory  

和我的models.py

class Inventory(models.Model):
    name = models.CharField(max_length=255)
    sn = models.DecimalField(max_digits=20, decimal_places=0)
    desc = models.TextField(blank=True, null=True, default='Empty')
    employee = models.ForeignKey(Employee, null=True, on_delete=models.SET_NULL, related_name='employee')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True, null=True)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse("system:inventory_list")

和我的urls.py

url(r'^invn/$',views.InventoryListView.as_view(), name='inventory_list'),
url(r'^invn/create$',views.InventoryCreateView.as_view(), name='inventory_create'),

和我的inventory_list.html

{% for inventory in inventorys %}
  <td>{{ inventory.name }}</td>
{% endfor %}

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

如果表格有效,则表现良好。

但是如果表单无效,它会重定向到inventory_form.html,因为Django TemplateDoesNotExist需要CreateView(CMIIW)才会导致inventory_form.html

简单的解决方案创建inventory_form.html,但这不是我想要的。

如果表单无效并有错误消息,如何将其重定向到我的ListView

1 个答案:

答案 0 :(得分:0)

可以在form_invalid()方法中重定向用户,并使用Django Message Framework提醒用户(错误消息)。

from django.contrib import messages
from django.shortcuts import redirect

class InventoryCreateView(CreateView):
    fields = ('name', 'sn', 'desc', 'employee')
    model = models.Inventory  


    def form_invalid(self, form):
        'form is invalid'
        messages.add_message(self.request,messages.WARNING,"Form is invalid")
        return redirect('inventory_list')

要在模板中检索消息:

{% if messages %}
    <ul class="messages">
    {% for message in messages %}
      <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
    {% endfor %}
    </ul>
{% endif %}