'Django Model: ForeignKey and Relations

I have 2 models:

class Post(models.Model):
   pass

class Vote(models.Model):
      post = models.ForeignKey(Post)
      user = models.ForeignKey(django.contrib.auth.models.User)

I want to allow logged User to make a vote on Post's Admin site. I think about 2 solution as below:

  1. Add 'voted' field to Post model.
  2. Customize Post's Admin forms by add a Button control and implement do_vote() function in Post model to call when the Button is clicked.

Do you have any other solutions? Additionally, I don't know how to implement 2 above solutions. Could you give me some lines of code?



Solution 1:[1]

On your PostAdmin class you can add an action:

class PostAdmin(admin.ModelAdmin):
    ...
    actions = [vote_on_post,]

and then you can implement the vote_on_post method based on this documentation, should be something like this:

@admin.action(description='Vote on action')
def vote_on_post(modeladmin, request, queryset):
    user = request.user
    for post in queryset:
        Vote.objects.create(user=user,post=post)

You probably want to add logic to prevent multiple votes from the same user on the same post, etc.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DanielM