How to handle JavaScript event inside a inlineformset_factory with formset_media_js - javascript

I have an inlineformset_factory implemented with formset_media_js, these two by itself are working ok. What I need to implement is to be able to handle the enable and disable state of some checkboxes and input fields that are inside the inlineformset_factory.
I have a javascript that works on the first group of formset created on page load, but when a new formset is added by the user the javascript is not working.
How can I handle the new formsets input fields added by the user with javascript?
If "is chapter" is checked then "is subchapter" and "quantity" are disabled, by default the inlineformset_fatory creates 1 formset on page load, on this formset the javascript works. But when the user adds another formset with button "Add another Budget Item" the javascript is no longer working. If for example, I configure the inlineformser_factory to create 3 formset on page load the javascript works on those 3 formset but not on the formsets added by the user.
forms.py : at this forms.py i have the inlineformset_factory that is created every time the user adds a formset.
from django import forms
from django.forms import inlineformset_factory
from djangoformsetjs.utils import formset_media_js
from accounts.models import ProjectManager
from projects.models import Project, BudgetModel, BudgetModelItems
class CreateBudgetItem(forms.ModelForm):
class Media(object):
js = formset_media_js
class Meta:
model = BudgetModelItems
fields = ('budget_model',)
widgets = {
'budget_item_description': forms.Textarea(attrs={'rows': 2, 'cols': 50}),
'budget_item_item': forms.NumberInput(attrs={'size': 6}),
'budget_item_quantity': forms.NumberInput(attrs={'size': 6}),
}
BudgetItemFormset = inlineformset_factory(BudgetModel, BudgetModelItems,
form=CreateBudgetItem,
fields=('budget_model', 'budget_item_item',
'budget_item_description', 'budget_item_unit',
'budget_item_quantity', 'budget_item_is_chapter',
'budget_item_is_subchapter'),
extra=1,
can_delete=True,
can_order=True
)
views.py
from django.shortcuts import render, redirect
from django.forms import formset_factory
from accounts.models import ProjectManager
from projects.forms.create_project import CreateProjectForm
from projects.forms.create_budgetmodel import BudgetFormset, ProjectForBudgetModel
from projects.forms.create_budgetitem import CreateBudgetItem, BudgetItemFormset
from projects.models import BudgetModel, Project
def create_budget_item(request):
user = request.user.projectmanager
projects = Project.objects.filter(project_manager_id=user)
models = BudgetModel.objects.none()
project_form = ProjectForBudgetModel(user)
budget_item_form = CreateBudgetItem()
formset = BudgetItemFormset()
for project in projects:
models |= BudgetModel.objects.filter(project_id=project.pk)
budget_item_form.fields['budget_model'].queryset = models
if request.method == 'POST':
project_form = ProjectForBudgetModel(user, request.POST)
budget_item_form = CreateBudgetItem(request.POST)
if project_form.is_valid() and budget_item_form.is_valid():
# project_id = project_form.cleaned_data['project']
budget_model_id = budget_item_form.cleaned_data['budget_model']
formset = BudgetItemFormset(request.POST, instance=budget_model_id)
if formset.is_valid():
formset.save()
context = {'project_form': project_form,
'bi_form': budget_item_form,
'formset': formset,
'models': models}
return render(request, 'projects/create_budget_items.html', context)
budget_item_form.html: this form is called (included) at create_budget_items.html
<div data-formset-form>
<div class="card">
<div class="card-body">
<div class="row">
<div class="col">
<table class="table">
<thead class="thead-light">
<tr>
<th scope="col">Item</th>
<th scope="col">Description</th>
<th scope="col">Unit</th>
<th scope="col">Quantity</th>
<th scope="col">Is Chapter</th>
<th scope="col">Is SubChapter</th>
</tr>
</thead>
<tbody>
<tr>
<th>{{ form.budget_item_item }}</th>
<td>{{ form.budget_item_description }}</td>
<td>{{ form.budget_item_unit }}</td>
<td>{{ form.budget_item_quantity }}</td>
<td>{{ form.budget_item_is_chapter }}</td>
<td>{{ form.budget_item_is_subchapter }}</td>
</tr>
</tbody>
</table>
</div>
<div class="col-md-auto">
{% if form.ORDER %}
<div class="row mt-1">
<div class="d-none">{{ form.ORDER }}</div>
<button class="btn btn-info btn-block" type="button" data-formset-move-up-button>
{% trans 'Move up' %}
</button>
</div>
<div class="row mt-1">
<button class="btn btn-info btn-block" type="button" data-formset-move-down-button>
{% trans 'Move down' %}
</button>
</div>
{% endif %}
</div>
<div class="col col-lg-2 mt-1">
{% if form.DELETE %}
<div class="d-none">{{ form.DELETE }}</div>
<button type="button" class="btn btn-danger btn-block h-100" data-formset-delete-button>
{% trans 'Delete' %}
</button>
{% endif %}
</div>
</div>
</div>
</div>
</div>
create_budget_items.html: On this template I have the javascript where I control the enable and disable states of checkboxes and input fields. I thought that by calling the script inside the for loop where the formset is being iterated I was going to be able to control the input fields of the formsets added by the user. Is only working on the formsets created on page load.
{% block dashboard_head %}
{{ formset.media }}
<script type="text/javascript">
function trackDisabled(trigger_id, ...targets) {
const checkbox = document.getElementById(trigger_id);
checkbox.addEventListener('change', e => {
console.log(e.target.checked);
{#console.log(trigger_id);#}
{#console.log(...targets);#}
if (e.target.checked === true) {
targets.forEach(x => {
const element = document.getElementById(x);
element.disabled = true;
element.checked = false;
element.value = ''
})
} else {
targets.forEach(x => document.getElementById(x).disabled = false)
}
})
}
</script>
{% endblock dashboard_head %}
{% block dashboard_content %}
<h1>Create Budget Items</h1>
<form method="post">
{% csrf_token %}
{{ project_form.project }}
<select name="budget_model" id="id_budget_model" class="form-control">
{% with value=bi_form.budget_model.value %}
{% for model in models %}
<option value="{{ model.pk }}" class="{{ model.project.pk }}"
{% if model.pk|slugify == value|slugify %}selected="selected"{% endif %}>
{{ model.budget_name }}
</option>
{% endfor %}
{% endwith %}
</select>
{% load formset_tags %}
<div id="formset" data-formset-prefix="{{ formset.prefix }}">
{{ formset.management_form }}
<div data-formset-body>
{% for form in formset %}
{% include "projects/budget_item_form.html" with form=form only %}
<script>
trackDisabled(
'{{ form.budget_item_is_chapter.auto_id }}',
'{{ form.budget_item_is_subchapter.auto_id }}',
'{{ form.budget_item_quantity.auto_id }}'
);
console.log('{{ form.budget_item_is_chapter.auto_id }}');
</script>
{{ form.errors }}
{% endfor %}
</div>
<script type="form-template" data-formset-empty-form>
{% escapescript %}
{% include "projects/budget_item_form.html" with form=formset.empty_form only %}
{% endescapescript %}
</script>
<div class="row mt-3 mr-1 ml-1">
<!-- This button will add a new form when clicked -->
<div class="col text-center">
<input class="w-75 btn btn-info" type="button"
value="{% trans 'Add another Budget Item' %}" data-formset-add>
</div>
<div class="col text-center">
<button class="w-75 btn btn-success" type="submit">
{% trans 'Create Models' %}
</button>
</div>
</div>
</div>
</form>
{% endblock dashboard_content %}

This is the javascript that finally worked out, was written by a friend.. Thank you FunkyBob!
<script>
function isChapter() {
const root = document.getElementById('formset');
const prefix = root.dataset.formsetPrefix;
console.log({root, prefix});
// listen for all input changes
root.addEventListener('change', ev => {
// check if it matches out name pattern
console.log(ev.target.name);
console.log(ev.target.checked, !ev.target.checked);
console.log(`${prefix}-(\\d+)-budget_item_is_chapter`);
let m = ev.target.name.match(RegExp(`${prefix}-(\\d+)-budget_item_is_chapter`));
// if it's not {prefix}-*-budget_item_is_chapter ignore
if (!m) return;
console.log(m);
let idx = m[1]; // the matched regex group
// Find the related fields, and set them as enabled/disabled
root.querySelector(`[name="${prefix}-${idx}-budget_item_is_subchapter"]`).disabled = ev.target.checked;
root.querySelector(`[name="${prefix}-${idx}-budget_item_is_subchapter"]`).checked = false;
root.querySelector(`[name="${prefix}-${idx}-budget_item_unit"]`).disabled = ev.target.checked;
root.querySelector(`[name="${prefix}-${idx}-budget_item_unit"]`).value = ev.target.checked;
root.querySelector(`[name="${prefix}-${idx}-budget_item_quantity"]`).disabled = ev.target.checked;
root.querySelector(`[name="${prefix}-${idx}-budget_item_quantity"]`).value = ev.target.checked;
console.log("Done!")
});
}
isChapter();
</script>

Related

When using Fetch the page reloads (when it shouldn't) and only shows the Json data instead of the page that should be displayed

I am trying to make a basic twitter style application for a class project. When the like button is clicked the text in the button should then change to say unlike and the like count should increase by one without reloading the page. The database information is updated. The page itself reloads to a white background and the only thing on the page is my json data "{"likeButton": "Unlike", "total_likes": 0}", instead of the page itself. Any help would be appreciated.
Edit: here is a screenshot of the result I am getting
webpage screenshot
views.py
#login_required
def likes(request, post_id):
try:
current_user = request.user
post = Post.objects.get(id = post_id)
likeCount = Post.objects.get(id = post.id)
total_likes = likeCount.like_count
likeButton = request.POST.get('buttonForLikes')
if likeButton == 'Like':
total_likes = total_likes + 1
post.like_count = total_likes
post.save()
post.like.add(current_user)
post.save()
else:
total_likes = total_likes - 1
post.like_count = total_likes
post.like.remove(current_user)
post.save()
return JsonResponse ({'likeButton': likeButton, 'total_likes': total_likes,}, status=200,)
except KeyError:
return HttpResponseBadRequest("Like Error")
urls.py
from django.urls import path
from . import views
app_name = "network"
urlpatterns = [
path("", views.index, name="index"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
path("new-post", views.new_post, name="new-post"),
path("profile/<str:username>", views.profile, name="profile"),
path("follows/<str:username>", views.follows, name="follows"),
path("following", views.following, name="following"),
path("edit", views.edit, name="edit"),
path("likes/<int:post_id>", views.likes, name='likes')
]
HTML
{% extends "network/layout.html" %}
{% load static %}
{% block body %}
{% if user.is_authenticated %}
<div class="borderDiv">
<div class="newPostCard">
<form id = "new_post_form" name="newPost" action = "{% url 'network:new-post' %}" method ="POST">
{% csrf_token %}
<label id="test"><h2>New Post</h2></label><br>
<textarea id="newPostBox" name="newPost"></textarea></textarea><br><br>
<input type ="submit" id = "new_post_submit" class = "btn btn-primary">
</form>
</div>
</div>
{% endif %}
<div class="newPostCard">
{% for item in all_post %}
<div class="borderDiv">
<div class="newPostCard">
<h2>{{ item.user }}</h2>
<p id="user_post">{{ item.post }}</p>
</div>
<form id = "like_form" method ="POST" action = "{% url 'network:likes' item.id %}" >
{% if request.user in item.like.all %}
<div> <button claas="likes" id = 'likeButton' data-id= '{{ item.id }}' value="Unlike" name="buttonForLikes">
Unike</button>: <span id="numOfLikes">{{ item.like_count }}</span>
{% csrf_token %}
</div>
{% else %}
<div> <button class="likes" id = 'likeButton' data-id= '{{ item.id }}' value="Like" name="buttonForLikes">
Like</button>: <span id="numOfLikes">{{ item.like_count }}</span>
{% csrf_token %}
</div>
{% endif %}
</form>
<div>
{% if user.is_authenticated and request.user == item.user %}
<button class ="btn btn-primary" id="edit">Edit</button>
{% endif %}
<textarea id="editText" name="editBox" style="display: none;"></textarea>
<button class="btn btn-primary" id="editSaveButton" style="display: none;">Save</button>
</div>
<p><i>{{ item.timestamp }}</i></p>
</div>
</div>
{% endfor %}
<div id="page_num">
<span class="page_numbers">
{% if all_post.has_previous %}
« first
previous
{% endif %}
<span class="current_page">
Page {{ all_post.number }} of {{ all_post.paginator.num_pages }}.
</span>
{% if all_post.has_next %}
next
last »
{% endif %}
</span>
</div>
</div>
<script src="{% static 'network/edit.js' %}"></script>
<script src="{% static 'network/likes.js' %}"></script>
{% endblock %}
javascript
let likes = document.getElementById('likeButton');
likes.addEventListener("click", (e) =>{
e.preventDefault();
e.stopPropagation();
let likeCount = document.getElementById('numOfLikes');
fetch(`/likes/${likes.dataset.id}`, {
credentials: "include",
method: "PUT",
headers: {
"Accept": "application/json",
'Content-Type': 'application/json',
},
})
.then(response => response.text())
.then(result => {
if (result.likeButton === 'Like'){
likes.innerHTML = "Unlike";
likeCount.innerHTML = result.total_likes;
}
else{
likes.innerHTML = 'Like';
likeCount.innerHTML = result.total_likes;
}
})
return false;
});

Converting inline javascript to Alpine.js

I'm trying to avoid inline javascript and would like to convert it to Alpine.js code. Is there a way to rewrite the following piece of code in Alpine.js?
<script type="text/javascript">
window.addEventListener('DOMContentLoaded', function () {
const message = "Do you really want to remove the selected e-mail address?";
const actions = document.getElementsByName('action_remove');
if (actions.length) {
actions[0].addEventListener("click", function (e) {
if (!confirm(message)) {
e.preventDefault();
}
});
}
});
document.addEventListener('DOMContentLoaded', function () {
$('.form-group').removeClass('row');
})
</script>
Here is the full context (I'm working with Django templates):
{% extends "account/base.html" %}
{% load tailwind_filters %}
{% load crispy_forms_tags %}
{% block head_title %}
Account
{% endblock %}
{% block inner %}
<h1>E-mail Addresses</h1>
{% if user.emailaddress_set.all %}
<p>The following e-mail addresses are associated with your account:</p>
<form action="{% url 'account_email' %}" class="email_list" method="post">
{% csrf_token %}
<fieldset class="blockLabels">
{% for emailaddress in user.emailaddress_set.all %}
<div class="radio">
<label for="email_radio_{{forloop.counter}}" class="{% if emailaddress.primary %}primary_email{%endif%}">
<input id="email_radio_{{forloop.counter}}" type="radio" name="email" {% if emailaddress.primary or user.emailaddress_set.count == 1 %}checked="checked" {%endif %} value="{{emailaddress.email}}" />
{{ emailaddress.email }}
{% if emailaddress.verified %}
<span class="verified">Verified</span>
{% else %}
<span class="unverified">Unverified</span>
{% endif %}
{% if emailaddress.primary %}<span class="primary">Primary</span>
{% endif %}
</label>
</div>
{% endfor %}
<div class="form-group">
<button class="secondaryAction btn btn-primary" type="submit" name="action_primary">Make Primary</button>
<button class="secondaryAction btn btn-primary" type="submit" name="action_send">Re-send Verification</button>
<button class="primaryAction btn btn-primary" type="submit" name="action_remove">Remove</button>
</div>
</fieldset>
</form>
{% else %}
<p><strong>Sad news:</strong>You currently do not have any e-mail address set up. You should add an e-mail address so you can receive notifications, reset your password, etc.</p>
{% endif %}
<h2>Add E-mail Address</h2>
<form method="post" action="{% url 'account_email' %}" class="add_email">
{% csrf_token %}
{{ form|crispy }}
<button class="btn btn-primary" name="action_add" type="submit">
Add E-mail
</button>
</form>
{% endblock %}
{% block inline_javascript %}
{{ block.super }}
<script type="text/javascript">
window.addEventListener('DOMContentLoaded', function () {
const message = "Do you really want to remove the selected e-mail address?";
const actions = document.getElementsByName('action_remove');
if (actions.length) {
actions[0].addEventListener("click", function (e) {
if (!confirm(message)) {
e.preventDefault();
}
});
}
});
document.addEventListener('DOMContentLoaded', function () {
$('.form-group').removeClass('row');
})
</script>
{% endblock %}
You can try something like this:
Initialize the parent form element with x-data and set the state variable confirmMsg to null.
On form submit you prevent the actual submit with #submit.prevent and check whether a confirm message (confirmMsg) was set. If yes, you prompt the user to confirm the set message. If the users confirms, you reset the confirmMsg to null and submit the form with $el.submit().
On the buttons, you can just set the respective confirmMsg with #click = "confirmMsg = 'Are you sure?'".
Here is a code example:
<script src="//unpkg.com/alpinejs" defer></script>
<form
x-data="{confirmMsg: null}"
#submit.prevent="
if (confirmMsg && !confirm(confirmMsg)) return;
confirmMsg = null;
alert('Submitting form...'); $el.submit()"
>
<button
#click="confirmMsg = 'Do you really want to remove the selected e-mail address?'"
type="submit"
name="action_remove"
>
Remove
</button>
</form>

Django: Javascript error with alert box displaying values

I am creating a web application that will serve as a grocery store. The way I set it up is so the customer can come onto the website, click on the items that they would like to purchase, and then click a submit button to purchase those items. The problem I am running into is that my Javascript is not printing the correct values. In both spots, it says undefined. I will put a picture below for reference.
views.py
def inventory(request):
products = request.POST.getlist('products')
for product in products:
a = Post.objects.get(title=product)
a.quantity = a.quantity -1
a.save()
print(products)
return redirect('blog-home')
home.html
{% extends "blog/base.html" %}
{% load static %}
{% block content %}
<form action="{% url 'js' %}" method="POST" id="menuForm">
{% for post in posts %}
{% if post.quantity > 0 %}
<article class="media content-section">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2">{{ post.category }}</a>
</div>
<h2><a class="article-title" >{{ post.title }}</a></h2>
<p class="article-content"> Price: ${{ post.Price }}</p>
<p class="article-content"> Sale: ${{ post.Sale }}</p>
<input type="checkbox" id="product_{{ post.id }}" value="{{ post.title }}" form="menuForm" name="products" > Inventory count: {{ post.quantity }}
</input>
</div>
</article>
{% else %}
{% endif %}
{% endfor %}
<button id="btn" type="submit" form="menuForm">Confirm Purchase</button>
</form>
<script src="{% static "JS/javascript.js" %}" type="text/javascript"></script>
{% endblock content %}
javascript.js
function getSelectedCheckboxValues(name) {
const checkboxes = document.querySelectorAll(`input[name="${name}"]:checked`);
let values = [];
checkboxes.forEach((checkbox) => {
values.push(checkbox.value);
});
return values, tPrice;
var price = 0;
var tPrice =0;
if (values=='Milk'){
var MPrice = 3.99
tPrice = price+MPrice;
}
if (values == 'Cheese'){
var CPrice = 4.50
tPrice = price + CPrice;
}
if (values == 'Yogurt'){
var YPrice = 1.99
tPrice = price + YPrice;
}
}
const btn = document.querySelector('#btn');
btn.addEventListener('click', (event) => {
alert('You ordered: ' + getSelectedCheckboxValues('products')+
'\nTotal Price: $'+ getSelectedCheckboxValues('tPrice'));
});
First of all you are passing the parameter to the function getSelectedCheckboxValues as a string when you call them in the alert which is completely wrong.
Also you are directly comparing values list with strings which is not possible. You need to loop over the list and then compare the different elements with the different products. I will also recommend to create an object instead of the list and keep the product name as key and its price as value.

Django form not getting validated even if correct?

So I have been trying to implement a way to post a project post that is able to upload multiple images at the same time.
Both of my forms are not getting validated even tho they are correct and complete.
I am not sure what am I doing wrong.
My codes are below:
views.py
class CreateProjectsView(View):
def get(self, request):
p_photos = P_Images.objects.all()
#project_form = ProjectsForm(initial=self.initial)
project_form = ProjectsForm()
context = {
'p_photos': p_photos,
'project_form': project_form,
}
return render(self.request, 'projects/forms.html', context)
def post(self, request):
project_form = ProjectsForm(request.POST, request.FILES)
multi_img_form = P_ImageForm(request.POST, request.FILES)
if project_form.is_valid() and multi_img_form.is_valid():
instance = project_form.save(commit=False)
instance.user = request.user
instance.save()
images = multi_img_form.save(commit=False)
images.save()
data = {
'is_valid': True,
'name': images.p_file.name,
'url': images.p_file.url
}
else:
data = {
'is_valid': False,
}
return JsonResponse(data)
forms.html
{% extends "projects/test.html" %}
{% block javascript %}
<form action="{% url 'create_post:create_projects' %}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{% for hidden in project_form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in project_form %}
{{ field.errors }}
{{ field }} <br />
{% endfor %}
<input type="submit" value="OK">
{% load static %}
{# JQUERY FILE UPLOAD SCRIPTS #}
<script src="{% static 'projects/js/jquery-file-upload/vendor/jquery.ui.widget.js' %}"></script>
<script src="{% static 'projects/js/jquery-file-upload/jquery.iframe-transport.js' %}"></script>
<script src="{% static 'projects/js/jquery-file-upload/jquery.fileupload.js' %}"></script>
{# PHOTOS PAGE SCRIPTS #}
<script src="{% static 'projects/js/basic-upload.js' %}"></script>
{# 1. BUTTON TO TRIGGER THE ACTION #}
<button type="button" class="btn btn-primary js-upload-photos">
<span class="glyphicon glyphicon-cloud-upload"></span> Upload photos
</button>
{# 2. FILE INPUT TO BE USED BY THE PLUG-IN #}
<input id="fileupload" type="file" name="p_file" multiple
style="display: none;"
data-url="{% url 'create_post:create_projects' %}"
data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token }}"}'>
{# 3. TABLE TO DISPLAY THE UPLOADED PHOTOS #}
<table id="gallery" class="table table-bordered">
<thead>
<tr>
<th>Photo</th>
</tr>
</thead>
<tbody>
{% for p_photo in p_photos %}
<tr>
<td>{{ p_photo.file.name }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<h1>hahahaha</h1>
</form>
{% endblock %}
basic-upload.js
$(function () {
/* 1. OPEN THE FILE EXPLORER WINDOW */
$(".js-upload-photos").click(function () {
$("#fileupload").click();
});
/* 2. INITIALIZE THE FILE UPLOAD COMPONENT */
$("#fileupload").fileupload({
dataType: 'json',
done: function (e, data) { /* 3. PROCESS THE RESPONSE FROM THE SERVER */
if (data.result.is_valid) {
$("#gallery tbody").prepend(
"<tr><td><a href='" + data.result.url + "'>" + data.result.name + "</a></td></tr>"
)
}
}
});
});
No errors are getting posted are shown on my terminal. Its just that nothing simply happens. Nothing is getting uploaded to my database.

Using Select2 with flask-wtforms

After select2 manipulates the dropdown field the regular use of form.owner_id.data yields None. How can I extract the selected option from a select2 field.
If I disable the select2 javascript, wtforms will work just fine and I will be able to use form.owner_id.data. (but it looks ugly)
screenshot of rendered form
forms.py
class ProjectForm(FlaskForm):
owner_id = SelectField('Owner:', [validators.Required()], choices=[], render_kw={"placeholder": "Owner company *"})
(rest of form has been truncated for simplicity)
views.py
#app.route('/new_project/<int:company_id>', methods=('GET', 'POST'))
def new_project(company_id):
membership = Membership.query.filter_by(user_id=current_user.id, company_id=company_id).first()
company = Company.query.filter_by(id=company_id).first_or_404()
form = ProjectForm()
form.owner_id.choices = [(str(comp.id), repr(comp)) for comp in Company.query.all()]
form.client_id.choices = [(str(comp.id), repr(comp)) for comp in Company.query.all()]
form.contractor_id.choices = [(str(comp.id), repr(comp)) for comp in Company.query.all()]
form.membership_id.choices = [(str(comp.id), repr(comp)) for comp in Company.query.all()]
if request.method == 'POST':
flash(str(form.owner_id.data), 'success')
if form.validate_on_submit():
project = Project()
connection = Assignment()
# PROJECT DETAILS
project.title = form.title.data
project.description = form.description.data
project.owner_id = int(form.owner_id.data)
_macro
{% macro render_select_field(field, placeholder='Select...', label='Select an option below') %}
<div class="form-group">
<label>{{ label }}</label>
<select data-placeholder="{{ placeholder }}" class="select-size-xs">
<option></option>
{% for choice in field.choices %}
<option value="{{ choice[0] }}">{{ choice[1] }}</option>
{% endfor %}
</select>
{% if field.errors %}
{% for error in field.errors %}
<span class="help-block text-danger"><i class="icon-cancel-circle2 position-left"></i>{{ error }}</span>
{% endfor %}
{% endif %}
</div>
{% endmacro %}
html
<form method="POST" action="{{ url_for('new_project', company_id=company.id) }}" enctype="multipart/form-data" role="form">
<div class="panel panel-body login-form">
<div class="text-center">
<div class="icon-object text-muted"><i class="icon-plus2"></i></div>
</div>
{{ form.hidden_tag() }}
<div class="text-center form-group"><span>Project details</span></div>
{{ new_render_field(form.title, icon="icon-quill2", class_='form-control') }}
{{ new_render_field(form.description, icon="icon-stack-text", class_='form-control', rows=10) }}
{{ render_select_field(form.owner_id, placeholder="Who's doing the work?", label="Select the owner company") }}
{{ render_select_field(form.client_id, placeholder="Where do the bills go?", label="Select the client company") }}
{{ new_render_field(form.default_client_rate, icon="icon-price-tag", class_='form-control') }}
{{ new_render_field(form.default_contractor_rate, icon="icon-price-tag", class_='form-control') }}
<!-- THE REST OF FORM HAS BEEN TRUNCATED FOR SIMPLICITY -->
<div class="form-group">
<button type="submit" class="btn bg-pink-400 btn-block">Create</button>
</div>
</div>
</form>
So after analyzing the select field in the inspect window, it became apparent that the select field is missing the name="{{ field.name }}" that wtforms requires in order to validate the form. The simple change made in my _macro was from this:
<select data-placeholder="{{ placeholder }}" class="select-size-xs">
To this:
<select data-placeholder="{{ placeholder }}" class="select-size-xs" name="{{ field.name }}">
With this addition wtforms can now validate, and find the selected option returning the proper id for form.owner_id.data.

Categories