django-autocomplete-light filter queryset - django

I am trying to use django-autocomplete-light but I have some problems.
I would like to filter the queryset in the ModelChoiceField.
If I don't use auto-complete my result selection is correct but if I use widget it doesn't work correctly, it shows all records.
Here is my code:
class MyModelAdminForm(forms.ModelForm):
def __init__(self, *args, **kw):
super(MyModelAdminForm, self).__init__(*args, **kw)
self.fields['my_field'] = forms.ModelChoiceField(
MyModel.objects.filter(status=1),
widget=autocomplete_light.ChoiceWidget('MyModelAutocomplete')
)
class MyModelAdmin(ModelAdmin):
form = MyModelAdminForm

You should set MyModelAutocomplete.choices, either via register():
autocomplete_light.register(MyModel, choices=MyModel.objects.filter(status=1))
Or within the class:
class MyModelAutocomplete(autocomplete_light.AutocompleteModelBase):
choices = MyModel.objects.filter(status=1)
Refer to docs for more:
AutocompleteModel API docs
Using register() to pass class attributes: "In addition, keyword arguments will be set as class attributes."
Overriding choices_for_request() might be useful if you need to filter choices based on the user.
I would like to automate this, but the widget isn't aware about the form field instance unfortunately.

Apply the filter inside MyModelAutocomplete by defining a method
class MyModelAutocomplete(autocomplete_light.AutocompleteModelBase):
choices=MyModel.objects.all()
def choices_for_request(self):
choices = choices.filter(status=1)
return self.order_choices(choices)[0:self.limit_choices]
choices_for_request is mostly used for dynamic filterming

I was trying to figure out how to do this within the autocomplete-light documentation. I figured out how, but not without a bit of digging, so hopefully this is helpful.
In the autocomplete_light_registry.py file, fill out the "name" and "choices" parameters:
#myapp/autocomplete_light_registry.py
autocomplete_light.register(MyModel,
#... Other Parameters ...
name = 'SpecialMyModelAutocomplete',
choices = YourQuerySetHere, #e.g. MyModel.objects.filter(...)
)
The default name is "MyModelAutocomplete" so if you include more than one registered autocomplete for a model, you need to specify which one you want to use (otherwise it uses the first one in the registry, NOT the default).
To specify, use "autocomplete_names" which is (from the docs) "A dict of field_name: AutocompleteName to override the default autocomplete that would be used for a field." In my case I'm using it within the django admin.
#myapp/admin.py
class MyModelAdminForm(autocompletelight.ModelForm):
class Meta:
model = MyModel
autocomplete_names = {'field_name':'SpecialMyModelAutocomplete'}
Note that you don't need to include any fields for which you want to use the default Autocomplete in autocomplete_names. Incidentally "autocomplete_exclude" and "autocomplete_fields" may also be of interest here and are analogous to "fields" and "exclude" in a ModelAdmin to specify which fields to include/exclude from using autocomplete.
Addition:
You can also use "autocomplete_names" in the modelform_factory:
form = autocomplete_light.modelform_factory(MyOtherModel,autocomplete_names={MyFieldName:'MyModelAutocomplete'}) #where MyFieldName is a ForeignKey to MyModel
From the docs:
autocomplete_light.forms.modelform_factory(model,autocomplete_fields=None,autocomplete_exclude=None,autocomplete_names=None,registry=None,**kwargs)

Related

How to make a generic List Filter in Django using django-filters?

I want to have a FilterSet class that allows all of the fields to be filtered as a list.
I was thinking of overriding the default FilterSet class of django-filters and having the fields be dynamically set as well as setting a method to each one.
So, something like this for example:
ModelName_fields = {'names': 'name', 'ids': 'id', 'second_ids': 'second_id'}
class ListFilter(FilterSet):
def __init__(self, *args, **kwargs):
# self._meta.fields = [field_name for field_name in modelNameHere + '_fields']
super(FilterSet).__init__(*args)
class SomeAPIView(mixins.ListModelMixin):
model = ModelName
filterset_class = ListFilter
Basically, ModelName_fields is a declared constant that maps the query parameter to the field name of the model. In this case, I declare the model on the view as well as the filterset class and in the __init__ method of the filterset class, I dynamically attach the fields as well as the query parameter name.
In all essence, I just want to make the ListFilter as generic as possible to be used on different views as well.
My question is, is this the correct way or is there some other better way to accomplish this? Also, how can I get the name of the model, which is an attribute of the view class, in the ListFilter class?

django-filter with django autocomplete light

