问题
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