Javascript 设置型号';s字段通过onclick(django)

Javascript 设置型号';s字段通过onclick(django),javascript,python,django,Javascript,Python,Django,这是我的代码: models.py class Photos(models.Model): username = models.CharField(max_length=50) caption = models.CharField(max_length=150, blank=True, null=True) img = models.ImageField(upload_to = 'userProfile/static/img', null=True, blank=True

这是我的代码:

models.py

class Photos(models.Model):
    username = models.CharField(max_length=50)
    caption = models.CharField(max_length=150, blank=True, null=True)
    img = models.ImageField(upload_to = 'userProfile/static/img', null=True, blank=True)
    update_date = models.DateTimeField(default=timezone.now)
    category = models.CharField(max_length=50, blank=True, null=True)
    likes_count = models.IntegerField(blank=True, null=True)

class Meta:
    managed = False
    db_table = 'photos'
这是我的js代码生成的html代码的一部分

<div class="container_card">
    <img class="container_card_image" onclick="..." src="/static/img/1/uploads/img1.jpg">
</div>

有什么方法可以得到我想要的吗?

为了得到你想要的,你需要使用ajax。 例如,jquery非常简单,很容易发出ajax请求并处理响应

此外,django视图不应将您重定向到其他页面,因为这将导致整个页面刷新。相反,您应该使用JSONResponse

def get(self, request, *args, **kwargs):
    photo = Photos.objects.get(pk=value)
    photo.likes_count += 1
    photo.save()
    return JsonResponse({'action': 'success'}, safe=False)
更高级的是,您可以使用一个完整的框架来处理json响应,例如,为了编写更少的代码,请使用一些基于类的视图,查找“ajax”。
def like(request, value):
    photo = Photos.objects.get(pk=value)
    photo.likes_count += 1
    photo.save()
    return redirect('home')
$.post( "photo/15/like", function( data ) {
  // here you handle the response.
});
def get(self, request, *args, **kwargs):
    photo = Photos.objects.get(pk=value)
    photo.likes_count += 1
    photo.save()
    return JsonResponse({'action': 'success'}, safe=False)