[Answered ]-Trying to save to database via ModelForm Django

1👍

You should not construct a new form when the form fails: a failed form will render the errors, such that the user knows what is going wrong, so:

def index(request):
    component = Component.objects.all()
    form = ComponentModelForm()
    if request.method == 'POST':
        form = ComponentModelForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('/maintenance')
        else:
            # Don't create a new form!
            print("didnt work!")
    context = {
        'components': component,
        'form': form,
    }
    return render(request, 'maintenance/index.html', context)

Leave a comment