Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
71 views
in Technique[技术] by (71.8m points)

Django: how to increase object value

I'm trying to implement a simple 'like' button, however, the value of the object is not changing. I have only a week of experience with django, any help is appreciated!

model>

class Mainnews(models.Model):
    author = models.ForeignKey(Author, on_delete=models.DO_NOTHING, default= True)
    title = models.CharField(max_length=200)
    description = models.TextField()
    image = models.ImageField(upload_to = 'photos/%Y/%m/%d/')
    is_published = models.BooleanField(default = True)
    publish_date = models.DateTimeField(default = datetime.now, blank = True)
    views_counter = models.IntegerField(default=0)
    likes = models.IntegerField(default=0)

    def __str__(self):
        return self.title

html>

<form action = "{% url 'like' %}" method = "POST">
    {% csrf_token %}
    <button type ='submit'>Like</button>
</form>

view>

def like(request):
    if request.method == 'POST':
        thelike = Mainnews.likes + 1
        thelike.save()

url> on like redirect to homepage

  path('news/', like, name = 'like'),
question from:https://stackoverflow.com/questions/65888903/django-how-to-increase-object-value

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

the ideal way to do it is using ajax ,so your page will not refresh every time you click the button,what missing in your question the condition of model which you want to increase ,in my code i set it news id you can change it ,check this :

<input id='news_id' name='news_id' >
<input type='button' onclick='Increase()'  name='increase' >

<srcipt>
function Increase(){
var new_id= document.getElementById("news_id").value;
$.ajax({  
    type:"POST",      
    data:JSON.stringify({'data':new_id}),    
    success:function(responsedata){
           // process on data

    }
 })

}

But if you want to use ajax you have to add a csrf_exempt decorator on your view

from django.views.decorators.csrf import csrf_exempt
#then write this before your view 
@csrf_exempt

you can use F() object to generate a SQL expression that describes the required operation without actually having to pull them out of the database into Python memory check here you can use this :

if request.is_ajax():
    new_id = json.loads(request.body.decode('utf-8'))["data"]
    _reponse = Mainnews.objects.filter(id=new_id).update(likes=F('likes') + 1)
    return JsonResponse({'data_to_return':'data'})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...