[Answered ]-Django, jquery, and modelforms


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

$(document).ready(function() {
  $('#comment_form').submit(function(e) {
    type: 'POST',
    url: '{% url art.views.post %}',
    data: $('#comment_form').serialize(),
    dataType: 'json';
    success: function(){
  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)
  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)
      raise Http404
    response = serializers.serialize('json', [comment])
    return HttpResponse(response, mimetype='application/json')
  return render_to_response('post.html', d)


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)
            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();
        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
    return false;

Leave a comment