How can I automatically add the blogpost author into the member list?

試著忘記壹切 提交于 2021-01-28 08:00:43

问题


Everytime a blogpost is added, a memberlist will be generated. How do I automatically make it such that the author of the post will be included in the member list? I have added the create blog view

models.py

class BlogPost(models.Model):
 chief_title                    = models.CharField(max_length=50, null=False, blank=False, unique=True)
 body                   = models.TextField(max_length=5000, null=False, blank=False)
 members    = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name="members")
 author                     = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)


class Account(AbstractBaseUser):
 email                  = models.EmailField(verbose_name="email", max_length=60, unique=True)
 username               = models.CharField(max_length=30, unique=True)

views.py

from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin


class BlogPostMixin(object):
    model=BlogPost

class MemberListView(
    LoginRequiredMixin,
    UserPassesTestMixin,
    BlogPostMixin,
    DetailView
):
    login_url = 'must_authenticate'
    template_name = "HomeFeed/membersof_yourpost.html"

    def test_func(self):
        post = self.get_object()
        return self.request.user in post.members.all()


def create_blog_view(request):
    context = {}
    user = request.user
    if not user.is_authenticated:
        return redirect('must_authenticate')
    form = CreateBlogPostForm(request.POST or None, request.FILES or None)
    if form.is_valid():
        obj= form.save(commit = False)
        author = Account.objects.filter(email=user.email).first()
        obj.author = author
        obj.save()
        context['success_message'] = "Updated"
        return redirect('HomeFeed:main')
    context['form'] = form
    return render(request, "HomeFeed/create_blog.html", {})



回答1:


obj.save()
obj.members.add(request.user) #change is here


来源:https://stackoverflow.com/questions/65824038/how-can-i-automatically-add-the-blogpost-author-into-the-member-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!