django use multiple widgets in form field - django

I'm trying to use two widgets (one to add custom class names, one for the choices) in one field, but not sure how.. there's no clear way specified in the official documentation to do this
widget=forms.TextInput(attrs={'class': 'select is-medium'})
widget=forms.Select

If you want a Select field with custom classes in it you just have to do the following:
widget=forms.Select(attrs={'class': 'select is-medium'})
In case you want to have two widgets in one field check Django MultiWidget.

Related

A Select Widget with fields as checkboxes with multiple options possible

I have the following model:
class Owner(models.Model)
country = models.CharField(max_length=255, choices=COUNTRIES, default=COUNTRIES_DEFAULT)
COUNTRIES is compose of tuples:
COUNTRIES = (
('afg', 'Afghanistan'),
('ala', 'Aland Islands'),
('alb', 'Albania'),
('dza', 'Algeria'),
('asm', 'American Samoa'),
....... )
For FrontEnd, I need to show a Widget, and for each country to have a checkbox.
A Person/User can select multiple Countries.
I presume I need to use a custom widget, but I don't know where to start inherit for Field/Widget and make the query in the database.
--- Why is not a duplicate of Django Multiple Field question ----
I don't need a new Model field, or to store it in the database and is not a many to many relation, so something like the package django-multiselectfield is not useful.
The ModelField is storing just one value, but in the form will appear values from the tuple.I added just to see the correspondence.
Instead I need to be just a Form Field, to get the values, and query the database. Like get all owners that resides in USA and UK.
Also is not looking like Select2, I need to respect design. As functionality is like in the image:
In your Form you must define a MultipleChoiceField with the CheckboxSelectMultiple widget:
countries = forms.MultipleChoiceField(choices=COUNTRIES, widget=forms.CheckboxSelectMultiple)
This will give you a list of multiple choice checkboxes. You can style that yourself to appear with a scrollbar if you don't want to show a long list.
Here is an example from the Django documentation: https://docs.djangoproject.com/en/2.1/ref/forms/widgets/#setting-arguments-for-widgets

How to filter choices in fields(forms) in Django admin?

I have model Tech, with name(Charfield) and firm(ForeignKey to model Firm), because one Tech(for example, smartphone) can have many firms(for example Samsung, apple, etc.)
How can I create filter in admin panel for when I creating model, If I choose 'smartphone' in tech field, it show me in firm field only smartphone firms? Coz if I have more than one value in firm field (for example Apple, Samsung, IBM), it show me all of it. But IBM must show only if in tech field I choose 'computer'. How release it?
class MyModelName(admin.ModelAdmin):
list_filter = (field1,field3,....)
refer:-
https://docs.djangoproject.com/en/2.1/ref/contrib/admin/
You can define the choices of the input with the attribute 'choices' of the widget. When you create the admin form of the model, you could define manually the fields, and also you can define the widget for each input. In the widget you could define with a tuple the choices and the initial values.

Django way for dynamic forms with dependencies?

I'm looking for a django way to handle some complex forms with a lot of business logic. The issue is many of my forms have dependencies in them.
Some examples:
1. two "select" (choice) fields that are dependent on each other. For example consider two dropdowns one for Country and one for City.
2. A "required-if" rule, i.e set field required if something else in the form was selected. Say if the user select "Other" option in a select field, he need to add an explanation in a textarea.
3. Some way to handle date/datetime fields, i.e rules like max/min date?
What I'm doing now is implementing all of these in the form clean(), __init__(), and write some (tedious) client-side JS.
I wonder if there is a better approach? like defining these rules in a something similar to django Meta classes.
I'm going to necro this thread, because I don't see a good answer yet. If you are trying to validate a field and you want that field's validation to depend on another field in that same form, use the clean(self) method.
Here's an example: Say you have two fields, a "main_image" and "image_2". You want to make sure that if a user uploads a second image, that they also uploaded a main image as well. If they don't upload an image, the default image will be called 'default_ad.jpg'.
In forms.py:
class AdForm(forms.ModelForm):
class Meta:
model = Ad
fields = [
'title',
'main_image',
'image_2',
'item_or_model_names',
'category',
'buying_or_selling',
'condition',
'asking_price',
'location',
]
def clean(self):
# "Call the cleaned form"
cleaned_data = super().clean()
main_image = cleaned_data.get("main_image")
image_2 = cleaned_data.get("image_2")
if "default_ad" not in image_2:
# Check to see if image_2's name contains "default_ad"
if "default_ad" in main_image:
raise forms.ValidationError(
"Oops, you didn't upload a main image."
)
If you want more info, read: https://docs.djangoproject.com/en/2.2/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other
Good luck!
1.This task is souly related the the html building of the form, not involving django/jinga.
2.Here, you go to dynamic forms. the best and most used way nowdays to do this, is through JS.
3.try building a DB with a "time" type field and then through "admin" watch how they handle it. all of special fields useage is covered here: https://docs.djangoproject.com/en/1.9/ref/forms/fields/

Django forms.SelectMultiple complains about choices

I'm trying to create a form consisting of a multiple select field which is used to select multiple instances of my Person model.
class MyForm(forms.Form):
choices = [(p.id, str(p)) for p in Person.objects.all()]
my_field = forms.ChoiceField(widget=forms.SelectMultiple, choices=choices)
The widget looks exactly like I want, but when I submit the form, it fails with the message
Select a valid choice. ['2', '3'] is not one of the available choices.
What am I doing wrong? When removing the widget=forms.SelectMultiple, from the third line, it works, but then it's only a single select field.
You are getting the error because ChoiceField expects a single choice.
If you want to allow multiple choices, use a MultipleChoiceField.
my_field = forms.MultipleChoiceField(choices=choices)
Note you don't have to specify the widget, as it's forms.SelectMultiple by default.

Render (and validate) related choice form fields in Django

I am trying to work out the best way to implement a form in django that has two choice fields on it, one of which affects the choices available in the other. An example - form field one is a radio button (can choose only one option) called 'cuisine', and the second is a multichoice field called 'menu'. If you choose 'french' from 'cuisine' then you get french dishes in the menu list, but if you choose 'chinese' you get a different selection.
How do I work this server-side in the form validation process. How do I 'bind' the two controls so that only dishes related to the cuisine option are accepted?
And how do I render this - should I pass in a ModelForm for each type of cuisine, or have a single menu ModelForm that has everything in it, and just show/hide stuff on the client-side?
All of the menu options are stored in the db and loaded in as fixtures, and the cuisines are hard-coded into the app:
CUISINE = ((0,'French'),(1,'Chinese'),(2,'Italian'))
class MenuItem(models.Model):
description = models.CharField(max_length=200)
cuisine = models.IntegerField('Cuisine', choices=CUISINE)
For rendering, you can use django-selectable or django-autocomplete-light,
For server side validation, django has it completely documented.