I've some code like this:
<select id="form.category}}">
{% for category in form.category %}
<option value="{{ category }}"></option>
{% endfor %}
</select>
And result is:
https://zapodaj.net/940329c1516df.png.html
Why?
#edit
category = models.CharField(max_length=100, choices=get_categories())
def get_categories():
categories = (
("wydarzenia", "wydarzenia"),
("informacje", "informacje"),
("konkursy", "konkursy"),
("wycieczki", "wycieczki"),
("sport", "sport"),)
return categories
form.category is a field in model
The option looks empty because you are not showing anything inside the options tag. You need to display some labels for option tag. Do something like this if category is an object and it has attributes like id and name.
<select id="form.category">
{% for category in form.category %}
<option value="{{ category.id }}">{{category.name}}</option>
{% endfor %}
</select>
If category is a string or number do something like this
<select id="form.category">
{% for category in form.category %}
<option value="{{ category }}">{{category}}</option>
{% endfor %}
</select>
Bear in mind that form.category should be an iterable.
Related
i have table in db in which i stores countries and i dynamically pass those countries in template and and in forms.pt i have a ChoiceField(widget=forms.Select,required=True) like this but i didnot get the value from this filed but when i chane it into CharField i get the value.
<div class="form-group col-md-4 select-border">
<label>Country</label>
<select class="form-control basic-select" name="country">
{% for country in countries %}
<option value="{{ country.value }}">{{ country.value }}</option>
{% endfor %}
</select>
</div>
form.py
country = forms.ChoiceField(widget=forms.Select,required=True)
views.py
users_meta.candidate_country = ProfileForm.cleaned_data['country']
Here is my model form
class CategoryCreateForm(forms.ModelForm):
class Meta:
model = Category
fields = [
'nature',
'name',
'description',
]
The field nature is a one-to-many foreign field (There could be many categories of the same nature). I know I can render this field in the template using {{ form.nature }} but I would like to render the form manually without the help of Django or crispy forms. I have managed to do so for the other fields but don't know how to do it for a select field of a model form. I am looking for a solution similar to the following
<select class="custom-select custom-select-sm{% if form.nature.errors %} is-invalid{% endif %}" id="{{ form.nature.id_for_label }}" name="{{ form.nature.html_name }}">
{% for nature in form.nature.objects %}
<option value="{{ nature.id }}">{{ nature.name }}</option>
{% endfor %}
</select>
This is what worked
<select class="custom-select custom-select-sm{% if form.nature.errors %} is-invalid{% endif %}" id="{{ form.nature.id_for_label }}" name="{{ form.nature.html_name }}">
{% for id, name in form.fields.nature.choices %}
<option value="{{ id }}">{{ name }}</option>
{% endfor %}
</select>
I want to update / edit a product from a page by clicking a form button (UPDATE) after selecting product from a dropdown list or an auto-complete list.
List.html page works fine while clicking on UPDATE button update.html page cannot parse the POST data.
Manually I could access update.html with pk suffix (/update/1/), it is working fine too.
How can I pass pk's value alone to url?
views.py
class ProductUpdateView(UpdateView):
template_name = 'update.html'
model = Product
fields = ['name', 'description', 'image', 'file',]
success_url = '/list/'
class ProductsView(ListView,):
template_name = 'list.html'
model = Product
urls.py
urlpatterns = [
url(r'^list/$', ProductsView.as_view(), name='list'),
url(r'^update/(?P<pk>[0-9]+)/$', ProductUpdateView.as_view(), name='update'),
]
list.html
<body>
<form method='POST' action='/update/'> {% csrf_token %}
<select name='pk'>
{% for obj in object_list %}
<option value='{{ obj.id }}'>{{ obj.name }}</option>
{% endfor %}
</select>
<input type="submit" value='UPDATE'>
</form>
</body>
You can do this by only using <select>
<select name="select_path" id="select_path"
ONCHANGE="location = this.options[this.selectedIndex].value;">
{% for obj in object_list %}
<option value="{% url app_name:update obj.id %}">{{ obj.name }}
</option>
{% endfor %}
</select>
You just need to change the option value, I don't know the exact url, tewak as per your requirement.
I know it's a little bit late but this answer will definitely help someone.
<select name="select_path" id="select_path">
<option value="{{ initial_value }}">{{ initial_value name }}</option>
{% for obj in object_list %}
<option value="{{ edited object value }}">{{ edited obj.name }}
</option>
{% endfor %}
</select>
Get the value normally as you would when saving a form.
In my template i have a multiple-choice-object like this:
<form action="/hmi/give_trend3/" method="get">
<p>
<select name="n" size="3" multiple="multiple">
{% for tag in tags %}
<option>{{ tag.name }}</option><br>
{% endfor %}
</select>
</p>
</form>
and i want to get all the values (of the multiple-choice) in my
views.py:
def give_trend3(request):
v = request.GET['v']
b = request.GET['b']
nn = request.GET['n'] ....
but in the value nn I find only the last value of the choices.
How do I do that?
Try this,
vals = request.GET.getlist("n", '')
Also bind the id to the options in your template,
<select name="n" size="3" multiple="multiple">
{% for tag in tags %}
<option value="{{ tag.id }}">{{ tag.name }}</option><br>
{% endfor %}
</select>
I have a select field in the form and now I need to iterate over options in this field.
{{ form.myselect }} gives me this:
<select name="myselect" id="id_myselect">
<option value="" selected="selected">---------</option>
<option value="2">Item 1</option>
<option value="3">Item 2</option>
...
</select>
Now I need to add some attributes to the options and because of that what I need is:
<select name="myselect" id="id_myselect">
{% for x in form.myselect %}
<option value="{{ x.id }}">{{ x.name }}</option>
{% endfor %}
</select>
but there is an error:
Caught TypeError while rendering: 'BoundField' object is not iterable
I tried form.myselect.all, form.myselect.option_set but it gives nothing
I've been struggling with this problem today and found the solution. Yes, you can iterate over options of the select tag directly in template. Here's how to do it in template:
<select id="id_customer" name="customer">
{% for x, y in form.fields.customer.choices %}
<option value="{{ x }}"{% if form.fields.customer.value == x %} selected{% endif %}>{{ y }}</option>
{% endfor %}
</select>
In this case I have a customer field in the form which has choices set up as follows:
class SomeForm(forms.Form):
customer = forms.ChoiceField(label=u'Customer')
def __init__(self, *args, **kwargs):
super(SomeForm, self).__init__(*args, **kwargs)
self.fields['customer'].choices = [(e.id, e.customer) for e in Customers.objects.all()]
Got it to work with:
<select name="myselect" class="i-can-add-my-own-attrs-now" id="id_myselect">
{% for id, name in form.myselect.field.choices %}
<option value="{{ id }}">{{ name }}</option>
{% endfor %}
</select>
BUT REALLY, a better way to do this is with django-widget-tweaks:
{% load widget_tweaks %}
{{ form.myselect|add_class:"i-can-haz-custom-classes-easily" }}
Doing it with django-widget-tweaks will also set the default 'selected="selected"' for you, which is super nice!
I do this way:
<select id="id_construction_type" name="construction_type" class="form-control input-md">
{% for value, key in form_urban.fields.construction_type.choices %}
<option value="{{ value }}"{% if form_urban.initial.construction_type == value %} selected {% endif %}>
{{ key }}
</option>
{% endfor %}
</select>
This is a cleaner solution, you can set the attributes using a custom Widget. This way you don't have to render the field manually:
class CustomSelectWidget(forms.Select):
def create_option(self, name, value, *args, **kwargs):
option = super().create_option(name, value, *args, **kwargs)
if value:
instance = self.choices.queryset.get(pk=value) # get instance
option['attrs']['custom_attr'] = instance.field_name # set option attribute
return option
class SomeForm(forms.ModelForm):
some_field = forms.ModelChoiceField(
queryset=SomeModel.objects.all(),
widget=CustomSelectWidget
)
With radio buttons in your template use.
<table>
{% for x,y in form.fields.Customer.choices %}
<tr>
<td><input id="id_Customer_{{x}}" {% if form.fields.Customer.value == x %}checked="checked"{% endif %} name="Customer" type="radio" value="{{x}}" /></td>
<td>{{ y }}</td>
</tr>
{% endfor %}
</table>