【问题标题】:Unable to trigger Ajax click function in Django无法在 Django 中触发 Ajax 点击功能
【发布时间】:2020-07-19 03:39:05
【问题描述】:

尝试根据在 Django 中按下的下载链接更新模型。

请查看下面的当前代码,所以它似乎也没有登录到控制台。

来自 profile.html

{% for x in source %}
    {% if forloop.counter <= 4 %}
      <div class="content-section">
        <div class="media-body">
        <h2 class="account-heading">{{ x.video_id }}</h2>
        {% for y in records %}
          {% if x.video_id == y.sourcevideo.video_id %}
            <div class="media-body">
              <video width="320" height="240" controls>
                <source src="{{ y.highlight.url }}" type="video/mp4">
                  Your browser does not support the video tag
                </video>
                <br>
                <a class="btn" id="download" href="{{ y.highlight.url }}" data-id="{{ y.highlight_id }}" download>Download</a>
            </div>
          {% endif %}
        {% endfor %}
        </div>
      </div>
    {% endif %}
  {% endfor %}
<script type="text/javascript">
  $("#download").click(function() {
    console.log( $(this).attr("data-id") );
    var catid;
    catid = $(this).attr("data-id");
    $.ajax({
        type:"POST",
        url: "/downloaded",
        data: {
              highlight_id: catid
            },
        success: function( data )  {
          console.log(data)
        }
      })
   })
  </script>

来自views.py

def downloaded(request):
    if request.method == 'POST':
        highlight_id = request.GET('highlight_id')
        downloadedvideo = Highlight.objects.get(pk=highlight_id)
        downloadedvideo.used = True
        downloadedvideo.save()
        return
    else:
        return

urls.py

urlpatterns = [
    path('', UploadVideo.as_view(), name='upload'),
    path(r'^downloaded/$', views.downloaded, name='downloaded'),
]

非常感谢任何帮助!

更新 profile.html 这是按照此处的说明更新的配置文件:JQuery: Perform a post before a link is followed

     {% if forloop.counter <= 4 %}
      <div class="content-section">
        <div class="media-body">
        <h2 class="account-heading">{{ x.video_id }}</h2>
        {% for y in records %}
          {% if x.video_id == y.sourcevideo.video_id %}
            <div class="media-body">
              <video width="320" height="240" controls>
                <source src="{{ y.highlight.url }}" type="video/mp4">
                  Your browser does not support the video tag
                </video>
                <br>
                <a class="btn" class="download" href="{{ y.highlight.url }}" data-id="{{ y.highlight_id }}" download>Download</a>
            </div>
          {% endif %}
        {% endfor %}
        </div>
      </div>
    {% endif %}
  {% endfor %}
<script type="text/javascript">
  $(".download").click(function(ev) {
    var self = this;
    $post.('/downloaded', function() {
      window.location.href = self.href;
    });
    return false;
});

来自 Models.py

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User

class Highlight(models.Model): #record of each HIGHLIGHT video, derived from a SOURCE video
    highlight_id = models.AutoField(primary_key = True)
    creator = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
    game = models.ForeignKey(Game, null=True, on_delete=models.SET_NULL)
    date_created = models.DateTimeField(default=timezone.now)
    sourcevideo = models.ForeignKey(Video, null=True, on_delete=models.SET_NULL)
    highlight = models.FileField(upload_to = 'highlights/')
    max_energy = models.IntegerField()
    average_energy = models.IntegerField()
    highlight_length = models.IntegerField()
    quality = models.IntegerField(null=True)
    used = models.BooleanField(default=False)

    def __str__(self):
        return self.title

【问题讨论】:

  • 你不应该有多个具有相同 id 的元素。尝试改用一个类。您应该遵循此问题中关于如何在链接被关注之前执行帖子的建议stackoverflow.com/q/9256916/548562
  • 感谢 Iain,已更新为带有链接建议的课程,但是我仍然没有将布尔值更改记录到数据库中。在操作中包含更新的代码。

标签: jquery django ajax django-templates


【解决方案1】:

在您的views.py 文件中,您使用的是request.GET 而不是request.POST

由于没有 GET 请求,因此您的视图返回 None。

应该是这样的:

def downloaded(request):
    if request.method == 'POST':
        highlight_id = request.POST('highlight_id')
        downloadedvideo = Highlight.objects.get(pk=highlight_id)
        downloadedvideo.used = True
        downloadedvideo.save()
        return
    else:
        return

【讨论】:

  • 这是有道理的,现在已经更新,不幸的是我仍然没有看到数据库更新。
  • 你能添加你的models.py吗?我会试着对你的案子做一个快速的模型。另外,您是否尝试过打印出 highlight_id 并查看控制台中打印的内容?
  • 我尝试添加一个它没有触发的打印命令,这意味着 post 信号没有到达函数。我已经继续添加了 models.py 和 urls.py
猜你喜欢
  • 1970-01-01
  • 2018-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-16
  • 2018-02-13
  • 2012-08-25
  • 2014-02-26
相关资源
最近更新 更多