[Answered ]-Django, jquery, and modelforms

0👍

Thanks for the posts I finally got things worked out. The jquery was the main issue.

$(document).ready(function() {
  $('#comment_form').submit(function(e) {
  e.preventDefault();
  $.ajax({
    type: 'POST',
    url: '{% url art.views.post %}',
    data: $('#comment_form').serialize(),
    dataType: 'json';
    success: function(){
      location.reload();
$('#comment_form').get(0).reset();
  },
  });
  return false;
  });
});

I was sending the DOM object not the actual form data to the view.

In the view I combined two functions to get the two sharing the same URL.

def post(request, pk):
  post = Post.objects.get.(pk=int(pk))
  comments = Comment.objects.filter(post=post)
  _dict = dict(post=post, comments=comments, form=Comment_form(), user=request.user)
  _dict.update(csrf(request))
  cf_obj = Comment(post = Post.objects.get(pk=pk))
  if request.method == 'POST' and request.is_ajax():
    if comment_form.is_valid():
      comment = comment_form.save(commit=True)
    else:
      raise Http404
    response = serializers.serialize('json', [comment])
    return HttpResponse(response, mimetype='application/json')
  return render_to_response('post.html', d)
👤tijko

2👍

This can helps:

this could be your view:

import json

def add_comment(request, pk):
    if request.method == 'POST' and request.is_ajax():
        comment_form = CommentForm(request.POST)
        if comment_form.is_valid():
            comment = comment_form.save(commit=True)
            comment.save()
            json_response = json.dumps({"status":"Success"})
            return HttpResponse(json_response)
        errors = {}
        for k, v in job_type_form.errors.items():
            errors[k.capitalize()] = v
        response = {
            'success': False,
            'errors': errors
        }
        return HttpResponse(json.dumps(response))

and your jquery could be like this:

$('#comment_form').submit(function() {
    var dataString = $('#comment_form').serialize();
    $.ajax({
        type: 'POST',
        url: '',// you need to put this to something like '{% url to_your_view %}'
        data: dataString,
        dataType: 'json'
        success: function(data){
            // you can access to your json object like data.status or data.something
            $('').html(data.status);
        },
    });
    return false;
});
👤pahko

Leave a comment