This is my model. I want to make a copy from my model with copy function. and update the created_time to this time and eventually return the post id.
from django.db import models
from django.utils import timezone
class Author(models.Model):
name = models.CharField(max_length=50)
class BlogPost(models.Model):
title = models.CharField(max_length=250)
body = models.TextField()
author = models.ForeignKey(Author, on_delete=models.CASCADE)
date_created = models.DateTimeField(auto_now_add=True)
def copy(self):
blog = BlogPost.objects.get(pk=self.pk)
comments = blog.comment_set.all()
blog.pk = None
blog.save()
for comment in comments:
comment.pk = None
comment.blog_post = blog
comment.save()
return blog.id
class Comment(models.Model):
blog_post = models.ForeignKey(BlogPost, on_delete=models.CASCADE)
text = models.CharField(max_length=500)
I also want copy function makes a copy from post and comments, would you help me to correct my code and update the time in my function.
Intuition
You want to update the date_created of new copied blog post to timezone.now(), instead of date_created of old blog post time, am I right?
I guess the reason of it's not updated, is because when you do blog.pk = None, the blog.date_created is still existed, so even you do blog.save(), blog.date_created is still old value.
Solution
blog.pk = None
blog.date_created = timezone.now() # Update the date_created to the current time
blog.save()
Related
I am trying to make a button on the post that when a user cliks on it, is requesting to be added to the post as an attendance and then, the author of the post has to approve that request.
Models.py
class Attending(models.Model):
is_approved = models.BooleanField(default=False)
attending = models.ManyToManyField(User, related_name='user_event_attending')
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField(blank=True)
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
attending = models.ForeignKey(Attending, on_delete=models.CASCADE, verbose_name='atending', null=True)
My problem here is that every time I writte a query for the button is giving me erros and I couldn`t figure it out how to get the reverse of the foreign key.
This is my code on my views.py
def request_event(request, pk):
previous = request.META.get('HTTP_REFERER')
try:
query = Attending.objects.get(pk=pk)
request_attending = query.post_set.add(request.user)
messages.success(request, f'Request sent!')
return redirect(previous)
except query.DoesNotExist:
return redirect('/')
Thank you very much for your help in advance!
This: query.post_set is just relationship. You cannot call method add just like that. You can add to ManyToMany relation and I believe you want to add user to Attending.attending field, not directly to Post object. Change that to:
...
query = Attending.objects.get(pk=pk)
query.attending.add(request.user)
messages.success(request, f'Request sent!')
....
| Update |
I think you should consider rearraning your relationships. If I understand your plan, you should go this way:
class Attending(models.Model):
...
attendant = models.ForeignKey(User, related_name='events_attending', on_delete=models.CASCADE)
post = models.ForeignKey('Post', on_delete=models.CASCADE)
class Post(models.Model):
...
author = models.ForeignKey(User, on_delete=models.CASCADE)
For one Post object there can be many Attending objects, then you can use relations like that:
att = Attending.objects.first()
att.post # get related Post object from ForeignKey | there is only one
post = Post.objects.first()
post.attending_set.all() # get all related Attending objects
Post.objects.get(attending=att) # get Post object that the Attending object have in ForeignKey field
user = User.objects.first()
user.post_set.all() # get all Post objects that User is author in
user.events_attending.all() # get all related Attending objects
For more check Django Docs.
So I have this model
model.py
class Post(models.Model):
uuid = models.UUIDField(primary_key=True, default=generate_ulid_as_uuid, editable=False)
created = models.DateTimeField('Created at', auto_now_add=True)
updated_at = models.DateTimeField('Last updated at', auto_now=True, blank=True, null=True)
creator = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="post_creator")
body = models.CharField(max_length=POST_MAX_LEN, validators=[MinLengthValidator(POST_MIN_LEN)])
class LikePost(AbstractSimpleModel):
creator = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="like_post")
post = models.ForeignKey(Post)
class User(AbstractDatesModel):
uuid = models.UUIDField(primary_key=True)
username = models.CharField(max_length=USERNAME_MAX_LEN, unique=True, validators=[
MinLengthValidator(USERNAME_MIN_LEN)])
created = models.DateTimeField('Created at', auto_now_add=True)
updated_at = models.DateTimeField('Last updated at', auto_now=True, blank=True, null=True)
Then I also have this annotator for returning a bunch of data outside of the Post table
annotator.py
def query_to_full_post_data_serializer(post_query_set: QuerySet):
query_set_annotated = post_query_set.annotate(
creator_username=F('creator__username'),
user_liked=F(<flag for each post in query for if user liked the post>)
reply_count=Count('postreply', distinct=True),
like_count=Count('likepost', distinct=True),
).prefetch_related(
Prefetch('photo', Photo.objects.order_by('-created')),
Prefetch('video', Video.objects.order_by('-created'))
)
return FullPostDataSerializer(query_set_annotated, many=True)
I'd like to return a field called "user_liked", which returns a boolean for each post in a query set that is True if the current logged in user has liked it or is the creator of a LikePost to a Post. When the request comes in I get the current user making the request so I can get their uuid. I'd like to use that uuid to check if the user has liked a post in the query set. How do I check if the current logged in user has liked a Post object in a query set Django?
I'm assuming you can do something like user_liked=F('likepost', filter=creator__uuid=current_user_uuid), but that wouldn't be a boolean that'd return user. If I really wanted I could do user_liked=Count('likepost, filter=creator__uuid=current_user_uuid) seems kind of inefficient though.
Sorry for my previous wrong answer.
So I'm quite rusty in the Django ORM so that query might not have best optimisation. Here is what I have come up with
Post.objects.all().annotate(liked_by_user=Q(likepost__creator=user))
The issue being that it will add duplicates for each reverse relationship it finds. That's why you should not use that and use a many to many.
For example, with a many to many, it would be as simple as
class User2(models.Model):
_id = models.BigAutoField(primary_key=True)
class Post2(models.Model):
_id = models.BigAutoField(primary_key=True)
creators = models.ManyToManyField(User2)
and now you only need
Post2.object.all().annotate(liked_by_user=Q(creator__in=[user]))
which is way better.
I been struggling with this for a while and can't seem to find an answer on any of the other threads.
I am trying to programmatically add some entries to a model in Django, the model I am trying to add to has a foreign key, and this is what I am getting hung up on.
My two models are:
class Post(models.Model):
direct_url = models.URLField(unique=True)
post_url = models.URLField()
post_title = models.CharField(max_length=300)
time_posted = models.DateTimeField(default=timezone.now)
class Comment(models.Model):
post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE)
content = models.CharField(max_length=500)
author = models.CharField(max_length=60)
date_created = models.DateTimeField(default=timezone.now)
I am trying to run some code to add some data I am pulling from another location in the DetailView (Class based view)
The code that I have for that is here:
class PostDetailView(DetailView):
model = Post
for i in hot:
if i.url.endswith(Endings):
post_to = model.objects.get(direct_url=i.url)
submission = reddit.submission(url=f'https://www.reddit.com/r/{i.permalink}')
submission.comments.replace_more(limit=None)
for comment in submission.comments.list():
Comment.objects.create(post=f'{post_to}', content=f'{comment.body}', author=f'{comment.author}', date_created=f'{datetime.datetime.fromtimestamp(comment.created)}')
I am trying to pull the reddit comments, and store them in a database. The problem I am running into is the following:
ValueError: Cannot assign "'Post object (22)'": "Comment.post" must be a "Post" instance.
What am I doing wrong?
As per this meta directive, I have turned the following comment by #Sajad into a community wiki, signalling that this question is solved.
In the last line, you're formatting post_to to string and assigning it to post which must be a Post instance and not str. Just write post=post_to.
The following code should work:
class PostDetailView(DetailView):
model = Post
for i in hot:
if i.url.endswith(Endings):
post_to = model.objects.get(direct_url=i.url)
submission = reddit.submission(url=f'https://www.reddit.com/r/{i.permalink}')
submission.comments.replace_more(limit=None)
for comment in submission.comments.list():
Comment.objects.create(post=post_to, content=f'{comment.body}', author=f'{comment.author}', date_created=f'{datetime.datetime.fromtimestamp(comment.created)}')
I am a beginner to django programming. I have been trying to add a like button to the post which is posted by the user.
In my models.py
class Post(models.Model):
post = models.CharField(max_length=500)
user = models.ForeignKey(User)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
Please help in adding a like button to my blog.
It's basic database structure, you can simply use a many to many field where you store every user that has liked/upvoted the post :
class Post(models.Model):
post = models.CharField(max_length=500)
user = models.ForeignKey(User)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
upvoted = models.ManyToManyField(User)
Recently I've started to learn Django, I've decided to make
a sample blog website. I've made Post model which creates and publish post. But there's a problem, I've no idea how to attach html markups to my Post object's attribute for instance "text" e.g
I want to bold my text, but instead text, I see "<b>text</b>".
Here is how I've made Post model:
from django.db import models
from django.utils import timezone
class Post(models.Model):
author = models.ForeignKey('auth.User')
title = models.CharField(max_length=200)
introduction = models.TextField()
text = models.TextField()
created_date = models.DateTimeField(
default=timezone.now)
published_date = models.DateTimeField(
blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
On your template file use the safe filter like this:
<h1>{{post.title | safe}}</h1>