Home > Mobile >  How would I pass request.user into my form?
How would I pass request.user into my form?

Time:08-07

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". 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:

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__'

CodePudding user response:

For the author you can use this.

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

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

CodePudding user response:

I have an example with class based views where is easy to accomplish.

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)
  • Related