Skip to content

Commit

Permalink
reformat to new ruff rules
Browse files Browse the repository at this point in the history
Increase ruff linter strictness and apply fixes
  • Loading branch information
crucialfelix committed Sep 14, 2024
1 parent 7e8bffb commit 55ee7fe
Show file tree
Hide file tree
Showing 26 changed files with 453 additions and 386 deletions.
1 change: 1 addition & 0 deletions ajax_select/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""JQuery-Ajax Autocomplete fields for Django Forms."""

__version__ = "3.0.2"
__author__ = "crucialfelix"
__contact__ = "crucialfelix@gmail.com"
Expand Down
10 changes: 3 additions & 7 deletions ajax_select/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@


class AjaxSelectAdmin(admin.ModelAdmin):
"""in order to get + popup functions subclass this or do the same hook inside of your get_form"""
"""in order to get + popup functions subclass this or do the same hook inside of your get_form."""

def get_form(self, request, obj=None, **kwargs):
form = super().get_form(request, obj, **kwargs)
Expand All @@ -20,13 +20,9 @@ def get_formset(self, request, obj=None, **kwargs):
return fs


class AjaxSelectAdminTabularInline(
AjaxSelectAdminInlineFormsetMixin, admin.TabularInline
):
class AjaxSelectAdminTabularInline(AjaxSelectAdminInlineFormsetMixin, admin.TabularInline):
pass


class AjaxSelectAdminStackedInline(
AjaxSelectAdminInlineFormsetMixin, admin.StackedInline
):
class AjaxSelectAdminStackedInline(AjaxSelectAdminInlineFormsetMixin, admin.StackedInline):
pass
5 changes: 3 additions & 2 deletions ajax_select/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@ class AjaxSelectConfig(AppConfig):
Your LookupClass subclass may register itself.
"""

name = 'ajax_select'
verbose_name = 'Ajax Selects'
name = "ajax_select"
verbose_name = "Ajax Selects"

def ready(self):
from ajax_select.registry import registry

registry.load_channels()
60 changes: 24 additions & 36 deletions ajax_select/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,8 @@ def render(self, name, value, attrs=None, renderer=None, **_kwargs):
try:
obj = objs[0]
except IndexError as e:
raise Exception(f"{lookup} cannot find object:{value}") from e
msg = f"{lookup} cannot find object:{value}"
raise Exception(msg) from e
current_repr = lookup.format_item_display(obj)
initial = [current_repr, obj.pk]

