dynamic filter choice field in django

2024/11/18 8:33:43

I am using django-filter to filter results on a page. I am able to use static choice filters like this:

filters.py

FILTER_CHOICES = (
('', 'All States'),
('AL', 'Alabama'),
('AK', 'Alaska'),
('AZ', 'Arizona'),
#and so forth, I am not going to list all 50 states for this a question on a forum
)class SightingFilter(django_filters.FilterSet):state = django_filters.ChoiceFilter(choices=FILTER_CHOICES)class Meta:model = Sightingfields = ['city', 'store', 'brand', 'product', 'flavor', 'fat', 'size']   

So that code above works fine, but if I try to make a dynamic list like "plant_number" below:

class SightingFilter(django_filters.FilterSet):state = django_filters.ChoiceFilter(choices=FILTER_CHOICES)plant_number = django_filters.ChoiceFilter(choices=[(o.plant_number, o.plant_number + " " + o.manufacturer_name) for o in Plant.objects.all()])class Meta:model = Sightingfields = ['city', 'store', 'brand', 'product', 'flavor', 'fat', 'size']

Then I get the error:

invalid literal for int() with base 10:

and it highlights this code in my template

{% for obj in filter %}<a href="/sighting/{{ obj.slug }}/ ">{{ obj.date|date:"m/d/Y" }} {{ obj.brand }} ${{ obj.price|intcomma }} </a><br />
{% endfor %}

The plant_number is a CharField in the model (plant numbers use the format XX-XXX, where the X's are digits).

My view looks like this:

def dashboard(request):if "Clear Filters" in request.GET:return redirect('/')
else:filter = SightingFilter(request.GET, queryset=Sighting.objects.all())context = {'filter': filter, 'request': request}return render_to_response('dashboard.html', context, context_instance=RequestContext(request))

Thanks for your help!

EDIT 1/14/15

So I am pretty certain the issue is that plant_number is a foreign key (sorry didn't include the models.py above). That is why it is expecting an int and not a string. So now I need to figure out how to get the foreign key value of the plant number instead of just the plant number. I tried:

plant_number = django_filters.ChoiceFilter(choices=[[o.plant_number.id, o.plant_number + " " + o.Manufacturer] for o in Plant.objects.all()])

Also tried:

plant_number = django_filters.ChoiceFilter(choices=[[o.plant_number_id, o.plant_number + " " + o.Manufacturer] for o in Plant.objects.all()])

Neither works. I get 'unicode' object has no attribute 'id' on the first one and 'Plant' object has no attribute 'plant_number_id' on the second.

models.py

class Sighting(models.Model):date = models.DateField(default=today)brand = models.CharField(max_length=200)product = models.CharField(max_length=200)flavor = models.CharField(max_length=200)fat = models.DecimalField(max_digits=4, decimal_places=2)size = models.DecimalField(max_digits=10, decimal_places=2)price = models.DecimalField(max_digits=10, decimal_places=2)plant_number = models.ForeignKey('Plant', blank=True, null=True )store = models.CharField(max_length=200)city =  models.CharField(max_length=200)state = models.CharField(max_length=200, choices=STATE_CHOICES)photo = ProcessedImageField(upload_to=yogurtupload,processors=[ResizeToFit(600, 600)], #Resizes so the largest dimension is 600 (width or height, whichever hits 600 first)format='JPEG',options={'quality': 72})slug = models.SlugField(unique=True)def save(self):now = timestamp()forslug = str(now) + " " + str(self.plant_number) + " " + str(self.brand)self.slug = slugify(forslug)super(Sighting, self).save()def __unicode__(self):return self.slugclass Plant(models.Model):plant_number = models.CharField(max_length=200)Manufacturer = models.CharField(max_length=200)city = models.CharField(max_length=200)state = models.CharField(max_length=200, choices=STATE_CHOICES)slug = models.SlugField(unique=True)def save(self):self.slug = slugify(self.plant_number)super(Plant, self).save()def __unicode__(self):return self.slug
Answer

That's because FILTER_CHOICES is tuples in a tuple, not tuples in a list. Try this:

plant_number = django_filters.ChoiceFilter(choices=((o.plant_number.id, o.plant_number.foobar + " " + o.manufacturer_name) for o in Plant.objects.all()))
https://en.xdnf.cn/q/120092.html

Related Q&A

How to print a table from a text file and fill empty spaces?

I have the following table in a txt file:|Client | Container weight | Country of Origin | Product code ||S4378 | 450 Ton | China | 457841 || | 350 Ton | Japan…

Open a file in python from 2 directory back

I want to read a file from 2 folders back.. with open(../../test.txt, r) as file:lines = file.readlines()file.close()I want to read from ../../ two folders back. but not work.. How i can do that ?

Do string representations of dictionaries have order in Python 3.4?

I know dictionaries themselves in Python do not have order. However, Im rather curious if when you call str() on a dictionary if it is always in the same order. It appears to be sorted (by key), no mat…

BeautifulSoup Scraping Results not showing

I am playing around with BeautifulSoup to scrape data from websites. So I decided to scrape empireonlines website for 100 greatest movies of all time. Heres the link to the webpage: https://www.empireo…

How to verify username and password from CSV file in Python?

I am doing a Python project where I have to verify my username and password from a csv file where the first two rows and columns have the username and password as hi.Current Code: answer = input("…

adding validation to answer in quiz gives wrong answers

I am a complete novice with Python and working on a multiple choice quiz that reads questions from a file and keeps a score that then writes to a file. Everything was working perfectly until I added v…

Why do I get None as the output from a print statement? [duplicate]

This question already has answers here:Why is "None" printed after my functions output?(7 answers)Closed 2 years ago.def print_name(name):print(name)print(print_name(Annabel Lee))Why do I ge…

How to collect tweets about an event that are posted on specific date using python?

I wish to collect all tweets containing specific keywords(ex:manchesterattack,manchester) that are posted about the manchester attack from 22may. Can anyone provide me a code to collect tweets using py…

Pivoting a One-Hot-Encode Dataframe

I have a pandas dataframe that looks like this:genres.head()Drama Comedy Action Crime Romance Thriller Adventure Horror Mystery Fantasy ... History Music War Documentary Sport Musical W…

How to declare multiple similar variables in python? [duplicate]

This question already has answers here:How do I create variable variables?(18 answers)Closed 5 years ago.How can I declare multiple (about 50) variables that count from slider1 to slider50 ? Is there…