[Django]-How to get an object id in form_valid?

3👍

You will need to encode the primary key (or another attribute) of the message in the request. You can do that in several ways: by encoding it in the URL that is triggered for example, or by a hidden field in the form that will then be send as a POST parameter.

We can thus for example add a message_id parameter to the url:

#urls.py

urlpatterns = [
    # …,
    path('my_form/<int:message_pk>', MyFormView.as_view(), name="form-view")
]

Then in the form, we can use the parameter, by accessing it in self.kwargs:

#views.py

class MyFormView(FormView):
    form_class = CommentForm
    success_url = "/"

    def form_valid(self,form,*args,**kwargs):
        form.instance.message_id = self.kwargs['message_pk']
        self.object = form.save()
        return super(MyFormView, self).form_valid(form)

By using message_id, we avoid making an extra call to the the database to fetch the corresponding Message.

In the template you render for the MessageDetailView view, the <form> will then need to use as action URL a URL with the corresponding primary key of the message. For example if the context object name is 'message', you can pass it with:

<form action="{% url 'form-view' message_pk=message.pk %}" method="post">
    …
</form>

Leave a comment