Has anyone succesfully used dal and django-filter together?
Below attempt is mine,
I tried to use filterset_factory, supplying model class and fields list, then I tried to use futuremodelform.
I got ,
ModelForm has no model class specified.
I think it's just one of many errors to occur.
Anybody done that before, I have to use filterset_factory, and create dynamic classes from arguments, I also want to override widgets so dal widgets can be used.
#testing filterset
from dal import autocomplete
from django.db import models
class PanFilterSet(django_filters.FilterSet):
filter_overrides = {
models.ForeignKey: {
'filter_class': autocomplete.ModelSelect2,
},
}
def pan_filterset_factory(model,fields):
meta = type(str('Meta'), (object,), {'model': model,'fields':fields,'form':autocomplete.FutureModelForm})
filterset = type(str('%sFilterSet' % model._meta.object_name),
(PanFilterSet,), {'Meta': meta})
return filterset
searchFormFilterSet = pan_filterset_factory(self.model_class,self.final_search_fields)
f = searchFormFilterSet(self.request.GET, queryset=self.get_queryset())
print f.form.as_p()
I'm not very familiar with DAL, but I contribute to django-filter and have a decent understanding of its internals. A few notes:
The filter_class in your filter_overrides should be a filter, not a widget. You can provide additional arguments (such as the widget) through the extra key, as seen here. Any parameter that does not belong to the filter is automatically passed to the underlying form field.
Using an override isn't the right approach anyway, as the widget needs a field-specific endpoint to perform autocompletion. Since the endpoint is field-specific, it's not applicable to all ForeignKeys.
django-filter uses regular Forms, not ModelForms, so an appropriate Meta inner class would not be constructed. FutureModelForm doesn't seem to provide autocomplete functionality anyway - it seems irrelevant?
Your factory will have to generate your autocomplete filters manually - something like the following:
def dal_field(field_name, url):
return filters.ModelChoiceFilter(
name=field_name,
widget=autocomplete.ModelSelect2(url=url),
)
def dal_filterset_factory(model, fields, dal_fields):
attrs = {field: dal_field(field, url) for field, url in dal_fields.items()}
attrs['Meta'] = type(str('Meta'), (object,), {'model': model,'fields': fields})
filterset = type(str('%sFilterSet' % model._meta.object_name),
(FilterSet,), attrs)
return filterset
# Usage:
# mapping of {field names: autocomplete endpoints}.
dal_fields = {'birth_country': 'country-autocomplete'}
fields = ['list', 'or', 'dict', 'of', 'other', 'fields']
SomeModelFilterSet = dal_filterset_factory(SomeModel, fields, dal_fields)
The fields in attrs use the declarative API. More info in the docs.

Django admin: don't send all options for a field?

One of my Django admin "edit object" pages started loading very slowly because of a ForeignKey on another object there that has a lot of instances. Is there a way I could tell Django to render the field, but not send any options, because I'm going to pull them via AJAX based on a choice in another SelectBox?
You can set the queryset of that ModelChoiceField to empty in your ModelForm.
class MyAdminForm(forms.ModelForm):
def __init__(self):
self.fields['MY_MODEL_CHOIE_FIELD'].queryset = RelatedModel.objects.empty()
class Meta:
model = MyModel
fields = [...]
I think you can try raw_id_fields
By default, Django’s admin uses a select-box interface () for fields that are ForeignKey. Sometimes you don’t want to incur the overhead of having to select all the related instances to display in the drop-down.
raw_id_fields is a list of fields you would like to change into an Input widget for either a ForeignKey or ManyToManyField
Or you need to create a custom admin form
MY_CHOICES = (
('', '---------'),
)
class MyAdminForm(forms.ModelForm):
my_field = forms.ChoiceField(choices=MY_CHOICES)
class Meta:
model = MyModel
fields = [...]
class MyAdmin(admin.ModelAdmin):
form = MyAdminForm
Neither of the other answers worked for me, so I read Django's internals and tried on my own:
class EmptySelectWidget(Select):
"""
A class that behaves like Select from django.forms.widgets, but doesn't
display any options other than the empty and selected ones. The remaining
ones can be pulled via AJAX in order to perform chaining and save
bandwidth and time on page generation.
To use it, specify the widget as described here in "Overriding the
default fields":
https://docs.djangoproject.com/en/1.9/topics/forms/modelforms/
This class is related to the following StackOverflow problem:
> One of my Django admin "edit object" pages started loading very slowly
> because of a ForeignKey on another object there that has a lot of
> instances. Is there a way I could tell Django to render the field, but
> not send any options, because I'm going to pull them via AJAX based on
> a choice in another SelectBox?
Source: http://stackoverflow.com/q/37327422/1091116
"""
def render_options(self, *args, **kwargs):
# copy the choices so that we don't risk affecting validation by
# references (I hadn't checked if this works without this trick)
choices_copy = self.choices
self.choices = [('', '---------'), ]
ret = super(EmptySelectWidget, self).render_options(*args, **kwargs)
self.choices = choices_copy
return ret

Django forms.ChoiceField without validation of selected value

