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();"}))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With