1
Wrap the make_concordance
in try
–except
; if an exception occurs,
render the original form template for the user, along with the error information.
import re
try:
context, texts_len, results_len = make_concordance(searchterm, search_type)
except re.error as e:
form._errors['search_term'] = str(e)
del form.cleaned_data['search_term']
return render_to_response('corpus/search_test.html',
{'form': form}, context_instance=RequestContext(request))
The better way could be to make a custom cleaner, but it seems to be a bit more complicated, and I do not have Django.
1
I ended up building a custom cleaner, as Antti mentioned. This is what worked in the end:
def clean(self):
cleaned_data = self.cleaned_data
searchterm = cleaned_data.get('searchterm')
search_type = cleaned_data.get('search_type')
if search_type == 'regex':
try:
re.search(searchterm, 'randomdatastring') #this is just to test if the regex is valid
except re.error:
raise forms.ValidationError("Invalid regular expression.")
return cleaned_data
- [Answered ]-Save related models in one query
- [Answered ]-Adding new url patterns to urls.py on the fly in django
0
To build on @Sam’s comment, here’s how to capture the specific error when a regular expression fails to compile:
import re
err_message = None
try:
re.compile('(unbalanced')
except re.error as exc:
err_message = 'Uhoh: {}'.format(exc)
print err_message
Output:
Uhoh: unbalanced parenthesis
- [Answered ]-Empty QueryDict in ajax POST query – Django
- [Answered ]-Django – Follow a backward ForeignKey and then a ForeignKey (query)
- [Answered ]-From django rest framework 3 pre_save, pre_delete is not available than how to manipulate and insert requested user name in any field?
Source:stackexchange.com