[Answered ]-Django form commit=false after how to save many to many field data

1👍

I would advise not to work with commit=False in the first place:

def Add_Vendor(request):  # for vendor add
    branch_id = request.session['branch_id']
    branch_data = get_object_or_404(Branch, pk=branch_id)
    if request.method == 'POST':
        form = VendorForm(request.POST, request.FILES)
        if form.is_valid():
            form.instance.created_by = request.user
            form.instance.branch = branch_data.id
            vendor_add = form.save()
            vendor_add.branch.add(branch_data)
            return redirect('name-of-some-view')
    else:
        form = VendorForm()
    context = {
        'form': form,
        'branch_data': branch_data,
        'btn_type': 'fa fa-regular fa-plus',
        'form_title': 'Vendor Form',
        'tree_main_title': 'Vendor',
        'v_url': 'vendor_page',
        'tree_title': 'Add Form',
    }
    return render(request, 'base/vendor_master/form_vendor.html', context)

You can simplify your form by automatically adding form-control to each widget:

class VendorForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field in self.fields.values():
            attrs = field.widget.attrs
            attrs['class'] = attrs.get('class', '') + ' form-control'

    class Meta:
        model = Vendor
        exclude = ['created_by', 'branch']

Note: In case of a successful POST request, you should make a redirect
[Django-doc]

to implement the Post/Redirect/Get pattern [wiki].
This avoids that you make the same POST request when the user refreshes the
browser.


Note: You can set a field editable=False [Django-doc]. Then the field does not show up in the ModelForms and ModelAdmins by default. In this case for example with created_by.


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.


Note: Please do not pass messages manually to the template. Django has the messages framework [Django-doc], which allows to add messages to the request, which will then be delivered the next time a template renders these messages. This makes delivering multiple messages convenient, as well as setting different log levels to the messages.

Leave a comment