Someone asked this same exact question but it did it not help me out. I tried implementing the tips, but my modal was still not loading within my django site. (note: I am an intermediate programmer, but not great. Not super familiar with Javascript, but have been developing in django for 2 years.)
I am trying to add an item to a grocery list. On the grocery list page, I want the user to be able to click "add item" and have the Add Item Form pop up in a modal.
I've researched and have looked through many stack overflow resources and others, as well, and cannot find a solution. It's been about 4-5 weeks of research.
Depending on the code combination I use, half the time a modal pops up with no form and half the time a grey grid overlays my screen without a modal or a form. In either case, my crispy form (and django form) will not render within the modal.
I'm assuming my form is valid, because my form will render and work perfectly when directly within the html, without a modal.
add_item_test.html
<div class="modal hide" id="itemModal">
<form class="well" method="post" action="/send_add_item/">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3>Add Item</h3>
</div>
<div class="modal-body">
{% csrf_token %}
{{form|crispy}}
</div>
<div class="modal-footer">
<input class="btn btn-primary" type="submit" value="Save" />
<input name="cancel" class="btn" type="submit" value="Cancel"/>
</div>
</form>
</div>
list.html
<section>
<div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
</div>
<a class="btn btn-primary" data-toggle="modal" href="{% url 'add_item' %}" data-target="#modal" title="add item" data-tooltip>Add Item</a>
</section>
<script>
$(".item_add_form").click(function(ev) {
ev.preventDefault();
var url = $(this).data("form");
$("itemModal").load(url, function() {
$(this).modal('show');
});
return false;
});
$('.item_add_form').live('submit', function() {
$.ajax({
type: $(this).attr('method'),
url: this.action,
data: $(this).serialize(),
context: this,
success: function(data, status) {
$('itemModal').html(data);
}
});
return false;
});
</script>
views.py
def add_item(request):
list_name = get_user_list(request.user.id)
userprofile = get_user_profile(request.user)
items = ItemModel.objects.filter(list_name=list_name).order_by('-name__iexact')
context = {
'userprofile':userprofile,
'list_name':list_name,
'items':items,
}
form = ExampleForm(request.POST, request.FILES)
context_dict = {}
form = ItemModelForm()
form.fields['lists'].queryset = ListModel.objects.filter(user=request.user)
context_dict['form'] = form
return render(request, 'ribbon/add_item_test.html', context_dict)
urls.py
url(r'^add_item/$', views.add_item, name='add_item'),
url(r'^send_add_item/$', views.send_add_item),