javascriptpythonhtmldjangodjango-crispy-forms

Django Crispy Forms Cancel Button That Sends User Back A Page


I have a Django Crispy Form that I want to add a cancel button to. Unlike the answers here and here, however, the user can get to the form via multiple pages, so I need to send them back to the page they came from if they cancel, not send them to a static page. How can I accomplish this?


Solution

  • Figured it out. Simple javascript embed in an anchor tag of <a href="javascript:history.back()"> got it done. Here's the full context:

    class SetForm(forms.ModelForm):
        class Meta:
            model = #blah blah
            fields = #blah blah 
    
        helper = FormHelper()
        helper.form_method = 'POST'
    
        helper.layout = Layout(
            # other inputs blah blah
    
            Row(
                Column(HTML('<a class="btn btn-warning form-group" href="javascript:history.back()">Cancel</a>')),
                Column(Submit('submit', 'Submit', css_class='btn btn-primary form-group')),
            )
        )
    

    Hope this helps save someone else the time.