我的Django项目没什么问题。我的项目有模态窗口,用户可以在其中创建新对象。该模态窗口中只有一个字段(名称)。我也使用AJAX。我想检查相同的对象是否已经存在并在该模态中显示消息。你可以看到我试图使用的代码,但不幸的是我没有看到任何消息。如何在Ajax中发送消息?
views.py :
def function_add(request, project_code):
data = dict()
project = get_object_or_404(Project, pk=project_code)
if request.method == 'POST':
form = FunctionAddForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
if Function.objects.filter(name=name, project=project_code).exists():
messages.warning(request, 'Already exist.')
else:
function = form.save(commit=False)
function.project = project
function.save()
data['form_is_valid'] = True
functions = Function.objects.filter(project=project_code)
data['html_function'] = render_to_string('project/function_list.html', {'functions': functions})
else:
data['form_is_valid'] = False
else:
form = FunctionAddForm()
context = {'project': project, 'form': form}
data['html_function_add_form'] = render_to_string('project/function_add.html', context, request=request)
return JsonResponse(data)
function_add.html :
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li class="{{ message.tags }}">{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
答案 0 :(得分:0)
最后在官方文档中我找到form.add_error
。 Click this link.
if form.is_valid():
name = form.cleaned_data['name']
if Function.objects.filter(name=name, project=project_code).exists():
form.add_error('name', 'Already exist')