Dophi
Dophi

Reputation: 1

Django forms get request user

I am building using Django and now when someone tries to post something it makes him choose which user to make the post with. how can I make the value of author same as the request user. this is the form code.

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ("title", "author", "body", "header_image")

        widgets = {
            "title": forms.TextInput(attrs={"class": "form-control"}),
            "author": forms.Select(attrs={"class": "form-control"}),
            "body": forms.Textarea(
                attrs={"class": "form-control", "rows": 4, "cols": 15}
            ),
        }

and the view code

class BlogCreateView(CreateView):
    model = Post
    form_class = PostForm
    template_name = "post_new.html"
    success_url = reverse_lazy("blogs:posts")

Upvotes: 0

Views: 162

Answers (2)

elyas
elyas

Reputation: 1415

You can extend the get_initial() method in your CreateView. For example:

class BlogCreateView(CreateView):
    model = Post
    form_class = PostForm
    template_name = "post_new.html"
    success_url = reverse_lazy("blogs:posts")

    def get_initial(self):
        initial = super().get_initial()
        initial['author'] = self.request.user
        return initial

The output of method is then passed to PostForm by the FormMixin that CreateView inherits from i.e. PostForm(initial=initial).

And to make the author field hidden in your PostForm you can use a HiddenInput widget:

widgets = {
    ...
    "author": forms.HiddenInput(),
    ...
}

Upvotes: 1

Yevhen Bondar
Yevhen Bondar

Reputation: 4707

You can pass request.user to ModelForm and use them in save method like this

class PostForm(forms.ModelForm):
    class Meta:
        ...

    def __init__(self, *args, **kwargs):
        self.user: Account = kwargs.pop('user', None)
        super(PostForm, self).__init__(*args, **kwargs)

    def save(self, commit=True):
        post = super().save(commit=False)
        if commit:
            post.author = self.user     
            post.save()
        return post



class BlogCreateView(CreateView):
    ...

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs["user"] = self.request.user

Also you should remove author field from form

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ("title", "body", "header_image")

        widgets = {
            "title": forms.TextInput(attrs={"class": "form-control"}),
            "body": forms.Textarea(
                attrs={"class": "form-control", "rows": 4, "cols": 15}
            ),
        }

Upvotes: 1

Related Questions