Using jquery autocomplete Django form - django

I am using jquery autocomplete with my generic views on Django. I am getting the list via AJAX, but there is one problem. When the user get the category he wants, he will select that value. Thus, if I append the value on that field $("#id_category").val(ui.item.value); it will show the pk on that field instead of value, so if I append $("#id_category").val(ui.item.label); django will complain it should be the instance. Django is completely right. How to make this work?
Edit:
I have made id_category hidden field and added category_display to append the text value. It is working. But while editing the category_display would be empty. Again I am using generic view. How to solve this one on the edit?

I had similar issue and I suggest you to think about question: 'What will happen if user enters not valid category name(category with this name doesn`t exist)?'
if you need to accept entered value and add new category, you have to make clean_category method in form:
def clean_category(self):
name = self.data['category']
return Category.objects.get_or_create(name=name)[0]
and display ui.item.label for user
if new category isn`t acceptable you can raise error in clean_category method or use something like select2(http://ivaynberg.github.io/select2/) for your field. I choose second variant.

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

Save the dynamically populated value on dropdown

I'm using wagtail CMS for Django, I want to add a dynamically populated value for a dropdown and save it on the Page model, this is my code:
class MyPage(Page):
domain = CharField(max_length=10, choices=MY_CHOICES)
subdomain = CharField(max_length=10, choices=[('', '------')]
I've got some frontend logic to populate dynamically the options for subdomain, but after I hit save I got: The page could not be created due to validation errors And in the subdomain field: Select a valid choice. [my value] is not one of the available choices.
I can't use ForeignKey to populate subdomain because it depends from an external API service that we're using.
I tried to use a custom field that inherits from CharField with no success, it looks it executes validate method only for the domain field.
If you use the choices argument, you have to predefine the list of possible values. Read the relevant part of the docs (last two paragraphs of that section).
You could omit the choices argument from the model field definition and only render a HTML select tag in the frontend (which is then filled with options dynamically, like you explained).
You could also look into changing the default widget of the CharField to a select tag, like this answer and this part of the docs show.

Form of a list of instances

I am missing an idea or a way to handle this in django.
I have a list of instances (class Sample) and I want to present the last 10 of them in a form with a checkbox before... I want to have a button "work on these" to submit the checked instances to a view. This view should present a detailView of the selected instances.
I don't know, how to handle this exactly. Can somebody give me a hint? All I did so far was just creating a form of a instance.
Thanks in advance.
You can use a ModelChoiceField or a ModelMultipleChoiceField.
class MyForm(forms.Form):
my_list_of_instances = forms.ModelMultipleChoiceField(queryset = MyModel.objects.all().order_by('-id')[:10], widget=forms.CheckboxSelectMultiple)
This should generate a list of checkbox with your last 10 instances created.
With this you have your form ready to receive your input...just point your action to your view.
Edit:
In case you want to have several forms, one for each instance, you can work with Formsets. You would not get the checkboxes tho...you would get any change applied to your instances. If you want to have both (checkboxes and formsets) you can use both suggestions, using the checkbox values sent to the server to filter the formsets you are going to save.

Remove "Name" field from Joomla registration form

I would like to remove the Name field in the Joomla registration form.
I have tried editing the /com_users/models/forms/registration.xml
I've tried removing the field from the XML file and I've also tried to set it as 'optional'. Neither of these work. The is a registration failed message in the next page in either case.
Found the instructions http://www.2createthatwebsite.com/tutorials/joomla-tutorials/remove-fields-joomla-registration-form
You need to edit the libraries/joomla/database/table/user.php file.
You need to edit the check() function.
In my case, I added a:
$this->name=$this->username;
at the beginning of the check function, that sets the username as the name, juse before saving.

In Django, how to validate a (multiple) cholice field when the choices are added by Javascript?

I have a ChoiceField where the choices are not known at the time the HTML is rendered; they are defined dynamically by the user and added to the form through Javascript, but the validation naturally fails since the selected option is not in the choices attribute (which is just an empty list). I have tried setting the field to a CharField, but then the validator just gets a string value that needs to be converted into a list before it van be used. Ah, and I'd like to avoid subclassing the field class as it's just for one occasion.
I hope this is clear. Any ideas?
Don't subclass the field class but override the clean_<yourfield> method in your Form class. See the docs here.