【问题标题】:Django, jquery, and modelformsDjango、jquery 和模型表单
【发布时间】:2012-02-25 02:12:21
【问题描述】:

希望获得一些关于在 django 中使用 ajax 的见解和技巧。

假设我有一个函数:

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 = simplejson.dumps(comment, ensure_ascii=False)
   return HttpResponse(json, mimetype='application/json')
  return render_to_response({{ post.id }}', {'comment': comment,}), context_instance=RequestContext(request), mimetype='application/json')

我正在尝试将 cmets 发布到没有使用 ajax 函数重定向的页面:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script></javascript>
<script type="text/javascript">
  $(document).click(function()
  {
   $('#comment_form').submit(function()
   {
    var dataString = $('#comment_form').serialize();
    $.ajax({
      type: 'POST',
      url: '',
      data: dataString,
      success: function(data){
        $('').html(data);
      },
    });
    return false;
    });
  });

</script>

我相信我在这里混淆了一些东西。我试图让页面在没有重定向的情况下加载 cmets。我不需要一个确切的答案,也许只是朝着正确的方向前进。

【问题讨论】:

  • 我要求获得有关使用 ajax 和 django 发布 cmets 的见解和技巧。置顶帖,不是很清楚吗?
  • 你熟悉 django 和 ajax,我看了你的资料,好像你只用 matplot 回答问题。如果您有一些见解,请分享。
  • 我对 django 和 Ajax 的经验很少,很抱歉,但给我留下的印象是您的问题含糊不清。我可能是错的。你说得对,我一直专注于 matplotlib 问题,而且我在回答具体问题时取得了最大的成功:为什么 xxx 不起作用?
  • 我非常感谢您的回复。正如您可能会说的那样,我对这个网站很陌生。为了将来,我一定会牢记这一点。

标签: ajax django modelform


【解决方案1】:

这会有所帮助:

这可能是你的看法:

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))

你的 jquery 可能是这样的:

$('#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;
});

【讨论】:

  • 嘿,首先感谢您的回复。我要修改这段代码。至于处理要查看的 url 的 ajax 函数上的 cmets,我已经输入了“{{ post.id }}”,但是这不起作用。我正在尝试将 cmets 直接发布到页面而无需重定向。我找到了很多可以让我返回成功页面的信息,我已经能够让 cmets 发布,但我只能重定向到主页。
  • 试过这个并修改它,仍然没有工作。我将重新审视所有内容。
  • 没有错误..你能告诉我有什么问题吗?你得到了什么错误??
  • 我相信 dataType: json 需要引号
  • 我还没有尝试过返回错误的函数部分。我知道模型没有保存,但是在萤火虫上我看到帖子通过了。
【解决方案2】:

感谢您的帖子,我终于解决了问题。 jquery 是主要问题。

$(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;
  });
});

我将 DOM 对象而不是实际的表单数据发送到视图。

在视图中,我结合了两个函数来让两个函数共享同一个 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-30
    • 1970-01-01
    • 2017-06-14
    • 2015-02-12
    • 2013-08-27
    • 2010-12-29
    • 2014-04-11
    • 1970-01-01
    相关资源
    最近更新 更多