how to display checkbox multi-select in django - django

if I select all checkbox then my checkbox display only one thing
i want display multi select checkbox in django. what is problem in my code?
in html
<form action="" method="GET">
<label style="color: gray;" > 확장자 -</label>
{% for extention in file_extention %}
{% if extention.name == extention_name %}
<input type="checkbox" name="extention_name" value="{{ extention.name }}" checked>{{ extention.name }}
{% else %}
<input type="checkbox" name="extention_name" value="{{ extention.name }}"> {{ extention.name }}
{% endif %}
{% endfor %}
</form>
in views.py
if request.method == 'GET':
png = {'name' : '.png'}
jpg = {'name' : '.jpg'}
gif = {'name' : '.gif'}
file_extention = [png, jpg, gif]
context = {}
context['file_extention'] = file_extention
extention_name = request.GET.get('extention_name',None)
context['extention_name'] = extention_name
return render(request, 'home/index.html',context)```

You're currently breaking out of your IF statement when it hits the first match. Consider moving the if statement to within your input tag so each input tag in the loop is checked for matches. Something like this within your for loop should do it:
<input type="checkbox" name="extention_name" value="{{ extention.name }}"
{% if extention.name == extention_name %}checked{% endif %}>
{{ extention.name }}

Related

convert string value to integer in Django template

In home.html
<div class="container">
<div class="row">
<div class="col-md-6">
<h3>Select products:</h3>
<form id="selectProduct" role="search" method="get" action="{% url 'home' %}">
<select name="parameters" data-placeholder="Choose products" class="chosen-select" multiple tabindex="4">
{% for p in productnames %}
{% if k == p %}
<option value="{{ p.productnames }}" selected> {{ p.productnames }} </option>
{% else%}
<option value="{{ p.id }}"> {{ p.productnames }} </option>
{% endif %}
{% endfor %}
</select><br/>
<label for="submit"></label><button id="submit" type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</div>
<div class="row"></div><br />
<h3> Distribution of sales in the products:</h3>
</div>
</div>
{% for p in productList %}
{% for pin in productnames %}
<p>{{pin.id}} {{p}}</p>
{% if p == pin.id %}
<p>exists</p>
{% else %}
<p>not exist</p>
{% endif %}
{% endfor %}
{% endfor %}
<p>{{ productList }}</p>
in this html file 'p' always returns a string value for ex: it returns like '10' instead of 10. all i want is to convent this '10' to 10 or convert returned other p_in value to 10 to '10'.
in views.py
def productList(request):
if request.method == 'GET':
p = request.GET.get('parameters')
print(p)
#k = request.GET('parameters[]')
productnames = Products.objects.all()
context = {
'productList': p, 'productnames': productnames,
}
return render(request, 'home.html', context)
I tried to convert the values of the p in product list to integer. because it dosen't mactch the format with pin.id
You filter the queryset in the template using if-else which is not ideal. Instead you should perform this filtering in the view itself. Also your parameters is a select tag which may have multiple selected values yet you use .get('parameters') which will only give you one value instead you should use the getlist method [Django docs] of the QueryDict:
def productList(request):
if request.method == 'GET': # Do you even need to check this? You appear to only use a GET request...
p = request.GET.getlist('parameters')
productnames = Products.objects.all()
filtered_products = Products.objects.filter(pk__in=p)
context = {
'productList': p, 'productnames': productnames, 'filtered_products': filtered_products
}
return render(request, 'home.html', context)
In the template your loop would simply become:
{% for product in filtered_products %}
{{ product.productnames }}
{% endfor %}
Note: You should use a form class instead of manually making a form. See Building a form in
Django.
Also a models name should be singular hence instead of
Products you should name it Product. In general in
your code you also break various naming conventions in Python, I would
suggest you to look at PEP 8 -- Style Guide for Python
Code
In views.py
def productList(request):
if request.method == 'GET':
p = request.GET.getlist('parameters')
print(p)
#k = request.GET('parameters[]')
productnames = Products.objects.all()
context = {
'productList': p, 'productnames': productnames,
}
# --- logic later for chart ------
return render(request, 'home.html', context)
In home.html
<div class="container">
<div class="row">
<div class="col-md-6">
<h3>Select products:</h3>
<form id="selectProduct" role="search" method="get" action="{% url 'home' %}">
<select name="parameters" data-placeholder="Choose products" class="chosen-select" multiple tabindex="4">
{% for p in productnames %}
{% if k == p %}
<option value="{{ p.productnames }}" selected> {{ p.productnames }} </option>
{% else%}
<option value="{{ p.id }}"> {{ p.productnames }} </option>
{% endif %}
{% endfor %}
</select><br/>
<label for="submit"></label><button id="submit" type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</div>
<div class="row"></div><br />
<h3> Distribution of sales in the products:</h3>
</div>
</div>
{% for p in productList %}
{% for pin in productnames %}
<p>{{pin.id|stringformat:"s"}} {{p}}</p>
{% if p == pin.id|stringformat:"s" %}
<p>exists</p>
{% else %}
<p>not exist</p>
{% endif %}
{% endfor %}
{% endfor %}
<p>{{ productList }}</p>
Note {{value|stringformat:"s"}} can be used to convert integer value to string value

Change login label in Django auth form

I'm trying to change the login username label but without any success. Here is the website:
What I'd like to do is print "Usuário and e-mail" instead of just "Usuário" label:
I didn't customize the login form, in this way, I'm using all standard auth process.
#template
<form action="{% url 'login' %}" method="post">
{{ form.as_p }}
{% csrf_token %}
<input type="hidden" name="next" value="{{ next }}" />
<p><input type="submit" value="Login"></p>
</form>
If you guys have any suggestion modifying the input field through CSS style, it's welcome as well!
Thanks!
EDIT:
{% for field in form %}
<div class="fieldWrapper">
{% if field.label_tag == 'Usuário' %}
{% field.label_tag = 'Usuário ou e-mail:' %}
{% elif %}
{{ field.label_tag }}
{% endif %}
{{ field.label_tag }}{{ field }}
</div>
{% endfor %}
Value the label in the attribute form.

How to get flask form field value into Jijnja2 URL in HTML

I am new to Flask. I want to pass flask_mongoengine.wtf field value to jijnja URL into HTML.
There is my code. I want to pass {{ form.from_time_filter }} form field value to the formtime='{{form.from_time_filter}}' How i can do it?
{% macro render_pagination(page, endpoint ) %}
<div class=pagination>
{%- for page in posts.iter_pages() %}
{% if page %}
{% if page != posts.page %}
{{ page }}
{% else %}
<strong>{{ page }}</strong>
{% endif %}
{% else %}
<span class=ellipsis>…</span>
{% endif %}
{%- endfor %}
</div>
{% endmacro %}
{{ render_pagination(posts, 'test_list') }}
<form method="POST">
{{ form.from_time_filter.label }} {{ form.from_time_filter }}
{{ form.to_time_filter.label }} {{ form.to_time_filter }}
{{ form.incon_filter.label }} {{ form.incon_filter }}
{{ form.wordtype_filter.label }} {{ form.wordtype_filter }}
<input type="submit" value="Filter">
</form>
I am not sure if this will help but I'll try to give an answer.
I am using a form to handle searches on my flask based website, the code for the form looks as follows:
<form action="{{ url_for('index') }}" class="form-inline" id="search-form" method="get" role="search">
<div class="form-group">
<input class="form-control" name="q" placeholder="Search" type="text" value="{% if search %}{{ search }}{% endif %}">
</div>
</form>
The python code that then handles the input looks as follows:
def get_entries(offset=0, per_page=5, table=""): # Used in Index
search_query = request.args.get('q')
page = request.args.get(get_page_parameter(), type=int, default=1)
if search_query:
entries = table.search(search_query).where(table.published == True).order_by(table.timestamp.desc()).paginate(page, per_page)
print(entries)
else:
entries = table.select().where(table.published == True).order_by(table.timestamp.desc()).paginate(page, per_page)
print(entries)
return entries[offset: offset + per_page]
When my search form is used it redirects to the /index page, the /index page then checks if there is a value with the name 'q' (this name is specified in the input tag using name="q") if there is, the URL will look like this:
when I search for "iframe".
And just in case you need it this is what my route for /index looks like:
#app.route('/') # For browsing and searching up blog entries
#app.route('/index')
def index():
table = Entry
pagination_entry = get_entries(table=table)
pagination = get_pagination_entries(table=table)
return render_template('index.html', pagination=pagination, pagination_entry=pagination_entry)

Django next page in pagination on form submission

def listing(request):
contact_list = Question.objects.all()
paginator = Paginator(contact_list, 1) # Show 25 contacts per page
page = request.GET.get('page')
contacts = paginator.get_page(page)
Let's say in each page I have a form, and when the form submitted I need to go to the next page.
I first tried to add a hidden field in the form, and manually calculate the next page, and put into HTTPResponseRedirect, but then I get an empty object error for the last page because of the following:
<input type="hidden" name="next" value="?page={{ contacts.next_page_number }}">
That page contains no results
{% for contact in contacts %}
{# Each "contact" is a Contact model object. #}
{{ contact.question_text|upper }}<br>
...
<form action="{% url 'listing' %}" method="post">
{% csrf_token %}
{% for choice in contact.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}">
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br>
<input type="hidden" name="next" value="?page={{ contacts.next_page_number }}">
{% endfor %}
<input type="submit" value="Vote">
</form>
{% endfor %}
<div class="pagination">
<span class="step-links">
{% if contacts.has_previous %}
« first
previous
{% endif %}
<span class="current">
Page {{ contacts.number }} of {{ contacts.paginator.num_pages }}.
</span>
{% if contacts.has_next %}
next
last »
{% endif %}
</span>
</div>
So what should be my strategy? Do I need to create a seperate view for form action, or should I use listing as form action and check wheter it is a GET/POST method, I am kind of lost here.

Using Datepicker in Django

I am using Django and Datepicker together with Twitter-Bootstrap and I want the form.fields to have same class and same id if they are of same widget(DateInput). In specific, i would like to change the id accordingly. It should have a different id every time.
This is the class i defined below. How do i change the id to be a different one every time.
class MyDatePicker(forms.DateInput)
def __init__(self, *args, **kwargs):
attrs = kwargs.pop("attrs",{})
attrs["class"] = "datepick"
attrs["id"] ="date_1"
kwargs["attrs"] = attrs
super(MyDatePicker, self).__init__(*args, **kwargs)
How do i go about doing it?Need some help on it...Would welcome any suggestion...
You could register a templatetag to find out the widget type:
#register.filter('klass')
def klass(obj):
return obj.__class__.__name__
Then in your template:
{% load your_filter_module %}
<form id="form" enctype="multipart/form-data" class="form-horizontal" method="POST" action="">{% csrf_token %}
<fieldset>
{{ form.non_field_errors }}
{% for field in form %}
<div class="control-group{% if field.errors %} error{% else %}{% if form_errors %} success{% endif %}{% endif %}">
<label class="control-label" for="{{ field.auto_id }}">{% trans field.label %}</label>
<div class="controls">
{% if field.field.widget|klass == "CheckboxInput" %}
<label class="checkbox">
<input type="checkbox" id="{{ field.auto_id }}" name="{{ field.name }}"{% if field.value == "on" %} checked{% endif %}>
{% trans "Some random text" %}
</label>
{% endif %}
# ... etcetera continue check for other classes ...
Note: A cleaner DRY approach would be to add the loop and class logic (horizontal/vertical etc) to a filter returning a html widget