0

I have little problem in my Django project. My project has modal window where users create new object. There is only one field (name) in that modal window. Also I use AJAX. I am tring to check if the same object is already exist and show message in that modal. You can see code which I tried to use but unfortunatly I dont see any messages. How can I make message in 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 %}
Nurzhan Nogerbek
  • 4,806
  • 16
  • 87
  • 193
  • Possible duplicate: http://stackoverflow.com/questions/11276100/how-do-i-insert-a-django-form-in-twitter-bootstrap-modal-window & this http://stackoverflow.com/questions/11944887/jquery-ajax-django-present-form-in-a-bootstrap-modal-and-re-show-if-validati?noredirect=1&lq=1 – Abijith Mg Mar 28 '17 at 06:50
  • @AbijithMg its not the same question. We have differents aims. – Nurzhan Nogerbek Mar 28 '17 at 06:54
  • Your context dict doesn't have a key named 'messages' – Xiao Mar 28 '17 at 08:09

1 Answers1

0

Finally in official documentation I found 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')
Nurzhan Nogerbek
  • 4,806
  • 16
  • 87
  • 193