Placing a <select> field using Django templates with custom bootstrap styles - html

I am having an issues connecting my html css javascript front-end with django. I have html templates that look and work exactly as I want them too. I can display data without issue with I make a call to a django field that is part of my current view using:
<a>{{ thing.attribute }}</a>
That works great.
My issue is when trying to connect a form to the django view I created for updating and creating records using a POST action. For example, when using an mdbootstrap themed template, I have implemented an html <select> object like this:
<select type="select" class="mdb-select" id="fieldOne">
<option value="0">Something</option>
<option value="1">Something</option>
<option value="2">Something</option>
</select>
This works and looks exactly like I want it too as it is correctly utilizing the proper css and javascript.
When I want to place a django form object in place of the same field, I have to call it like this:
<div class="mdb-select">{{ thing.attribute }}</div>
I have to call it as a <div> in django, and it's breaking my css and javascript, thus not displaying correctly and not usable. I can see the data being returned when I look at the rendered html in dev tools, so I know my django views and forms are working.
Is there any way to call a django object while still utilizing the <select> tags in my html template?

1) If you're using model forms, do one one this:
Use django widget_tweaks and then in your template do this:
{% load widget_tweaks %}
<label>{{my_form.field.label}}</label>
{% render_field my_form.field class="mdb-select" name="field" %}
OR
class NewSomethingForm(ModelForm):
class Meta:
model = Account
fields = ['name', 'last_name', 'description']
def __init__(self, *args, **kwargs):
self.fields['description'].widget = forms.Textarea(attrs={'class': 'md-textarea', 'style': 'height: 75px'})`enter code here`
2) If you're not using model forms, then in your template, try this:
<select type="select" class="mdb-select" id="fieldOne" name=field>
<option value="my_form.field_name.field.choices.0">my_form.field_name.field.choices.1</option>
<!–– follow same sequence -- >
</select>
Don't forget to give the dropdown element a name that matches the field on the form.

You can render a select field using Django ModelChoiceField. When you use this form in template using {{yourForm.select_field_name}} it will be rendered as with
id:id_select_field_name
name:select_field_name
The css classes you need to associate are included in attrs
from django import forms
class yourForm(forms.Form):
select_field_name=forms.ModelChoiceField(queryset=recieptDetail.objects.all(), widget = forms.Select(attrs = {'class':"class-name",'onchange' : "jsFunction();"}))

Related

Flask WTForms SelectField add placeholder or disabled option

I am working on a webpage using flask and wtforms. When opening the webpage, my selectfield should not hold any value (i.e. be blank, have placeholder saying "please choose an option" or something in that direction).
My form is defined like this in forms.py:
class Form(FlaskForm):
selectfield = SelectField('Title', choices=[])
I leave choices as an empty list because they are created from a database through the function get_choices:
# create instance of form
form = Form()
# run function to get data from db
form.selectfield.choices = get_choices()
Here it starts to get gnarly: Since the placeholder value should be empty (i.e. "") or something like "please choose" I don't want to have it in my database. So I add the value manually:
# append
form.selectfield.choices.append('Please choose')
The html part, where I render the form looks like this:
<form method="POST" action= {{ url_for('index') }}>
{{ form.csrf_token }}
{{ form.selectfield(class_="form-control", **{"onchange":"this.form.submit()"}) }}
</form>
What have I tried:
adding 'placeholder = "please choose"' here:
{{ form.selectfield(placeholder="please choose", class_="form-control", **{"onchange":"this.form.submit()"}) }}
(as suggested by Crast here: WTForms Can I add a placeholder attribute when I init a field?)
adding default="Please choose" to my Form class as suggested by Liu Yue (How do you set a default value for a WTForms SelectField?):
class Form(FlaskForm):
selectfield = SelectField('Title', choices=[], default="Please choose")
This works partly, but the Please Choose value should not be selectable which it still is.
I feel like I might be completely on a wrong path here, and maybe oversee a very simple feature. I really can't believe that such a popular feature is not available using wtforms.
I am thankful for any advice and guidance.

How to disable a choice in django forms ChoiceField

