在django CreateView中,我有两个应该是唯一的字段。
即。说user和unique_name
要捕获完整性错误(当用户具有重复的unique_name时),我已经编写了try,除了正常的Django函数。它适用于HTML表单提交。 但是,当我尝试使用Ajax提交表单时,我找不到捕获错误的方法。
class DataCreate(AjaxableResponseMixin,CreateView):
model = Prescriptions
fields = ['user','unique_name','x','y','z']
success_url = reverse_lazy('some url')
def form_valid(self, form):
form.instance.user = self.request.user
try:
return super(DataCreate, self).form_valid(form)
except IntegrityError:
form.add_error('unique_name','You already have a user by that name')
return render_to_response('html')
def save(self):
request.session['unique_name'] = self.object.unique_name
super(DataCreate,self).save() </code>
Note : Ajax Mixin is taken from Django Documentation(1.7) as follows.
class AjaxableResponseMixin(object):
"""
Mixin to add AJAX support to a form.
Must be used with an object-based FormView (e.g. CreateView)
"""
def form_invalid(self, form):
response = super(AjaxableResponseMixin, self).form_invalid(form)
if self.request.is_ajax():
return JsonResponse(form.errors, status=400)
else:
return response
def form_valid(self, form):
# We make sure to call the parent's form_valid() method because
# it might do some processing (in the case of CreateView, it will
# call form.save() for example).
response = super(AjaxableResponseMixin, self).form_valid(form)
if self.request.is_ajax():
data = {
'pk': self.object.pk,
}
return JsonResponse(data)
else:
return response
def form_valid(self, form):
form.instance.user = self.request.user
try:
return super(DataCreate, self).form_valid(form)
except IntegrityError:
form.add_error('unique_name','You already have a user by that name')
return render_to_response('html')
def save(self):
request.session['unique_name'] = self.object.unique_name
super(DataCreate,self).save() </code>
答案 0 :(得分:1)
您应该在except子句中返回form_invalid
而不是使用render_to_response
def form_valid(self, form):
form.instance.user = self.request.user
try:
return super(DataCreate, self).form_valid(form)
except IntegrityError:
form.add_error('unique_name','You already have a user by that name')
return self.form_invalid(form)