Linear Scale Django form widget - django

I am looking for some guidance in order to create a widget that is not documented at all in the django documentation but is an evident part of forms.
And I am talking about Linear Scales widgets for forms. Giving the ability to a user to choose on a scale between 1-100 a score
If you have any idea on how to do it, any direction I would be please to get it ;)
thx you very much

I'm guessing that you want a type="range" input as you can find in this MDN page.
Django doesn't provide this kind of field out of the box and you have to do it yourself or find a library that implements it.
To implement a field you should look at the Field API and the Input API.
# example input
from django.form.widgets import Input
class RangeInput(Input):
input_type = 'range'
template_name = 'path/to/input/template.html'
You should also implement type coercion (to int of float) and range checking to be sure that you can validate a form and store it appropriately in the db.
Once you have done that you can create your form with this input or create a new RangeField for models and link it to the RangeInput element.

Related

Flask WTForms - option_widget for SelectMultipleField?

I have a field in my Flask WTForm which uses a SelectMultipleField. I'm using a frontend library which renders the choices fine from the db and adds them to the input field as tags when I select them (like the tags do on this website when creating a question!).
However the data is not being saved, form.field.data and request.form.getlist('field') etc all show None. If I add option_widget=widgets.CheckboxInput to the SelectMultipleField, I can select and save data.
So what I'm wondering is, do I need make a custom field or widget in order for the form to use the selected options as the form data (for example, instead of checking if the field has been checked, it checks if it's in the input field). Going a bit mad reading all the documentation so grateful for a hint in the right direction! Code below:
field = SelectMultipleField(
"fieldname",
validators=[Optional()],
widget=widgets.ListWidget(prefix_label=False),
# option_widget=CheckboxInput(),
)
please try this way
from flask_appbuilder.fieldwidgets import Select2ManyWidget
"users": QuerySelectMultipleField(
_("group.user"),
query_factory=lambda: db.session.query(User),
widget=Select2ManyWidget(),
default=[],
),
The result will look like the image below

Is there any way to determine attribute is select/choice in django model?

Currently implementing searchbox which provides two interface - textbox if required input is not normalized, and dropdown if required input is normalized and is defined with choices param in model, and select class in form.
Current model(partial):
id = models.CharField(args)
submitter = models.CharField(args)
experiment_type = models.CharField(args, choices=<tuple with choices>)
Current form.Meta.widgets for model above:
'id': TextInput(attrs={'id':'exp_id', readonly: ''})
'experiment_type': Select(attrs={'id': 'experiment_type', required=''})
I've currently found that I can retrieve each fields' html snippet by doing str(field), for field in form, and with beautifulsoup or other html parsing library I can find input type(is text field or dropdown(select)), and option values for dropdown.
But it seems too compilcated, and I'm currently guessing that there might be
some way django provides to determine such things.Looking forward, and thanks in advance for any help.

Django: Generate form from dictionary

I'm currently working on a django-app where users have the option to select synonyms for a select number of words. These words are then replaced all over the website by these synonyms
these synonymes are defined as a separate model:
class TransportSynonyms(models.Model):
user= models.ForeignKey(user)
key = models.CharField(max_length=255)
value = models.CharField(max_length=255)
This process is done in part with template tags, and as such the number of words that can be 'synonymed' is limited. For example, the following words can be replaced by synonymes:
'train', 'plane'.
And appear like so in the html template:
{% get_trans "train" %}
{% get_trans "plane" %}
I now want to give user the ability to define synonymes for themselves, without the admin view. I created a few pages using a ListView as an overview (so the users could see which words they can change) with individual buttons that led to EditViews.
However, I'm since user have no synonyms linked to them by default, the ListView appears empty. I could solve that by passing a list from the view, but that list wont have the required '.id' values and would be worthless for linking to the EditViews.
My listview currently looks like the following table:
Original | Synonym
---------------------------
train | train (button to editview)
plane | aircraft (button to editview)
The buttons require an ID value
href="{% url 'synonym_edit' pk=synonym.id %}"
I have to find a way to fill the ListView with the 'synonymable' words and provide links to a DetailView (for synonyms might not yet exist).
I thought about dropping the ListView all together and instead pass a dictionary to a form. By default both the key and the value will be the same word
({'train' : 'train', 'plane' : 'plane'})
and a form would then be generated form this dictionary, allowing users to change the value by having the dictionary value be shown as a text input.
Its a bit more limited (and more cumbersome) than my original plan, but I think this might work. Problem is that I've only really worked with modelforms before, and I am currently stuck on having the form be generated from the dictionary. Could anyone here point me to the right direction?
Regards,
Jasper

Alternative form for Django's `ChoiceField` that can handle thousands of entries

I have a form with a ChoiceField in it. It is rendered to the user as a dropdown box.
Problem is, I have thousands of entries in this field, which is causing the page to (a) load very slowly and (b) be sluggish.
I want an alternative widget, instead of Select, that could handle more than 10,000 choices.
Something like the admin's raw_id_fields would be good (if only it were usable in general forms...) but I'm open to ideas.
If autocomplete is an option for your UI you can take a look to django-simple-autocomplete:
App enabling the use of jQuery UI autocomplete widget for
ModelChoiceFields with minimal configuration required.
EDITED (reply OP comment)
I have not tested this solution, but digging documentation and source it seems that not all data is loaded at a time:
The ability to specify an URL for the widget enables you to hook up to
other more advanced autocomplete query engines if you wish.
Source code:
def get_json(request, token):
"""Return matching results as JSON"""
...
di = {'%s__istartswith' % fieldname: searchtext} # <- look here!
items = queryset.filter(**di).order_by(fieldname)[:10]
Widget source code
$("#id_%(name)s_helper").autocomplete({
source: function(request, response){
$.ajax({ # <-- look here
url: "%(url)s",
data: {q: request.term},
success: function(data) {
I don't know what is the raw_id_fields but why not use a model to store all your choices ?
class Choice(models.Model):
value = models.CharField()
class MyModel(models.Model):
choice = models.ForeignKey(Choice)
It would then be easy to select it if you want to display only 20 at a time for example.
Based on this comment (which really, you should have included in your question):
Let me clarify my task: I have 10,000 users. I have a form in which
you choose a user. You need to be able to choose any user you want.
You can't just load 20, because then you won't be able to choose the
other 9,980 users.
If you want something built-in, you can use the FilteredSelectMultiple widget from django.contrib.admin.widgets, which puts a filter on your select.
You should also cache the results of the 10,000 users so you don't hit your db everytime. This is what is causing your delay, not the number of users (which is tiny, for practical performance problems).

Customising specific fields in Django Admin change form

I have a couple of fields in my model that to which I wish to add a link that will allow the user to search for names/files (external from the application's database).
So what I would like is:
Field name: [text box] - LINK
Is there a straightforward django way of achieving this?
Cheers.
You need to change the widget that the form field uses to display the models information. You basically add some html after the input to link to where you want.
Here's some code I put together to create a widget that displays how many characters are left for a CharacterField so it's similar to what you are looking to do:
https://github.com/pastylegs/django-widget-charsleft/blob/master/widget_charsleft/widgets.py