问题描述
我有一个基于通用类的createview,它会生成唯一约束失败错误。我能够处理并将其重定向到相同的createview表单。但是,我需要向createview发送一条错误消息,说名称已存在。我该如何实现。
I have a generic class based createview, which generates "UNIQUE constraint failed" error. I am able to handle this and redirect it to the same createview form. However i need to send an error msg to the createview saying 'Name already exists'. How to i achieve this.
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:
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 %}
欢迎提出任何建议。
请帮助。
Any suggestions is welcome. Please help.
推荐答案
from .models import Feature, Release
from django.forms.models import modelform_factory
from django.views.generic.edit import CreateView
from django.contrib import messages
class FeatureCreate(CreateView):
form_class = modelform_factory(Feature, fields=('name', 'release'))
template_name = 'handle_images/feature_form.html'
success_url = '/feature/'
def post(self, request, *args, **kwargs):
# super().post() maybe raise a ValidationError if it is failure to save
response = super().post(request, *args, **kwargs)
# the below code is optional. django has responsed another erorr message
if not self.object:
messages.info(request, 'UNIQUE constraint failed.')
return response
class ReleaseCreate(CreateView):
form_class = modelform_factory(Release, fields=('name',))
template_name = 'handle_images/feature_form.html'
success_url = '/release/'
并且:
将'django.contrib.messages'添加到settings.py中的INSTALLED_APP列表中将前缀{%扩展'admin / base.html'%}到模板以显示messages.info
and: add 'django.contrib.messages' to INSTALLED_APP list in settings.py add prefix {% extends 'admin/base.html' %} to template for showing messages.info
这篇关于Django:如何处理针对唯一约束的CreateView中的错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!