1👍
This means there’s a typo, or the exception happens elsewhere. Insert a debug line:
import pdb; pdb.set_trace()
before the try-except and see how the code is executed. Try PUDB or IPDB debuggers instead of the standard one. Many questions disappear when you have a debugger and can see exactly what goes wrong.
4👍
The reason the exception is not caught is because the QuerySet
has not been evaluated yet.
To validate an arbitrary (user-specified) value used for a model field or order_by
value, simply check to see if that model has a field by that name.
For example, say you have a model called Ticket
and an arbitrary GET parameter called field_name
. Here’s how you might handle creating a valid QuerySet
in views.py
:
from django.db.models import FieldDoesNotExist
from myapp.models import Ticket
def index(request):
default_field = 'id'
field_name = request.GET.get('field_name', default_field)
try:
Ticket._meta.get_field_by_name(field_name)
except FieldDoesNotExist:
field_name = default_field
tickets = Ticket.objects.all().order_by(field_name)
return ...
- [Django]-Django remove source files and generate pyc files
- [Django]-Django-import-export before_import_row to automatically create object if it does not exist
- [Django]-Unable to connect to gmail smtp linode django apache2 setup
- [Django]-How can I choose the type of view in Django Rest Framework
0👍
I faced the same problem and surely it was because the exception is later. In order to raise exception in try-catch block I modified the code in following manner:
try:
result = item_list.order_by(order_items_by)
**result = list(result)**
except FieldError:
result = item_list
This worked for me.
- [Django]-FullCalendar and django
- [Django]-Django posts and responses
- [Django]-Is Docker an alternative for 'virtualenv' while develping Django project?