Django ChoiceField "Validates that the given value exists in the list of choices."
I want a ChoiceField (so I can input choices in the view) but I don't want Django to check if the choice is in the list of choices. It's complicated to explain why but this is what I need. How would this be achieved?
You could create a custom ChoiceField and override to skip validation:
class ChoiceFieldNoValidation(ChoiceField):
def validate(self, value):
pass
I'd like to know your use case, because I really can't think of any reason why you would need this.
Edit: to test, make a form:
class TestForm(forms.Form):
choice = ChoiceFieldNoValidation(choices=[('one', 'One'), ('two', 'Two')])
Provide "invalid" data, and see if the form is still valid:
form = TestForm({'choice': 'not-a-valid-choice'})
form.is_valid() # True
Best way to do this from the looks of it is create a forms.Charfield and use a forms.Select widget. Here is an example:
from django import forms
class PurchaserChoiceForm(forms.ModelForm):
floor = forms.CharField(required=False, widget=forms.Select(choices=[]))
class Meta:
model = PurchaserChoice
fields = ['model', ]
For some reason overwriting the validator alone did not do the trick for me.
As another option, you could write your own validator
from django.core.exceptions import ValidationError
def validate_all_choices(value):
# here have your custom logic
pass
and then in your form
class MyForm(forms.Form):
my_field = forms.ChoiceField(validators=[validate_all_choices])
Edit: another option could be defining the field as a CharField but then render it manually in the template as a select with your choices. This way, it can accept everything without needing a custom validator

How to prevent self (recursive) selection for FK / MTM fields in the Django Admin

Given a model with ForeignKeyField (FKF) or ManyToManyField (MTMF) fields with a foreignkey to 'self' how can I prevent self (recursive) selection within the Django Admin (admin).
In short, it should be possible to prevent self (recursive) selection of a model instance in the admin. This applies when editing existing instances of a model, not creating new instances.
For example, take the following model for an article in a news app;
class Article(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField()
related_articles = models.ManyToManyField('self')
If there are 3 Article instances (title: a1-3), when editing an existing Article instance via the admin the related_articles field is represented by default by a html (multiple)select box which provides a list of ALL articles (Article.objects.all()). The user should only see and be able to select Article instances other than itself, e.g. When editing Article a1, related_articles available to select = a2, a3.
I can currently see 3 potential to ways to do this, in order of decreasing preference;
Provide a way to set the queryset providing available choices in the admin form field for the related_articles (via an exclude query filter, e.g. Article.objects.filter(~Q(id__iexact=self.id)) to exclude the current instance being edited from the list of related_articles a user can see and select from. Creation/setting of the queryset to use could occur within the constructor (__init__) of a custom Article ModelForm, or, via some kind of dynamic limit_choices_to Model option. This would require a way to grab the instance being edited to use for filtering.
Override the save_model function of the Article Model or ModelAdmin class to check for and remove itself from the related_articles before saving the instance. This still means that admin users can see and select all articles including the instance being edited (for existing articles).
Filter out self references when required for use outside the admin, e.g. templates.
The ideal solution (1) is currently possible to do via custom model forms outside of the admin as it's possible to pass in a filtered queryset variable for the instance being edited to the model form constructor. Question is, can you get at the Article instance, i.e. 'self' being edited the admin before the form is created to do the same thing.
It could be I am going about this the wrong way, but if your allowed to define a FKF / MTMF to the same model then there should be a way to have the admin - do the right thing - and prevent a user from selecting itself by excluding it in the list of available choices.
Note: Solution 2 and 3 are possible to do now and are provided to try and avoid getting these as answers, ideally i'd like to get an answer to solution 1.
Carl is correct, here's a cut and paste code sample that would go in admin.py
I find navigating the Django relationships can be tricky if you don't have a solid grasp, and a living example can be worth 1000 time more than a "go read this" (not that you don't need to understand what is happening).
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['myManyToManyField'].queryset = MyModel.objects.exclude(
id__exact=self.instance.id)
You can use a custom ModelForm in the admin (by setting the "form" attribute of your ModelAdmin subclass). So you do it the same way in the admin as you would anywhere else.
You can also override the get_form method of the ModelAdmin like so:
def get_form(self, request, obj=None, **kwargs):
"""
Modify the fields in the form that are self-referential by
removing self instance from queryset
"""
form = super().get_form(request, obj=None, **kwargs)
# obj won't exist yet for create page
if obj:
# Finds fieldnames of related fields whose model is self
rmself_fields = [f.name for f in self.model._meta.get_fields() if (
f.concrete and f.is_relation and f.related_model is self.model)]
for fieldname in rmself_fields:
form.base_fields[fieldname]._queryset =
form.base_fields[fieldname]._queryset.exclude(id=obj.id)
return form
Note that this is a on-size-fits-all solution that automatically finds self-referencing model fields and removes self from all of them :-)
I like the solution of checking at save() time:
def save(self, *args, **kwargs):
# call full_clean() that in turn will call clean()
self.full_clean()
return super().save(*args, **kwargs)
def clean(self):
obj = self
parents = set()
while obj is not None:
if obj in parents:
raise ValidationError('Loop error', code='infinite_loop')
parents.add(obj)
obj = obj.parent