Here is an exemple of what I have:
forms.py
class aForm(forms.Form):
choices = [
('value1', 'choice1'),
('value2', 'choice2'),
('value3', 'choice3')
]
dropDownList = forms.ChoiceField(
choices=choices)
I want to add the attribute Disabledd to the first choice, like this:
<select>
<option selected value="value1" disabled>choice1</option>
<option selected value="value2">choice2</option>
<option selected value="value3">choice3</option>
</select>
How can I add that Disabled attribute from the forms.py file ?
After long search I didn't find the solution am looking for, but I did pass that problem with another aproch, what I did is creating a completly RAW html form from scratch where I had full power so I added the "disabled" attribute to the first option, without touching the views.py file, what I mean is am still using forms.Form and all the validations I already writen, this works by just naming your the fields in the RAW html form the same names as in the Form.
You can have a look at solution to this question. It pretty much addresses the same.
Disable Choice In ModelMultipleChoiceField CheckBoxSelectMultiple Django

How to populate html input in Django framework without using a any of Django form?

I'm implementing an HTML table that is populated with information as the page is rendered. I cannot use a form here but still, I need to embed some common input controls to certain s in that HTML table (selection boxes).
So I think the data itself can be passed to the template as the page is being rendered but do I need to use javascript to fill the controls? I think I cannot use anything related to forms here.
I have implemented a javascript ajax code to get the data when the table is filled by a user. That is working perfectly. But the user does not fill everything on that table but there must be some selections done before the data can be submitted. That data is read from the database, delivered to the HTML table for the user to make a selection.
But I have never used HTML inputs other than in Django forms.
Or is there a better solution to achieve this?
Edit: As the code that is given here as an answer is used the dropdown content of the selection control, it contains two classes as attributes: dropdown-content and select-dropdown. I changed the z-index in order to bring the dropdown box to the top. It did open but the container did hide the dropdown items inside it. So I made a test and by setting z-index to be large enough and the dropdown content came front. I have not used z-index before so please forgive me if I have done something funny here.
.dropdown-content {
z-index: 33;
position: relative;
}
.select-dropdown {
z-index: 32;
position: relative;
}
if your data form model, you can use return data to html, like this:
views.py
def articleCreate(request):
categrays = Categray.objects.all()
context = {'categrays':categrays}
return render(request, 'article/articleCreate.html', context)
and use {% for %} add your data to html.
<div class="categray">
<label>Categray:</label><br>
<select name=categray>
{% for categray in categrays %}
<option value={{categray.id}}>{{ categray.name }}</option>
{% endfor %}
</select>
</div>

Create "static" HTML Pages For Each Product

I have 10k+ products that need their HTML Page and the stuff within is to be static (thus searchable). I am trying to find a way to do the following using django:
Loop over all the items.
Get the matching information.
Fill a model template.
Save such template with the information now static.
As much as I tried looking here on Stack Overflow and in the web, I did not find any instructions to do so.
Build a standard template that has variables for the products. Then on the backend you can search for the products you want and populate the template with their information. Something like this for a concept:
search.html
<form action="{% url 'your_url' %}" method="POST">
{% csrf_token %}
<input type=text name=input value="" />
<input type="submit" value="Submit">
product.html
<html>
<div>Hello {{name}}!</div>
</html>
models.py
class Names:
user_name = models.CharField(max_length=200)
def __str__(self):
return self.user_name
views.py
input = request.POST['input']
name = Names.objects.get(user_name=input)
return render_to_response('product.html', {'name': name})
This will allow your user to search something, pull up the record searched, and place it in the template.
You can use that system for any number of variables.

How to integrate HTML form into django view and model?

I have one html file which contain submission form.
I want to use this HTML form in django with model and view.
I dont want to use form class in html like
<form method="post" action="">
{% csrf_token %}
{{ form }}
<input type="submit" value="Register"/>
</form>
I want to use complete form code in HTML and use django model to store that data in database.
How can I do that?
Please update the question that you want to use jQuery.Django by defaults generate id for its form element.
As avinash already said you can always inspect the element and get the id and classses but some time we need custom class in that case you can use something like.
If you want to write your own custom fields.
class myForm(forms.ModelForm):
class Meta:
model = ModeName
widgets = {
'field_one': forms.TextInput(attrs={'id':'foo', 'name':'foo'})
'field_two': forms.TextInput(attrs={'id':'bar', 'name':'bar'})
}