I tried to implement a cancel button via a mixin, but fail to get the correct URL. I want to go back to the page before the CreateView if the user presses "cancel" - if that should fail, I want the user to end up in index.
views.py:
class CancelButtonMixin(object):
def post(self, request, *args, **kwargs):
if "cancel" in request.POST:
if request.META.get('HTTP_REFERER') != None:
url = request.META.get('HTTP_REFERER' , '/')
else:
url = reverse_lazy("index/")
return redirect(url)
else:
return super(CancelButtonMixin, self).post(request, *args, **kwargs)
class SomeCreateView(CancelButtonMixin, CreateView):
model = SomeModel
template_name ="projectname/some_update.html"
form_class = SomeFormsetName
success_url = reverse_lazy('index/')
forms.py:
class SomeFormsetName(ModelForm):
required_css_class = "required"
class Meta:
model = SomeModel
fields = ("one", "two", "three", "four")
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_method = 'POST'
self.helper.layout = Layout(Row(Column(Field('one')),
Column(Field('two', css_class='form-control')),
css_class='form-row'),
Submit('submit', 'Save', css_class='btn-primary'),
Submit('cancel', 'Cancel', css_class='btn-secondary', formnovalidate='formnovalidate'),
Field("three", type="hidden"),
Field("four", type="hidden"))
my problem is that the url parameter holds exactly the url I am at, not the one from the previous page. How can I correct this behavior? url in my example will refer to http://127.0.0.1:8000/some_update/2