How to redirect to url by cancel button in django-crispy-forms?
class StudentCreateView(CreateView):
model = Student
template_name = "students/students_edit.html"
form_class = StudentCreateForm
def get_success_url(self):
return u'%s?status_message=Студент успішно створений' % reverse('home')
def post(self, request, *arg, **kwargs):
if request.POST.get('cancel_button'):
messages.info(self.request, u"Створення скасовано")
return HttpResponseRedirect(
u'%s?status_message=Створення скасовано'
% reverse('home'))
else:
messages.success(self.request, u"Студент успішно створений")
return super(StudentCreateView, self).post(
request,*arg, **kwargs)
def get_context_data(self, **kwargs):
context = super(StudentCreateView, self).get_context_data(**kwargs)
context['meta'] = u'Додавання студента'
context['headtext'] = context['meta']
return context
In this view i check in post function if is clicked cancel button
self.helper.layout[-1] = FormActions(
Submit('add_button',u'Зберегти', css_class='btn btn-primary'),
Submit('cancel_button', u'Скасувати'),
)
Only on createview submit cancel is not working properly. On click it tries to check form and crispy answers me to solve all problems on form when i want to cancel. I've changed submit to button and button cancel have no effect at all. I've found a variant on stackoverflow with adding onclick method to button, but it's not for me( When i cancel or post form on redirected window info message tells me a status of posting or canceling. So when i tried onclick method it pushed on past page, so info message wasn't shown. How to fix cancel on CreateView?
Solution 1:
Add Cancel
button and use window.location.href
within onclick
event:
self.helper.add_input(Button('cancel', 'Cancel', css_class='btn-primary',
onclick="window.location.href = '{}';".format(reverse('your-cancel-url-name'))))
Solution 2:
Another way if you prefer is to pass the HTML as is:
from crispy_forms.layout import HTML
self.helper.layout = Layout(
Fieldset(
'Title',
'field1',
'field2',
'field3'
),
FormActions(
Submit('save', 'Save'),
HTML('<a class="btn btn-primary" href="/">Cancel</a>')
)
)
Solution 3:
self.helper.layout.append(
FormActions(
submit,
Submit('cancel_button', u'Скасувати', css_class="btn btn-link"),
)
)