简体   繁体   English

我如何将 request.user 传递到我的表单中?

[英]How would I pass request.user into my form?

I'm trying to create a posts form that lets the user create posts on my site.我正在尝试创建一个帖子表单,让用户在我的网站上创建帖子。 I've been stuck on how to pass request.user into the fields "author" and "participants".我一直被困在如何将 request.user 传递到“作者”和“参与者”字段中。 Could anybody help?有人可以帮忙吗?

Here is my view:这是我的看法:

def home(request):
    if request.method == "POST":
        form = PostForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('')

My model:我的 model:

class Post(models.Model):
    author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    body = models.TextField()
    category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True)
    participants = models.ManyToManyField(User, related_name="participants", blank=True)
    created = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-created"]

    def __str__(self):
        return self.body

And my form:我的表格:

from django.forms import ModelForm
from .models import Post

class PostForm(ModelForm):
    class Meta:
        model = Post
        fields = '__all__'

I have an example with class based views where is easy to accomplish.我有一个示例,其中基于 class 的视图很容易完成。

class PostCreateView(CreateView):
    template_name = 'Post/article_create.html'
    form_class = ArticleModelForm
    queryset = Article.objects.all()

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['form_journal'] = JournalModelForm
        return context

    def dispatch(self, request, *args, **kwargs):
        if request.method == 'POST':
            want_redirect = request.POST.get('want_redirect')
            if not want_redirect:
                self.success_url = reverse_lazy('article:article-create')
        return super(ArticleCreateView, self).dispatch(request, *args, **kwargs)

    def form_valid(self, form):
        form.instance.user = self.request.user //I think this is what you are trying to do
        return super().form_valid(form)

For the author you can use this.对于author ,您可以使用它。

def home(request):
    if request.method == "POST":
        form = PostForm(request.POST)
        form.author = request.user
        if form.is_valid():
            form.save()
            return redirect('')

For the participants you can wait until the new Post is created an then add the User对于participants ,您可以等到创建新Post ,然后添加User

if form.is_valid():
   new_post = form.save()
   new_post.participants.add(user)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM