Allow dynamic choice in Django ChoiceField

2024/10/11 6:33:32

I'm using Select2 in my application for creating tags-like select dropdowns. Users can select number of predefined tags or create a new tag.

Relevant forms class part:

   all_tags = Tag.objects.values_list('id', 'word')# Tagstags = forms.ChoiceField(choices=all_tags,widget=forms.Select(attrs={'class': 'question-tags','multiple': 'multiple',}))

The problem is that Django won't allow custom tags(choices) upon validation. There error I'm getting looks like this: Select a valid choice. banana is not one of the available choices.

Is there any way around it?

Thanks

Answer

I would change the choicefield to charfield, and use the clean method to filter unwanted choices depending on certain conditions. Simply changing it to a char field with a select widget would work since Select2 is javascript anyways.

class Myform(forms.Form):tags = forms.CharField(max_length=254,widget=forms.Select(choices=tags,  # here we set choices as part of the select widgetattrs={'class': 'question-tags','multiple': 'multiple',}))def clean_tags(self):tags = self.cleaned_data['tags']# more tag cleaning logic herereturn tags
https://en.xdnf.cn/q/69805.html

Related Q&A

Row-wise unions in pandas groupby

I have a large data frame that looks like so (and is copy-pasteable with df=pd.read_clipboard(sep=\s\s+):user_nm month unique_ips shifted_ips halves quarters mo_pairs100118231 2 set(…

Add seaborn.palplot axes to existing figure for visualisation of different color palettes

Adding seaborn figures to subplots is usually done by passing ax when creating the figure. For instance:sns.kdeplot(x, y, cmap=cmap, shade=True, cut=5, ax=ax)This method, however, doesnt apply to seabo…

Running Django with Run can not find LESS CSS

I have a Django project that uses buildout. When running or debugging the application it runs fine by using my buildout script. I also use django-compressor to compress and compile my LESS files. I ins…

OpenCV + python -- grab frames from a video file

I cant seem to capture frames from a file using OpenCV -- Ive compiled from source on Ubuntu with all the necessary prereqs according to: http://opencv.willowgarage.com/wiki/InstallGuide%20%3A%20Debia…

python 3.1 - Creating normal distribution

I have scipy and numpy, Python v3.1I need to create a 1D array of length 3million, using random numbers between (and including) 100-60,000. It has to fit a normal distribution. Using a = numpy.random.…

Faster way to iterate all keys and values in redis db

I have a db with about 350,000 keys. Currently my code just loops through all keys and gets its value from the db.However this takes almost 2 minutes to do, which seems really slow, redis-benchmark gav…

How to store a floating point number as text without losing precision?

Like the question says. Converting to / from the (truncated) string representations can affect their precision. But storing them in other formats like pickle makes them unreadable (yes, I want this too…

Integer in python/pandas becomes BLOB (binary) in sqlite

Storing an integer in sqlite results in BLOBs (binary values) instead of INTEGER in sqlite. The problem is the INT in the "Baujahr" column. The table is created. CREATE TABLE "Objekt&quo…

Calling Scrapy Spider from Django

I have a project with a django and scrapy folder in the same workspace:my_project/django_project/django_project/settings.pyapp1/app2/manage.py...scrapy_project/scrapy_project/settings.pyscrapy.cfg...Iv…

Python Threading: Multiple While True loops

Do you guys have any recommendations on what python modules to use for the following application: I would like to create a daemon which runs 2 threads, both with while True: loops. Any examples would b…