django valid form code example

Example 1: django form_valid

If you save a form with commit=False, you must call the form's save_m2m method to save the many-to-many data. See the docs for more info.

If you decide to use the form_valid method, I would change the following things:

update the instance returned by form.save() and save it, instead of calling form.save() again.
explicitly call form.save_m2m()
return a redirect response instead of calling super().form_valid() (which will save the form again)
Putting that together, you get:

def form_valid(self, form):
    product = form.save(commit=False)
    product.user =  self.request.user
    product.location.location = user.user_location
    product.save()
    form.save_m2m()
    return redirect('/success-url/')

Example 2: django get form id from request

# html
<input type="submit" value="Reply" name ="message_frm">

# views.py
if 'message_frm' in request.POST:
    #do somethings