[Answered ]-Django form's not valid

1👍

You always add the warning, regardless whether the form is valid or not, this does not make much sense.

That being said, you are writing too much boilerplate code, you can use a CreateView which will eliminate most of the boilerplate code:

from django.shortcuts import get_object_or_404
from django.urls import reverse_lazy

class RoomInsideView(View):
    template_name = 'room/room_inside.html'
    form_class = SendMessageForm
    success_url = reverse_lazy('name-of-some-view')

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        context['room'] = get_object_or_404(Room, pk=self.kwargs['room_id'], is_private=False)
        return context

    def form_invalid(self, form):
        messages.error(request, 'form not valid', 'warning')
        return super().form_invalid(form)

    def form_valid(self, form):
        form.instance.room_id = self.kwargs['room_id']
        form.instance.user = self.request.user
        return super().form_valid(form)

The name-of-some-view should be replaced with the name of the view where the view should redirect to in case of a successful POST request, this is done to implement the Post/Redirect/Get architectural pattern [wiki].


Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

Leave a comment