Reputation: 61
I am creating an upvoting system where the user upvotes, however to prevent a user from voting more than once I need to store a list of all users who have upvoted the post, I am using sqlite3 database, I would like to know how to go about storing these users in a list in my post model, I have tried several diffrent options but they havent worked.
Database: sqlite3 Python Version: 3.8 Django Version: 3.0.3
current attempt:
models.py:
class Upvote(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
current code :
def up_vote(request, pk):
current_user=request.user
pk=Post.objects.get(pk)
try:
post_instance = Post.objects.get(pk)
upvote = Upvote(post=post_instance, user=current_user)
except Upvote.DoesNotExist:
post_instance = Post.objects.get(pk)
upvote = Upvote(post=post_instance, user=current_user)
return redirect(Post(pk))
Upvotes: 0
Views: 54
Reputation: 3205
You need to have an Upvote
model with a foreign key to the Post
model. Take this as an example:
class Upvote(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
Once the user upvotes a post you create a row in the Upvote
table. You can check if the user has already upvoted the post by using a try block:
try:
upvote = Upvote.objects.get(post=some_post, user=some_user)
# User has upvoted
# Response accordingly
except Upvote.DoesNotExist:
upvote = Upvote(post=some_post, user=some_user)
# Create the upvote
Edit
Regarding your error, when you are creating or querying a new instance of a model with a foreign key, you should pass an instance of the foreign key, not the class itself. You are now:
upvote = Upvote(post=Post, user=current_user)
# Notice the Post
The Post
is the definition of the class Post
. What you should do is create/obtain an instance of the class Post
and pass it along. such as:
post_instance = Post.objects.get(pk=2) # Or whatever query you might need to use or even creating a new post
upvote = Upvote(post=post_instance, user=current_user)
Upvotes: 1
Reputation: 483
For this type of data usually is best to create a new model, for example, called "Upvotes" which will have 3 fields:
class Upvotes(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
timestamp = models.DateTimeField(auto_now_add=True)
This way you will create a table that will contain all the users that have upvoted a comment and which comment they have upvoted, including the date and time.
I hope it helps.
Upvotes: 1