I am looking to slightly edit the default password_reset_form.html provided by django-registration. The current output is:
I would like to remove the 'E-mail address:' label and put a 'placeholder' text inside the input box. How can you accomplish this? I can't seem to find documentation on form.email or form.email.errors.
Password_reset_form.html is shown below:
{% extends "registration/registration_base.html" %}
{% load i18n %}
{% block title %}{% trans "Reset password" %}{% endblock %}
{% block content %}
<p>
{% blocktrans %}
Forgot your password? Enter your email in the form below and we'll send you instructions for creating a new one.
{% endblocktrans %}
</p>
<form method="post" action="">
{% csrf_token %}
{{ form.email.errors }}
<p><label for="id_email">{% trans 'E-mail address:' %}</label> {{ form.email }} <input type="submit" value="{% trans 'Reset my password' %}" /></p>
</form>
{% endblock %}
{# This is used by django.contrib.auth #}
you can use this package.
So your code will look like this.
{% extends "registration/registration_base.html" %}
{% load i18n %}
{% load widget_tweaks %}
{% block title %}{% trans "Reset password" %}{% endblock %}
{% block content %}
<p>
{% blocktrans %}
Forgot your password? Enter your email in the form below and we'll send you instructions for creating a new one.
{% endblocktrans %}
</p>
<form method="post" action="">
{% csrf_token %}
{{ form.email.errors }}
<p> {{ form.email|attr:"placeholder:E-mail address:" }} <input type="submit" value="{% trans 'Reset my password' %}" /></p>
</form>
{% endblock %}
{# This is used by django.contrib.auth #}
Related
I am developing a domestic worker booking app in django
When I try to pass the formset, I am not geting the label of that field. I am only getting the field in html.
{% for formset in formsets %}
<form method="post">
{% for form in formset %}
{% for field in form %}
<div>
<label for="{{ field.auto_id }}">{{ field.label }}</label>
{{ field }}
{% for error in field.errors %}
<p>{{ error }}</p>
{% endfor %}
</div>
{% endfor %}
{% endfor %}
<input type="submit" value="Submit">
</form>
{% endfor %}
This the html code
def staffApply(request,pk):
if request.method == 'POST':
selected_domestic_works = request.POST.getlist('domestic_works')
formsets = []
if 'cook' in selected_domestic_works:
formsets.append(CookingForm(request.POST,prefix='cook'))
if 'driver' in selected_domestic_works:
formsets.append(DriverForm(request.POST,prefix='driver'))
print(formsets)
return render(request, 'staffApply2.html', {'formsets': formsets})
return render(request,'staffapply.html',{'uid':pk})
enter code here
This is my views.py
class CookingForm(ModelForm):
food_cooked=(('veg','veg'),
('non-veg','non-veg'),
('both','both')
)
class Meta:
model = Cook
fields = '__all__'
exclude=['user']
widgets={
'food_cooked':forms.widgets.RadioSelect(),
'type_of_cuisine':forms.widgets.CheckboxSelectMultiple()
}
This is my forms.py
I am getting the fields to type. But I am not getting hte label for those fields. Please help me fix this.
class Cook(models.Model):
food_cooked=(('veg','veg'),
('non-veg','non-veg'),
('both','both')
)
type_of_cuisine=(('NorthIndian','NorthIndian'),
('SouthIndian','SouthIndian'),
('Chettinadu','Chettinadu'),
('Chinese','Chinese'),
)
user=models.ForeignKey(User,on_delete=models.CASCADE)
food_cooked=models.CharField(choices=food_cooked,max_length=30)
type_of_cuisine=models.CharField(choices=type_of_cuisine,max_length=30)
experience=models.IntegerField()
wages_expected=models.IntegerField()
dishwashing_flag=models.BooleanField()
wages_for_dishwashing=models.IntegerField(null=True)
desc=models.TextField(max_length=200)
This is my models.py
You have one extra loop, with the wrong naming so you cannot access {{ field.label }} on your loops its like you are trying something like {{ form.field.attribute.label }}, the correct way would be the following:
{% for form in formsets %}
<form method="post">
{% for field in form %}
<div>
<label for="{{ field.auto_id }}">{{ field.label }}</label>
{{ field }}
{% for error in field.errors %}
<p>{{ error }}</p>
{% endfor %}
</div>
{% endfor %}
<input type="submit" value="Submit">
</form>
{% endfor %}
That being said, you can also use Django form rendering options, instead of doing it manually.
{% for form in formsets %}
<form method="post">
{{form.as_p}}
<input type="submit" value="Submit">
</form>
{% endfor %}
I have a Django form in which I use crispy-forms along with bootstrap5. Everything was alright until I wanted to changed the Layout of my form. As my form is constructed dynamically, I just wanted to define the value of a set element item which is under the form (field_name, layout_index). The goal was to define it as a FieldWithButton, as I couldn't find another way to do that.
To do that, I modified my helper in the __init__ method of my form :
self.helper[item[1]] = Div(FieldWithButtons(item[0], StrictButton("Add item")), id=f'div_id_{item[0]}', css_class='mb-3 row')
This is rendered nearly correctly in my form, I have the FieldWithButton with Div etc. However, the div which contains my FieldWithButton doesn't take the field_class of my helper that I defined, and instead creates a <divclass='col-10'>...</divclass='col-10'>.
There's juste a space which disappeared and messed everything up. How can I either remove the class='col-10' part of my div and put it as its class or differently define my Field as a FieldWithButton ?
Here's my whole form class if needed :
class ScriptInputForm(forms.Form):
def __init__(self, *args, **kwargs):
variables = kwargs.pop('variables') # All variables to render
variables_names = [*variables] # under the form {'name':['type', 'description']}
super().__init__(*args, **kwargs)
for var in variables_names: # Dynamic creation of the fields
values = variables[var]
field = self.fields[var] = forms.CharField()
field.widget.attrs['placeholder'] = values[1].title()
self.helper = FormHelper(self)
num = 1 # Rough part where I define the tuples ('name', 'index') of all lists in my variables
lists = []
for k,v in variables.items():
if v[0]=='list':
lists.append((k,num))
num+=1
for item in lists: # Part where the problem is coming from
self.helper[item[1]] = Div(FieldWithButtons(item[0], StrictButton("Add item")))
self.helper.add_input(Submit('submit', 'Submit'),)
self.helper.label_class = 'col-2'
self.helper.field_class = 'col-10'
self.helper.form_action = reverse_lazy('scripts:data_input')
And the rendered HTML :
<div>
<div class="mb-3 row">
<label for="id_liste" class="col-form-label col-2">Liste</label>
<divclass="col-10"> <!-- With <div class="col-10"> everything's ok -->
<div class="input-group">
<input type="text" name="liste" placeholder="Your List" class="textinput textInput form-control" id="id_liste">
<button class="btn" type="button">Add item</button>
</div>
</divclass="col-10">
</div>
</div>
Seems like it was an error in crispy-bootstrap5.
The FieldWithButtons display is defined in field_with_buttons.html whose code is the following :
<div{% if div.css_id %} id="{{ div.css_id }}"{% endif %} class="mb-3{% if 'form-horizontal' in form_class %} row{% endif %}{% if wrapper_class %} {{ wrapper_class }}{% endif %}{% if field.css_classes %} {{ field.css_classes }}{% endif %}{% if div.css_class %} {{ div.css_class }}{% endif %}" {{ div.flat_attrs }}>
{% if field.label and form_show_labels %}
<label for="{{ field.id_for_label }}" class="{% if 'form-horizontal' in form_class %}col-form-label {% else %}form-label {% endif %}{{ label_class }}{% if field.field.required %} requiredField{% endif %}">
{{ field.label }}{% if field.field.required %}<span class="asteriskField">*</span>{% endif %}
</label>
{% endif %}
<div{% if field_class %}class="{{ field_class }}"{% endif %}> <!-- Here -->
<div class="input-group{% if input_size %} {{ input_size }}{% endif %}">
{% if field.errors %}
{% crispy_field field 'class' 'form-control is-invalid' %}
{% else %}
{% crispy_field field 'class' 'form-control' %}
{% endif %}
{{ buttons|safe }}
</div>
{% for error in field.errors %}
<p id="error_{{ forloop.counter }}_{{ field.auto_id }}" class="text-danger mb-0"><small><strong>{{ error }}</strong></small></p>
{% endfor %}
{% include 'bootstrap5/layout/help_text.html' %}
</div>
</div>
Just had to add a space at the start of the second div to fix the issue.
I googled for this, and the radio button should have the same 'name' attribute to allow only a single value to be chosen.
So I did, and It's still allowing me to choose multiple values...
I used HTML and Jinja2 templates for this, so the code might be looking a bit strange..
{% if search_keyword == None: %}
<p>Please enter your search keyword</p>
{% else: %}
{% for i in range(0, 10) %}
<form method="POST" action="./search">
<h2>
<input type="radio" name="selected_food" id="{{ i }}" value="{{ search_data["hits"][i]['recipe']['label'] }}">
{{ search_data["hits"][i]['recipe']['label'] }}
</h2>
<h4>
Calroies: {{ '%0.2f'| format(search_data["hits"][i]['recipe']['calories']) }} kcal
</h4>
{% for j in range(0, 40) %}
<p>{{ search_data['hits'][i]['recipe']['ingredientLines'][j] }}</p>
{% endfor %}
</form>
{% endfor %}
{% endif %}
In the above code the loop is creating multiple forms. This is the reason why you're able to select multiple values in radio.
If you can modify your code like this, it will work
{% if search_keyword == None: %}
<p>Please enter your search keyword</p>
{% else: %}
<form method="POST" action="./search">
{% for i in range(0, 10) %}
<div>
<h2>
<input type="radio" name="selected_food" id="{{ i }}" value="{{ search_data["hits"][i]['recipe']['label'] }}">
{{ search_data["hits"][i]['recipe']['label'] }}
</h2>
<h4>
Calroies: {{ '%0.2f'| format(search_data["hits"][i]['recipe']['calories']) }} kcal
</h4>
{% for j in range(0, 40) %}
<p>{{ search_data['hits'][i]['recipe']['ingredientLines'][j] }}</p>
{% endfor %}
</div>
{% endfor %}
</form>
{% endif %}
I am a super beginner with HTML, however, I am trying to resolve an issue with my website. I am trying to concatenate a wildcard(*) to the end of whatever a consumer tries to search so that it picks up similarly tagged items, however, I cannot figure out where to add said code... Our current search query works well when pulling up items based on partial keywords, but when hitting the 'enter' button it will say it could not find any products.
Additional notes: This is a Shopify website with a theme from halothemes so most of this is coded by them.
{% assign grid_results = true %}
<div class="search-page collection-template" data-search-page>
<div class="container">
{% if search.performed %}
{% comment %}
Avoid accessing search.results before the opening paginate tag.
If you do, the pagination of results will be broken.
{% endcomment %}
{% paginate search.results by 15 %}
{% comment %}
We don't have any results to show. Feel free to show off featured products
or suggested searches here.
{% endcomment %}
{% if search.results_count == 0 %}
<header class="page-header">
<h2>
{% render 'multilang' with settings.search_1 %}
<strong> "{{ search.terms }}" </strong>
{% render 'multilang' with settings.search_2 %}
</h2>
</header>
{% else %}
<header class="page-header">
<h2>
{% render 'multilang' with settings.search_3 %}
<strong> "{{ search.terms }}" </strong>
{% render 'multilang' with settings.search_4 %}
</h2>
</header>
{% comment %}
Each result template, based on the grid_layout variable above
{% endcomment %}
<div class="block-row col-main">
{% if grid_results == false %}
<div class="product-collection products-list product-search row">
{% for product in search.results %}
<div class="grid-item col-12{% if settings.product_image_border%} grid-item-border{% endif %}">
{% render 'search-result' with product as product %}
</div>
{% endfor %}
</div>
{% else %}
<div class="products-grid product-search row product-collection">
{% for product in search.results %}
<div class="grid-item col-6 col-md-4{% unless settings.layout_style == 'layout_style_1170' %} col5 col-lg-3{% endunless %}{% if settings.product_image_border%} grid-item-border{% endif %}">
{% if settings.style_product_grid == 'style_product_grid_2' %}
{% render 'product-grid-item-style-2' with product as product %}
{% else %}
{% render 'product-grid-item' with product as product %}
{% endif %}
</div>
{% endfor %}
</div>
{% endif %}
</div>
{% endif %}
{% if paginate.pages > 1 %}
<div class="padding">
{% render 'pagination-page' paginate: paginate %}
</div>
{% endif %}
{% endpaginate %}
{% else %}
{% comment %}
If search.performed is false, someone either accessed the page without
the q parameter, or it was blank.
Be sure to show a search form here, along with anything else you want to showcase.
{% endcomment %}
<header class="page-header">
<h2 style="text-align:center" {% if settings.enable_multilang %}data-translate="general.search.title"{%endif%}>{{ 'general.search.title' | t }}</h2>
<div class="header-search__form">
<form action="/search" method="get" class="search-bar" role="search">
<input type="hidden" name="type" value="product">
<input type="search" name="q"
{% if settings.enable_multilang %} data-translate="general.search.placeholder" translate-item="placeholder"{% endif %}
placeholder="{{ 'general.search.placeholder' | t }}"
class="input-group-field" aria-label="Search Site" autocomplete="off">
<button type="submit" class="btn icon-search">
{% render 'icon-search' %}
</button>
</form>
</div>
</header>
{% endif %}
Please let me know if you guys need any additional information! Thank you!
You can use a simple script to add a wildcard to the search query on submitting the form e.g:
var searchForm = document.querySelector(".search-bar");
searchForm.addEventListener("submit", function(e) {
var searchInput = searchForm.querySelector("[name=q]");
var q = searchInput.value;
if (!q.match(/\*$/)) {
e.preventDefault();
searchInput.value = q + "*";
searchForm.submit();
}
});
I have a form with 2 CharFields. Both have label="xyz".
If I use this form in a formset, the lables are not shown in the HTML
I have tried looking at the rendered HTML and the label is missing. I have tried just a form and that works.
Forms:
class WindingVoltsSpecifier(forms.Form):
winding_name = forms.CharField(max_length=20, label="Winding name")
voltages = forms.CharField(max_length=20, label="Voltages")
View:
def add_mains_transformer_primary_configs(request):
# Add a new config
# Create the formset, specifying the form and formset we want to use.
# From https://whoisnicoleharris.com/2015/01/06/implementing-django-formsets.html
VoltsSpecifierFormSet = formset_factory(WindingVoltsSpecifier)
if request.method == 'POST':
pass
else:
mt_config_form = MainsTransformerConfiguration()
volts_formset = VoltsSpecifierFormSet()
context = {
'mt_config_form' : mt_config_form,
'volts_formset' : volts_formset,
}
return render(request, 'designer/mains_configs.html', context)
Template:
{% extends 'designer/base.html' %}
{% load crispy_forms_tags %}
{% block title %}configuration{% endblock %}
{% block content %}
{% load static %}
<h1>Configuration</h1>
<form method="post">
{% csrf_token %}
{{ mt_config_form|crispy }}
{{ volts_formset.management_form|crispy }}
{% for volts_form in volts_formset %}
<table>
{% for form in volts_form %}
{{ form }}
{% endfor %}
<table>
<!--<div class="volts-formset">
{{ volts_form.winding_name }}
{{ volts_form.voltages }}
</div>
-->
{% endfor %}
{% if volts_formset.non_form_errors %}
{% for error in volts_formset.non_form_errors %}
{{ error|escape }}
{% endfor %}
{% endif %}
<input type="submit" value="Update Profile" class="button" />
</form>
<script>
$('.volts-formset').formset({
addText: 'add winding',
deleteText: 'remove'
});
</script>
{% endblock %}
I would expect the label to be beside the field.
Labels are not rendered with fields, you will have to do a {{ FIELD.label_tag }}.
It will be something like this:
<table>
{% for field in volts_form %}
{{ field.label_tag }}
{{ field }}
{% endfor %}
<table>
More info: Looping over the forms fields - Django documentation
Hope this solution to works!
{% for field in volts_forms %}
{{ field.name}} <!-- label name -->
{{ field }}<!-- ex. input -->
{% endfor %}