I have a django form with a choicefield, where I dynamically load some choices into the field:
class EntryForm(forms.Form):
project = forms.ChoiceField()
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
super(EntryForm, self).__init__( *args, **kwargs)
CHOICES2=[]
for x in Project.objects.all() :
if user in x.users.all():
CHOICES2.append((x.name,x.name))
CHOICES1 = [(x.name,x.name) for x in Project.objects.all()]
print CHOICES2==CHOICES1 #this is True in this case
self.fields['project']=forms.ChoiceField(choices=CHOICES2)
The form is loaded into the template with {{form.as_table}}. The form does not show a dropdown for the project field.
Now the strange thing: if I change the last line to:
self.fields['project']=forms.ChoiceField(choices=CHOICES1)
it works, although the print statement of the "=="" comparison returns True (the lists are purposely the same - this is just for testing). I really have no idea how this can even work technically.
Edit - my project model:
class Project(BaseModel):
name = models.CharField(max_length=80)
users = models.ManyToManyField(User)
Your field named project already exists and there's no need to construct another one as you are doing. It's better to just set the choices on the existing field:
self.fields['project'].choices = CHOICES2
But maybe you'd be better off using a ModelChoiceField:
project = ModelChoiceField(queryset=Project.objects.none())
and then set the queryset you want in init like so:
self.fields['project'].queryset=Project.objects.filter(users__in=[user])
..which should give you a list of all projects associated with user.
I think you have to use queryset argument, which is mandatory:
https://docs.djangoproject.com/en/1.8/ref/forms/fields/#django.forms.ModelChoiceField.queryset
ChoiceField must be declared with (queryset=None), and in the __init__ method you complete the query:
https://docs.djangoproject.com/en/1.11/ref/forms/fields/#fields-which-handle-relationships
The problem could be about the execution order of the queries, or the cache of non-lazy queries.
And I agree with little_birdie: the field already exists.
Related
After searching for a while, I can't seem to find any answer for this so I'm asking this question. What I want to is display some values based on a person's salary and a bracket. My models looks like this.
class Employee
salary = models.DecimalField
class Benefit
some_fields
class EmployeeBenefit
employee = models.ForeignKey
benefit = models.ForeignKey
class BenefitVersion
benefit = models.ForeignKey
class BenefitBracket
benefit_version = models.ForeignKey
from_salary = models.DecimalField
to_salary = models.DecimalField
the_fields_I_want_to_display
As you can see it's quite deep, there would be a bunch of querying to do to get to the fields I want.
I basically need to get the employee's salary(which is easy because this is gonna be inside EmployeeAdmin) then get the current benefit of the EmployeeBenefit list item, then based on the benefit and the employee's salary, get the bracket and then display some of it's fields on the inline.
I want to display the the_fields_I_want_to_display on the admin.TabularInline for EmployeeBenefit inside my EmployeeAdmin. I was testing using a forms.ModelForm in the inline and modifying it's contents using get_form based on this answer but django is not calling get_form. I also previously tried using calculated_fields but it's not being rendered as well.
I'm using django 3.1.7 btw
Edit:
I found this and try it out right now. I think it has potential but unfortunately the obj that get_formset gives is Employee so I still need to find a way to get the right EmployeeBenefit for the list item
After some more searching, I already figured out a way to do this. Based on this SO answer, I got an idea on how I should receive the data I passed to the formset using get_formset.
So, in my get_formset, I did something like this.
def get_formset(self, request, obj=None, **kwargs):
formset = super(Inline, self).get_formset(request, obj, **kwargs)
formset.request = request
benefit_details_dict_arr = []
emp_contribs = models.EmployeeBenefit.objects.filter(employee=obj)
#because what I'm getting here is Employee and not a EmployeeBenefit, I have to query it first
for contrib in emp_contribs:
bracket = contrib.get_benefit_bracket(datetime.now())
benefit_details_dict_arr.append({
"key": bracket.val,
"key2": bracket.val2,
})
formset.benefit_details = benefit_details_dict_arr
return formset
Then on the formset, I receive the data this way.
class EmpBenefitFormSet(forms.models.BaseInlineFormSet):
model = models.EmployeeBenefit
def __init__(self, *args, **kwargs):
super(EmpBenefitFormSet, self).__init__(*args, **kwargs)
cntr = 0
for form in self.forms:
init_data = self.benefit_details[cntr]
for field in form.fields:
if field in init_data:
form.initial[field] = init_data[field]
form.fields[field].required = False
form.fields[field].disabled = True
cntr += 1
Also, if you're gonna use this way of receiving the data, each field you want to inflate should be declared on the fields of the inline. This should work if the fields you want to set an initial value are actual fields of the model. You might need to tweak this a bit to work for custom fields
In my project I am using Django-Select2 heavily, particularly its ModelSelect2Widget as my users frequently need to select from lists of 2,000-6,000 items. In all my uses of it up 'til now, the queryset for the widget has always been called as ".all()" instances of a model, for the user to select from, and there's been no issues.
Now, however, I have implementations in different parts of the project for which filtering the queryset of options for the widget is necessary. In all of these cases, however, any modification of the queryset seems to have no effect, and I'm wondering if there is a problem with the widget itself.
In the primary case, the items in the database are boolean-flagged as active/inactive (about 65% inactive), and I need to only have active items available for the end-user to select.
I'm able to filter the queries correctly via the shell.
In the form definitiion, any filtering (".filter(flag_active=True)", or even setting the queryset to ".none()" has no effect – there is no apparent change in the options in the dropdown/autocomplete. Being that it is a select2 input, I can only view a small number of items at a time, but both the initial retrieved population and the winnowed-down selection as I type indicate that the filters are not been followed.
MODEL:
class Inventory_product_base(models.Model):
id = models.UUIDField(primary_key=True,default=uuid.uuid4,null=False)
upc = models.CharField(max_length=96,null=True,blank=True)
name = models.CharField('Item name',max_length=96,null=False)
flag_active = models.BooleanField("Active item",default=True)
price = models.DecimalField(max_digits=8,decimal_places=3,null=True,blank=True)
unit_of_measure = models.CharField('UOM',max_length=24, choices=UNITS_OF_MEASURE,default='EACH')
spec = models.CharField(max_length=36,null=True,blank=True)
category = models.ForeignKey(Inventory_category,on_delete=models.CASCADE,related_name='cat_products')
subcategory = models.ForeignKey(Inventory_subcategory,on_delete=models.CASCADE,related_name='subcat_products')
note = models.CharField(max_length=275,null=True,blank=True)
def __str__(self):
return str(self.name)
FORM:
class InventoryCatalogUpdateProductsForm(forms.ModelForm):
parent_product_base = forms.ModelChoiceField(
queryset=Inventory_product_base.objects.filter(flag_active=True),
label=u"",
widget=ModelSelect2Widget(
model=Inventory_product_base,
search_fields=['name__icontains'],
attrs={'data-placeholder': 'Select product...', 'data-width': '100%'},),)
class Meta():
model = Inventory_unit_catalog
fields = ('parent_product_base',)
class InventoryCatalogUpdateAllProductsForm(forms.ModelForm):
parent_product_base = forms.ModelChoiceField(
queryset=Inventory_product_base.objects.all(),
label=u"",
widget=ModelSelect2Widget(
model=Inventory_product_base,
search_fields=['name__icontains'],
attrs={'data-placeholder': 'Select product...', 'data-width': '100%'},),)
class Meta():
model = Inventory_unit_catalog
fields = ('parent_product_base',)
InventoryCatalogUpdateProductsFormset = modelformset_factory(model=Inventory_unit_catalog,form=InventoryCatalogUpdateProductsForm,extra=10,can_delete=True)
InventoryCatalogUpdateAllProductsFormset = modelformset_factory(model=Inventory_unit_catalog,form=InventoryCatalogUpdateAllProductsForm,extra=10,can_delete=True)
VIEW:
if product_flag == 'active':
formset = InventoryCatalogUpdateProductsFormset(queryset=parent_unit_catalog.products.filter(flag_active=True))
else:
formset = InventoryCatalogUpdateAllProductsFormset(queryset=parent_unit_catalog.products.all())
As noted, if I change the above queryset to .none() (or anything else, either in the widget or in the view) there is no difference in the rendered choices in the select2 field.
I've tried separate, parallel forms and formsets. Originally I tried for a more sophisticated approach, to pass a parameter and have the different querysets selected within a single form, by adding the following:
def __init__(self, *args, **kwargs):
self.product_flag = kwargs.pop('product_flag')
super(InventoryCatalogAddToForm, self).__init__(*args, **kwargs)
print("__init__ has product_flag: ",self.product_flag)
if self.product_flag == 'active':
self.fields['parent_product_base'].queryset = Inventory_product_base.objects.filter(flag_active=True)
print("Screened for flag_active=True")
else:
self.fields['parent_product_base'].queryset = Inventory_product_base.objects.all()
print("Screened for flag_active=False")
and I was able to verify by the debug prints that the correct filter choices were executing, but without any effect. So I moved back to a simpler, more direct approach of separate forms, and still nothing.
Any advice would be welcome. My project is several months in and Django-Select2 is one of the foundations across it, I would hate to learn that it cannot filter the select2 input and I would need to find a replacement.
self.fields['parent_product_base'].queryset sets the queryset for the formfield (i.e. allowed choices for validation).
Use self.fields['parent_product_base'].widget.queryset to set the widget's choices.
I have autocomplete-light in the django modal form. I wanted to apply dynamic filtering in the suggestion box, that's why I have used choice_for_request() in the autocompletebasemodel. But because of using choice_for_request(), the suggestions are not according to the keyword typed but all the values that can be entered.
This is my form:
class CamenuForm(autocomplete_light.ModelForm):
class Meta:
model = Ca_dispensaries_item
exclude = ('dispensary',)
autocomplete_fields = ('item',)
def __init__(self, *args, **kwargs):
self.category = kwargs.pop('category', None)
super(CamenuForm, self).__init__(*args, **kwargs)
self.fields['item'].queryset=Items.objects.filter(product_type__name=self.category)
This is the registry and the class:
autocomplete_light.register(Items, AutoComplete )
class:
class AutoComplete(autocomplete_light.AutocompleteModelBase):
search_fields=('item_name',)
def choices_for_request(self):
category = self.request.session.get('category','')
if category:
choices = Items.objects.filter(product_type__name=category)
return self.order_choices(choices)[0:self.limit_choices]
I really dont know what changes to make in changes_for_request so as to make it work correctly
After going through various documents, the solution which worked as correctly as it should be is
def choices_for_request(self):
category = self.request.session.get('category','')
item=self.request.GET.get('q','')
choices = self.choices.all()
if item:
choices = choices.filter(item_name__icontains=item)
super(AutoComplete, self).choices_for_request()
if category:
choices = choices.filter(product_type__name=category)
return self.order_choices(choices)[0:self.limit_choices]
I missed out
item=self.request.GET.get('q','')
autocomplete-light uses the get method and the predefined literal q to transfer the value typed by user.
I wasn't able to crack out the meaning of q. After some hit and trial, I got that it is used to store the user given value in suggestion box.
I'm using autocomplete-light and for some reason this specific class is not working--I can't see any major differences between it and the working autocompletes. My VirtualHost contains a fk to a Host provided that Host.contain_virtuals=True
Here's my form:
class VirtualHostForm(ServerForm):
def __init__(self, *args, **kwargs):
super(VirtualHostForm, self).__init__(*args, **kwargs)
self.helper.form_id = 'virtual_host_form'
host = forms.ModelChoiceField(Host.objects.all(),
widget=autocomplete_light.ChoiceWidget('HostAutocomplete'),
label='Associated Host'
class Meta:
model = Virtual
fields = ServerForm.Meta.fields + ['host',]
widgets = autocomplete_light.get_widgets_dict(Server)
I've tried two ways, each with their own errors:
class HostAutocomplete(autocomplete_light.AutocompleteBase):
#registers autocomplete for hosts that can contain virtuals
autocomplete_js_attributes = {'placeholder': 'Select a host'}
widget_template='assets/subtemplates/autocomplete_remove.html',
choice_template='assets/_autocomplete_choice.html',
def choices_for_request(self):
q = self.request.GET.get('q', '')
hosts = Host.objects.values_list('name', flat=True)
return hosts.filter(name__icontains=q, contain_virtuals=True).distinct()
autocomplete_light.register(HostAutocomplete)
This way, I get the error: 'NotImplementedType' object is not callable. That seemed to relate to not having a choices_for_values method (although some of my other Autocompletes don't) so I added:
def choices_for_values(self):
choices = Host.objects.filter(id__in=self.values)
return choices
(I don't really know what I'm doing here--I couldn't find much in the documentation, so I took my best guess).
That gave me a invalid literal for int() with base 10: which I guess means it's looking at the name, instead of the pk for a foreign key relationship? That's a guess.
It should be noted that all of the above attempts did not render the template-formatting correctly, but did at least give the correct options for the choices.
So finally I tried:
autocomplete_light.register(
Host,
autocomplete_light.AutocompleteModelTemplate,
name='HostAutocomplete',
widget_template='assets/subtemplates/autocomplete_remove.html',
choice_template='assets/_autocomplete_choice.html',
autocomplete_js_attributes={'placeholder': 'Type associated host'},
search_fields=['name'],
)
which saves (and contains the correct formatting) but does not filter the choices based on contain_virtuals=True; it just includes all possible hosts.
EDIT:
Thanks to #jpic's help below, this works:
class HostAutocomplete(autocomplete_light.AutocompleteModelTemplate):
#registers autocomplete for hosts that can contain virtuals
autocomplete_js_attributes = {'placeholder': 'Select a host'}
choice_template='assets/_autocomplete_choice.html',
def choices_for_request(self):
q = self.request.GET.get('q', '')
hosts = Host.objects.filter(contain_virtuals=True,name__icontains=q).distinct()
return hosts
def choices_for_values(self):
choices = Host.objects.filter(id__in=self.values)
return choices
autocomplete_light.register(Host, HostAutocomplete)
This is because you inherit from AutocompleteBase instead of AutocompleteModelBase ! You could use AutocompleteModelTemplate as well.
Check out how Autocomplete design is explained in docs for v2 (that part doesn't change from v1 to v2): http://django-autocomplete-light.readthedocs.org/en/v2/autocomplete.html
I am trying to create a custom cleaning method which look in the db if the value of one specific data exists already and if yes raises an error.
I'm using a model form of a class (subsystem) who is inheriting from an other class (project).
I want to check if the sybsystem already exists or not when i try to add a new one in a form.
I get project name in my view function.
class SubsytemForm(forms.ModelForm):
class Meta:
model = Subsystem
exclude = ('project_name')
def clean(self,project_name):
cleaned_data = super(SubsytemForm, self).clean(self,project_name)
form_subsystem_name = cleaned_data.get("subsystem_name")
Subsystem.objects.filter(project__project_name=project_name)
subsystem_objects=Subsystem.objects.filter(project__project_name=project_name)
nb_subsystem = subsystem_objects.count()
for i in range (nb_subsystem):
if (subsystem_objects[i].subsystem_name==form_subsystem_name):
msg = u"Subsystem already existing"
self._errors["subsystem_name"] = self.error_class([msg])
# These fields are no longer valid. Remove them from the
# cleaned data.
del cleaned_data["subsystem_name"]
return cleaned_data
My view function :
def addform(request,project_name):
if form.is_valid():
form=form.save(commit=False)
form.project_id=Project.objects.get(project_name=project_name).id
form.clean(form,project_name)
form.save()
This is not working and i don't know how to do.
I have the error : clean() takes exactly 2 arguments (1 given)
My model :
class Project(models.Model):
project_name = models.CharField("Project name", max_length=20)
Class Subsystem(models.Model):
subsystem_name = models.Charfield("Subsystem name", max_length=20)
projects = models.ForeignKey(Project)
There are quite a few things wrong with this code.
Firstly, you're not supposed to call clean explicitly. Django does it for you automatically when you call form.is_valid(). And because it's done automatically, you can't pass extra arguments. You need to pass the argument in when you instantiate the form, and keep it as an instance variable which your clean code can reference.
Secondly, the code is actually only validating a single field. So it should be done in a specific clean_fieldname method - ie clean_subsystem_name. That avoids the need for mucking about with _errors and deleting the unwanted data at the end.
Thirdly, if you ever find yourself getting a count of something, iterating through a range, then using that index to point back into the original list, you're doing it wrong. In Python, you should always iterate through the actual thing - in this case, the queryset - that you're interested in. However, in this case that is irrelevant anyway as you should query for the actual name directly in the database and check if it exists, rather than iterating through checking for matches.
So, putting it all together:
class SubsytemForm(forms.ModelForm):
class Meta:
model = Subsystem
exclude = ('project_name')
def __init__(self, *args, **kwargs):
self.project_name = kwargs.pop('project_name', None)
super(SubsystemForm, self).__init__(*args, **kwargs)
def clean_subsystem_name(self):
form_subsystem_name = self.cleaned_data.get("subsystem_name")
existing = Subsystem.objects.filter(
project__project_name=self.project_name,
subsytem_name=form_subsystem_name
).exists()
if existing:
raise forms.ValidationError(u"Subsystem already existing")
return form_subsystem_name
When you do form=form.save(commit=False) you store a Subsystem instance in the variable form but the clean method is defined in SubsystemForm. Isn't it?