【问题标题】:Django - posting comments using AjaxDjango - 使用 Ajax 发表评论
【发布时间】:2014-04-19 15:58:45
【问题描述】:

我正在尝试使用 Ajax 发布一个非常简单的评论,当我不使用 Ajax 时,评论会发布并保存到数据库中。

到目前为止,我遇到了 501 和 403 错误以及各种不需要的行为。我已经尝试关注这些instructions,并且我已经阅读了有关 stackoverflow 上类似主题的几个答案,但无法将这些解决方案应用于我的问题。

我真的被困在这里,所以任何帮助将不胜感激。

相关模型.py:

class Photo(models.Model):
    image = models.ImageField(
        'image path', upload_to='images/%Y/%m/%d')
    image_thumb = models.ImageField(
    'thumbnail path', upload_to='images/thumbnails/%Y/%m/%d')
    name = models.CharField(max_length=100)
    description = models.CharField(max_length=150)
    avg_rating = models.FloatField('average rating', default=5.1)

    def __unicode__(self):
        return self.description

class Comment(models.Model):
    post_date = models.DateTimeField('posted')
    comment_text = models.TextField(max_length=500)
    photo = models.ForeignKey(Photo)

    def __unicode__(self):
    return self.comment_text

forms.py 中的评论表单:

class CommentForm(forms.Form):
    comment_text = forms.CharField(widget=forms.Textarea)

以及通常在views.py中处理cmets的视图:

def details(request, photo_id):
photo = get_object_or_404(Photo, pk=photo_id)
ratings_list = photo.rating_set.all().order_by('-id')

if request.method == 'POST':
    form_c = CommentForm(request.POST)

    if form_c.is_valid():
        new_comment = Comment(
            post_date = datetime.now(),
            comment_text = form_c.cleaned_data['comment_text'],
            photo = photo
        )
        new_comment.save()
        if request.is_ajax():
            return "???"
        else:
            return HttpResponseRedirect(reverse('photos:details', args= (photo_id,)))
else:
    form_c = CommentForm()

return render(request, 'photos/details.html', 
    {'photo': photo, 'ratings_list': ratings_list[:5],
    'form_c': form_c})

我已经在那里打了问号,因为现在我不知道应该重定向到哪里。

相关details.html模板sn-p:

<div id="commentSection">
{% for c in photo.comment_set.all %}
    <p>On {{c.post_date|date:"dS \o\f F, \a\t H:i"}}, someone said: </p>
    <p>{{c.comment_text}}</p>
    <br>
{% endfor %}
</div>
<form id="commentForm" name="commentForm" action="{% url 'photos:details' photo.id %}" method="post">
    {% csrf_token %}
    <p>{{form_c.non_field_errors}}
    {{form_c.comment_text.label_tag}}
    {{form_c.comment_text.errors}}</p>
    <p>{{form_c.comment_text}}</p>
    <input type="submit" value="Post Comment" />
</form>

urls.py:

from django.conf.urls import patterns, url
from photos import views

urlpatterns = patterns('',
    url(r'^rate/(?P<photo_id>\d+)/$', views.rate, name='rate'),
    url(r'^(?P<photo_id>\d+)/$', views.details, name='details'),
    url(r'^$', views.index, name='index'),
)

我添加了这个脚本以避免在尝试通过 Ajax 提交 cmets 时导致 csrf 验证失败。

<script type="text/javascript">
    $(document).ajaxSend(function(event, xhr, settings) {
        function getCookie(name) {
            var cookieValue = null;
            if (document.cookie && document.cookie != '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = jQuery.trim(cookies[i]);
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) == (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
        function sameOrigin(url) {
            // url could be relative or scheme relative or absolute
            var host = document.location.host; // host + port
            var protocol = document.location.protocol;
            var sr_origin = '//' + host;
            var origin = protocol + sr_origin;
            // Allow absolute or scheme relative URLs to same origin
            return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
                (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
                // or any other URL that isn't scheme relative or absolute i.e relative.
                !(/^(\/\/|http:|https:).*/.test(url));
        }
        function safeMethod(method) {
            return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
        }

        if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
            xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
        }
    });

这是我今天和昨天一直在努力解决的 Ajax 部分:

$(document).ready(function() {
        $('#commentForm').on('submit', function(e){
            e.preventDefault();
            var form = $(this);
            $.ajax(
                ???
            });
        });
    });

感谢您的宝贵时间。

【问题讨论】:

    标签: jquery ajax django post comments


    【解决方案1】:

    您不能从 Ajax 帖子重定向。事实上,做 Ajax 的全部意义在于防止需要重定向。您实际上需要返回一些数据:通常的方法是返回一些 JSON 来指示发生了什么。如果表单有效并且保存成功,您可能只返回一个空响应:但如果表单无效,您需要序列化错误并将其作为 JSON dict 返回。

    然后,在您的 Ajax 脚本本身中,您需要处理该信息并将其显示给用户。您的 Ajax 函数应如下所示:

    var form = $(this);
    $.post(form.attr('action'), form.serialize())
       .done(function(data) {
           // do something on success: perhaps show a "comment posted!" message.
       })
       .fail(function(xhr, status, error) {
          // do something on failure: perhaps iterate through xhr.responseJSON and
          // and insert the error messages into the form divs.
       });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-03
      • 2016-10-07
      • 1970-01-01
      • 2017-01-28
      • 2019-02-23
      相关资源
      最近更新 更多