Skip to content

Commit

Permalink
refs #107 Add a mechanism to validate data in UrlProxy
Browse files Browse the repository at this point in the history
  • Loading branch information
moumoutte committed Oct 12, 2018
1 parent 800eaa7 commit c223741
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 1 deletion.
26 changes: 25 additions & 1 deletion agnocomplete/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@
from .constants import AGNOCOMPLETE_MAX_PAGESIZE
from .constants import AGNOCOMPLETE_DEFAULT_QUERYSIZE
from .constants import AGNOCOMPLETE_MIN_QUERYSIZE
from .exceptions import AuthenticationRequiredAgnocompleteException, SkipItem
from .exceptions import AuthenticationRequiredAgnocompleteException
from .exceptions import SkipItem
from .exceptions import ItemNotFound


logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -641,3 +643,25 @@ def selected(self, ids):
)
)
return data

def validate(self, value):
"""
From a value available on the remote server, the method returns the
complete item matching the value.
If case the value is not available on the server side or filtered
through :meth:`item`, the class:`agnocomplete.exceptions.ItemNotFound`
is raised.
"""

url = self.get_item_url(value)
try:
data = self.http_call(url=url)
except requests.HTTPError:
raise ItemNotFound()

data = self.get_http_result(data)

try:
return self.item(data)
except SkipItem:
raise ItemNotFound()
4 changes: 4 additions & 0 deletions agnocomplete/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,7 @@ class SkipItem(Exception):
Occurs when Item has to be skipped when building the final Payload
"""
pass


class ItemNotFound(Exception):
pass
20 changes: 20 additions & 0 deletions agnocomplete/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@
"""
from django import forms
from django.core.exceptions import ValidationError

import six

from .core import AgnocompleteBase
from .constants import AGNOCOMPLETE_USER_ATTRIBUTE
from .widgets import AgnocompleteSelect, AgnocompleteMultiSelect
from .register import get_agnocomplete_registry
from .exceptions import ItemNotFound
from .exceptions import UnregisteredAgnocompleteException


Expand Down Expand Up @@ -246,3 +248,21 @@ def clean(self, value):
qs = super(AgnocompleteModelMultipleField, self).clean(pks)

return qs


class AgnocompleteUrlProxyMixin(object):
"""
This mixin can be used with a field which actually using
:class:`agnocomplete.core.AutocompletUrlProxy`. The main purpose is to
provide a mechanism to validate the value through the Autocomplete.
"""

def clean(self, value):
try:
return self.agnocomplete.validate(value)
except ItemNotFound:
raise ValidationError(
self.error_messages['invalid_choice'],
code='invalid_choice',
params={'value': value}
)

0 comments on commit c223741

Please sign in to comment.