Expand All @@ -117,9 +118,7 @@ def render(self, name, value, attrs=None, renderer=None, **_kwargs):
"func_slug": self.html_id.replace("-", ""),
"add_link": self.add_link,
}
context.update(
make_plugin_options(lookup, self.channel, self.plugin_options, initial)
)
context.update(make_plugin_options(lookup, self.channel, self.plugin_options, initial))
templates = [
f"ajax_select/autocompleteselect_{self.channel}.html",
"ajax_select/autocompleteselect.html",
Expand All @@ -142,12 +141,12 @@ class AutoCompleteSelectField(forms.fields.CharField):
def __init__(self, channel, *args, **kwargs):
self.channel = channel

widget_kwargs = dict(
channel=channel,
help_text=kwargs.get("help_text", _(as_default_help)),
show_help_text=kwargs.pop("show_help_text", True),
plugin_options=kwargs.pop("plugin_options", {}),
)
widget_kwargs = {
"channel": channel,
"help_text": kwargs.get("help_text", _(as_default_help)),
"show_help_text": kwargs.pop("show_help_text", True),
"plugin_options": kwargs.pop("plugin_options", {}),
}
widget_kwargs.update(kwargs.pop("widget_options", {}))
kwargs["widget"] = AutoCompleteSelectWidget(**widget_kwargs)
super().__init__(*args, **kwargs, max_length=255)
Expand All @@ -161,12 +160,12 @@ def clean(self, value):
# or your channel is faulty
# out of the scope of this field to do anything more than
# tell you it doesn't exist
raise forms.ValidationError(f"{lookup} cannot find object: {value}")
msg = f"{lookup} cannot find object: {value}"
raise forms.ValidationError(msg)
return objs[0]
else:
if self.required:
raise forms.ValidationError(self.error_messages["required"])
return None
if self.required:
raise forms.ValidationError(self.error_messages["required"])
return None

def check_can_add(self, user, model):
_check_can_add(self, user, model)
Expand Down Expand Up @@ -219,11 +218,7 @@ def render(self, name, value, attrs=None, renderer=None, **_kwargs):
lookup = registry.get(self.channel)

values = list(value)
objects = (
values
if all([isinstance(v, Model) for v in values])
else lookup.get_objects(values)
)
objects = values if all(isinstance(v, Model) for v in values) else lookup.get_objects(values)

current_ids = pack_ids([obj.pk for obj in objects])

Expand All @@ -243,9 +238,7 @@ def render(self, name, value, attrs=None, renderer=None, **_kwargs):
"func_slug": self.html_id.replace("-", ""),
"add_link": self.add_link,
}
context.update(
make_plugin_options(lookup, self.channel, self.plugin_options, initial)
)
context.update(make_plugin_options(lookup, self.channel, self.plugin_options, initial))
templates = [
f"ajax_select/autocompleteselectmultiple_{self.channel}.html",
"ajax_select/autocompleteselectmultiple.html",
Expand Down Expand Up @@ -377,9 +370,7 @@ def render(self, name, value, attrs=None, renderer=None, **_kwargs):
"extra_attrs": mark_safe(flatatt(final_attrs)),
"func_slug": self.html_id.replace("-", ""),
}
context.update(
make_plugin_options(lookup, self.channel, self.plugin_options, initial)
)
context.update(make_plugin_options(lookup, self.channel, self.plugin_options, initial))
templates = [
f"ajax_select/autocomplete_{self.channel}.html",
"ajax_select/autocomplete.html",
Expand All @@ -398,11 +389,11 @@ class AutoCompleteField(forms.CharField):
def __init__(self, channel, *args, **kwargs):
self.channel = channel

widget_kwargs = dict(
help_text=kwargs.get("help_text", _(as_default_help)),
show_help_text=kwargs.pop("show_help_text", True),
plugin_options=kwargs.pop("plugin_options", {}),
)
widget_kwargs = {
"help_text": kwargs.get("help_text", _(as_default_help)),
"show_help_text": kwargs.pop("show_help_text", True),
"plugin_options": kwargs.pop("plugin_options", {}),
}
widget_kwargs.update(kwargs.pop("widget_options", {}))
if "attrs" in kwargs:
widget_kwargs["attrs"] = kwargs.pop("attrs")
Expand Down Expand Up @@ -446,9 +437,7 @@ def autoselect_fields_check_can_add(form, model, user):
related_model.
"""
for name, form_field in form.declared_fields.items():
if isinstance(
form_field, (AutoCompleteSelectMultipleField, AutoCompleteSelectField)
):
if isinstance(form_field, (AutoCompleteSelectMultipleField, AutoCompleteSelectField)):
db_field = model._meta.get_field(name)
if hasattr(db_field, "remote_field"):
form_field.check_can_add(user, db_field.remote_field.model)
Expand Down Expand Up @@ -480,5 +469,4 @@ def pack_ids(ids):
if ids:
# |pk|pk| of current
return "|" + "|".join(str(pk) for pk in ids) + "|"
else:
return "|"
return "|"
46 changes: 21 additions & 25 deletions ajax_select/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@


def make_ajax_form(model, fieldlist, superclass=ModelForm, show_help_text=False, **kwargs):
"""Creates a ModelForm subclass with AutoComplete fields.
"""
Creates a ModelForm subclass with AutoComplete fields.
Args:
model (type): Model class for which you are making the ModelForm
Expand Down Expand Up @@ -37,21 +38,20 @@ class YourModelAdmin(Admin):
"""
# will support previous arg name for several versions before deprecating
# TODO: time to go
if 'show_m2m_help' in kwargs:
show_help_text = kwargs.pop('show_m2m_help')
if "show_m2m_help" in kwargs:
show_help_text = kwargs.pop("show_m2m_help")

class TheForm(superclass):

class Meta:
exclude = []

Meta.model = model
if hasattr(superclass, 'Meta'):
if hasattr(superclass.Meta, 'fields'):
if hasattr(superclass, "Meta"):
if hasattr(superclass.Meta, "fields"):
Meta.fields = superclass.Meta.fields
if hasattr(superclass.Meta, 'exclude'):
if hasattr(superclass.Meta, "exclude"):
Meta.exclude = superclass.Meta.exclude
if hasattr(superclass.Meta, 'widgets'):
if hasattr(superclass.Meta, "widgets"):
Meta.widgets = superclass.Meta.widgets

for model_fieldname, channel in fieldlist.items():
Expand All @@ -64,7 +64,8 @@ class Meta:


def make_ajax_field(related_model, fieldname_on_model, channel, show_help_text=False, **kwargs):
"""Makes an AutoComplete field for use in a Form.
"""
Makes an AutoComplete field for use in a Form.
Args:
related_model (Model): model of the related object
Expand All @@ -82,29 +83,24 @@ def make_ajax_field(related_model, fieldname_on_model, channel, show_help_text=F
Returns:
(AutoCompleteField, AutoCompleteSelectField, AutoCompleteSelectMultipleField): field
"""
from ajax_select.fields import AutoCompleteField, AutoCompleteSelectField, AutoCompleteSelectMultipleField

field = related_model._meta.get_field(fieldname_on_model)
if 'label' not in kwargs:
kwargs['label'] = _(capfirst(force_str(field.verbose_name)))
if "label" not in kwargs:
kwargs["label"] = _(capfirst(force_str(field.verbose_name)))

if ('help_text' not in kwargs) and field.help_text:
kwargs['help_text'] = field.help_text
if 'required' not in kwargs:
kwargs['required'] = not field.blank
if ("help_text" not in kwargs) and field.help_text:
kwargs["help_text"] = field.help_text
if "required" not in kwargs:
kwargs["required"] = not field.blank

kwargs['show_help_text'] = show_help_text
kwargs["show_help_text"] = show_help_text
if isinstance(field, ManyToManyField):
f = AutoCompleteSelectMultipleField(
channel,
**kwargs)
f = AutoCompleteSelectMultipleField(channel, **kwargs)
elif isinstance(field, ForeignKey):
f = AutoCompleteSelectField(
channel,
**kwargs)
f = AutoCompleteSelectField(channel, **kwargs)
else:
f = AutoCompleteField(
channel,
**kwargs)
f = AutoCompleteField(channel, **kwargs)
return f
10 changes: 10 additions & 0 deletions ajax_select/lookup_channel.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ def get_query(self, q, request):
Returns:
(QuerySet, list, generator): iterable of related_models
"""
kwargs = {f"{self.search_field}__icontains": q}
return self.model.objects.filter(**kwargs).order_by(self.search_field)
Expand All @@ -59,6 +60,7 @@ def get_result(self, obj):
obj (Model):
Returns:
str: The object as string
"""
return escape(force_str(obj))

Expand All @@ -70,6 +72,7 @@ def format_match(self, obj):
obj (Model):
Returns:
str: formatted string, may contain HTML.
"""
return escape(force_str(obj))

Expand All @@ -81,6 +84,7 @@ def format_item_display(self, obj):
obj (Model):
Returns:
str: formatted string, may contain HTML.
"""
return escape(force_str(obj))

Expand All @@ -92,6 +96,7 @@ def get_objects(self, ids):
ids (list): list of primary keys
Returns:
list: list of Model objects
"""
# Inherited models have a OneToOneField (rather than eg AutoField)
if getattr(self.model._meta.pk, "remote_field", False):
Expand All @@ -118,10 +123,13 @@ def can_add(self, user, other_model):
Args:
user (User)
other_model (Model): the ForeignKey or M2M model to check if the User can add.
Returns:
bool
"""
from django.contrib.contenttypes.models import ContentType

ctype = ContentType.objects.get_for_model(other_model)
return user.has_perm(f"{ctype.app_label}.add_{ctype.model}")

Expand All @@ -138,8 +146,10 @@ def check_auth(self, request):
Args:
request (Request)
Raises:
PermissionDenied
"""
if not request.user.is_staff:
raise PermissionDenied
Loading

0 comments on commit 55ee7fe

Please sign in to comment.