Django:如何处理CreateView中针对UNIQUE约束的错误消息失败
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django:如何处理CreateView中针对UNIQUE约束的错误消息失败相关的知识,希望对你有一定的参考价值。
我有一个基于通用类的createview,它会生成“唯一约束失败”错误。我能够处理并将其重定向到相同的createview表单。但是,我需要向createview发送一条错误消息,说“名称已存在”。我如何实现这一目标。
model.py
class Release(models.Model):
name = models.CharField(max_length=200, db_index=True)
class Feature(models.Model):
release = models.ForeignKey(Release,
on_delete=models.SET_NULL, null=True, related_name='features')
name = models.CharField(max_length=200, db_index=True)
class Meta:
unique_together = ('name', 'release')
view.py
class FeatureCreate(CreateView):
model = Feature
fields = ['name', 'summary']
def form_valid(self, form):
form.instance.release_id = self.kwargs.get('pk')
from django.db import IntegrityError
from django.http import HttpResponseRedirect
try:
a = super(FeatureCreate, self).form_valid(form)
except IntegrityError as e:
if 'UNIQUE constraint failed' in e.args[0]:
return HttpResponseRedirect(reverse_lazy('feature-create', args=(form.instance.release_id,)))
return a
url.py:
path('release/<int:pk>/feature/create/', views.FeatureCreate.as_view(), name='feature-create'),
feature_form.html:
{% block content %}
<form action="" method="post">
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<input type="submit" value="Submit">
<input type="button" value="Cancel" onclick="history.back()">
</form>
{% endblock %}
欢迎提出任何建议。请帮助。
答案
from django.contrib import messages
#your view
#...
messages.info(request, _("your information"))
#...
return ...
并将'django.contrib.messages'添加到settings.py中的INSTALLED_APP列表中>
以上是关于Django:如何处理CreateView中针对UNIQUE约束的错误消息失败的主要内容,如果未能解决你的问题,请参考以下文章