【问题标题】:Django AJAX link not entering corresponding viewDjango AJAX 链接未进入相应视图
【发布时间】:2019-01-27 22:20:56
【问题描述】:

我希望用户可以将他们的帖子从公开列表中隐藏或再次显示。我的想法是只有一个链接,单击该链接会更改文本并更改帖子的状态。现在文字发生了变化,但帖子的状态没有变化,并且“我在这里”没有打印出来。

这是视图:

@login_required
def change_status(request):
    print("I'm here")
    if request.method == 'GET':
        post_id = request.GET['post_id']
        post = Post.objects.get(pk=post_id)
        if request.user.profile.post == post:
            if post.status == 'published':
                post.status = 'hidden'
            else:
                post.status = 'published'
            post.save()
            return HttpResponse("Success!")
        else:
            return HttpResponse("Request not from author")
    else:
        return HttpResponse("Request method is not a GET")

网址:

url(r'^status/$', views.change_status, name='change_status'),

模板:

{% extends "base_generic.html" %}

{% block content %}

<h1>{{ post.title }}</h1>
<p> {{ post.author }} - {{ post.pub_date }}</p>

{% for tag in post.tags.all %}
    <a href="{% url 'fortykwords:tag' tag.name %}">{{ tag.name }}</a>
{% endfor %}

<p>{{ post.body }}</p>
{% if post.author != request.user %}
<a href="{% url "pinax_messages:message_user_create" user_id=post.author.id %}" class="btn btn-default">Message this user</a>
{% endif %}
{% if post.author == request.user %}
    {% if post.status == 'published' %}
    <a class="likebutton" id="like{{post.id}}" href="#" data-catid="{{ post.id }}">Hide post</a>
    {% endif %}
    {% if post.status == 'hidden' %}
    <a class="likebutton" id="like{{post.id}}" href="#" data-catid="{{ post.id }}">Make post public again</a>
    {% endif %}
{% endif %}

<script type="text/javascript">
    $('.likebutton').click(function(){
    var catid;
    catid = $(this).attr("data-catid");
    $.ajax(
    {
        type:"GET",
        url: "/status",
        data:{
                 post_id: catid
        },
        success: function( data ) 
        {
            $( '#like'+ catid ).text("changed");
            $( '#message' ).text(data);
        }
     })
});
</script>
{% endblock %}

还有模特:

class Post(models.Model):

    STATUS_CHOICES = (
        ('hidden', 'Hidden'),
        ('published', 'Published'),
        ('banned', 'Banned'),
    )

    title = models.CharField(max_length=250)

    body = models.TextField(max_length=40000)

    pub_date = models.DateTimeField('date published')

    status = models.CharField(max_length=10, choices=STATUS_CHOICES,default='hidden')
    author = models.OneToOneField(User, on_delete=models.CASCADE, null=True)

    tags = tagulous.models.TagField(force_lowercase=True, max_count=15,autocomplete_view='fortykwords:post_tags_autocomplete')

    class Meta:
        ordering = ('-pk',)

    def __str__(self):
        return self.title

文本根据$( '#like'+ catid ).text("changed"); 更改,因此 jquery 正确加载,但由于它不打印“我在这里”,我假设它没有进入视图。不过,GET 请求确实发生了:[21/Aug/2018 16:46:59] "GET /status?post_id=10 HTTP/1.1" 302 0。任何想法为什么这不起作用?

提前致谢。

【问题讨论】:

  • 为什么不在模型中使用标志? hidden = models.BooleanField(default=False) 然后您可以在模板中添加一个单选按钮,如果您愿意,可以使用 ajax 来修改它的状态。
  • 使用选择变量和布尔值有什么重要区别吗?我可以在这个视图中使用你的单选按钮吗?
  • 在这种情况下,标志会更干净。无论哪种情况,您都可以使用单选按钮。
  • 我应该在 url 中有什么?
  • 帖子的状态有变化吗?您是否收到任何 http 响应数据?你登录了吗?

标签: ajax django django-templates django-views


【解决方案1】:

首先,我将其更改为 POST 请求而不是 GET 请求,因为我们毕竟是在更改数据。

<script type="text/javascript">
    $('.likebutton').click(function(){
    var catid;
    catid = $(this).attr("data-catid");
    $.ajax(
    {
        type:"POST",
        url: "/status/",
        data:{
                csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value,
                post_id: catid
        },
        success: function( data ) 
        {
            $( '#like'+ catid ).text("changed");
            $( '#message' ).text(data);
        },
        error: function(xhr, textStatus, errorThrown) {
            alert("Please report this error: "+errorThrown+xhr.status+xhr.responseText);
        }
     })
});

(当然,我在视图中添加了{% csrf_token %})。

视图最终变成:

@login_required
def change_status(request):
    print("I'm here")
    if request.is_ajax():
        post_id = request.POST['post_id']
        post = Post.objects.get(pk=post_id)
        if request.user.profile.post == post:
            if post.status == 'published':
                post.status = 'hidden'
            else:
                post.status = 'published'
            post.save()
            return HttpResponse("Success!")
        else:
            return HttpResponse("Request not from author")
    else:
        raise Http404

现在它工作得很好。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2015-09-01
  • 2020-09-01
  • 2015-03-24
  • 2019-08-12
  • 2014-12-20
  • 2014-11-18
  • 1970-01-01
  • 2011-06-12
相关资源
最近更新 更多