Render multiple html files and views and show it in single html file Django - django

Below shown are my files
index.html
<!-- Modal -->
<div class="modal fade modal{{link.id}}" id="createmodal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Create Contact</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<form method='POST'>
{% csrf_token %}
<div class="modal-body">
{{form.as_p}}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="Submit" class="btn btn-primary btn-delete" data-sid="{{link.id}}" >Create Contact</button>
<input type="submit" class="btn btn-primary save-btn">
</div>
</form>
</div>
</div>
</div>
new_contact.html
<!-- Modal -->
<div class="modal fade modal{{link.id}}" id="createmodal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Create Contact</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<form method='POST'>
{% csrf_token %}
<div class="modal-body">
{{form.as_p}}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="Submit" class="btn btn-primary btn-delete" data-sid="{{link.id}}" >Create Contact</button>
<input type="submit" class="btn btn-primary save-btn">
</div>
</form>
</div>
</div>
</div>
views.py
def new_contact(request):
data = Contact.objects.all()
form = CreateContactForm()
if request.method == 'POST':
form = CreateContactForm(request.POST)
if form.is_valid():
form.save()
messages.success(request, 'Link edited successfully.')
else:
messages.error(request, form.errors)
return render(request,'app/editModal.html', context={'form':form,'data':data})
def index(request):
data = Contact.objects.all()
return render(request,'app/editModal.html', context={'form':form})
I want to render new_contact.html file in index.html file. I have already used include tag but it doesn't work for my requirement. include tag includes that html file into the index file but does not render the new_contact function.
I want to render the new_contact.html file with new_contact function into index.html file.
Thank you

An important rule: Don't repeat yourself!. Or maybe you have pasted same html code by mistake?
You can't and shouldn't mix different views. Also, you cannot have two forms with the same name because the first one will be overwritten by the second one.

Related

Button type "submit" doesn't let bootstrap modal to open but type="button" doesn't fulfill my need. How to use AJAX to solve this?

I have a web page in which there is an input field. And below is an edit button. When I enter some text in the input field and press the edit button, a modal pops up and there is an input field in it also. I want to pass the text from the first input field to the input field in the modal window.
But then a problem arises. The modal window only opens when the edit button has type="button". But this type="button" doesn't submit the text input to the backend when I click the edit button. It submits the text to the backend when I use button type="submit", but then the modal doesn't open because the page reloads.
I don't know how to use AJAX, how can this be done with AJAX?
Here's my HTML code:
<div class="container">
<div class="row manage-groups">
<div class="row g-0 login_form justify-content-center" id="contactForm" novalidate="novalidate">
<form method="POST">
{% csrf_token %}
<div class="col-md-12 form-group">
<input type="text" class="login-inpt" id="name" name="type-groups" placeholder="type in the group name">
</div>
<div class="row g-0 justify-content-center group-action">
<div class="col-sm-4 submit-group">
<div>
<button type="submit" data-bs-toggle="modal" data-bs-target="#ModalAddGroups"
class="button-box">Add</button>
</div>
</div>
<div class="col-sm-4 submit-group">
<button type="button" onclick="form_submit()" data-bs-toggle="modal" data-bs-target="#ModalEditGroups"
class="button-box">Edit</button>
</div>
<div class="col-sm-4 submit-group">
<button type="submit" data-bs-toggle="modal" data-bs-target="#ModalDeleteGroups"
class="button-box">Delete</button>
</div>
</div>
</form>
</div>
</div>
</div>
<!-- Modal window for Edit button -->
<div class="modal fade" id="ModalEditGroups" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle"
aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content edit-modal">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Edit Group</h5>
<button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body grid-container">
<input type="text" value="{{ group.group_name }}">
{{ group.group_name }}
{{ group }}
<table class="edit-groupLinks">
<thead>
<tr class="header">
<th>Links</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" value="www.google.com"></td>
<td><button type="button" class="delete" aria-label="Close">
<span aria-hidden="true">×</span>
</button></td>
</tr>
</tbody>
</table>
<button class="add-linkBTN"><i class="fa fa-plus" aria-hidden="true"></i></button>
</div>
<div class="modal-ftr">
<button type="submit" class="button-box" id="footer-btn">Save</button>
</div>
</div>
</div>
</div>
Views.py file:
def manageGroups(request):
form = GroupSorting()
group = request.POST.get('type-groups', False)
content = Groups.objects.filter(group_name__contains = group)
if request.method == "POST":
form = GroupSorting(request.POST)
if form.is_valid():
form.save()
else:
form = GroupSorting()
context = {'form': form, 'group': content}
return render(request, 'posts/manage-groups.html', context)

how to save bootstrap modal form upon submit in django?

I'm new to ajax and I need help. I was able to open the modal when I clicked the Add grade, now my problem is how to save the form to the database using modal? that error page will show if I hit the save changes in modal form.
views.py
class GradeUpdateView(LoginRequiredMixin, UpdateView):
model = Subject
template_name = 'teacher/modal.html'
# fields = ['grade']
# success_url = '/'
form_class = UpdateGradeForm
def get_success_url(self):
subject = self.object.subject_name
year = self.object.year_taken
return reverse_lazy('student-list', kwargs={"subject_name_id": subject.id, "year_taken": year})
modal.html
<!-- Modal -->
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalCenterTitle">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form method="post" id="grade-form">
<div class="modal-body">
{% csrf_token %}
{{ form.as_p }}
{% comment %} <input type="submit" class="btn btn-sm btn-block btn-primary" value="Save"> {% endcomment %}
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" data-form-url="" class="btn btn-primary" id="save-form">Save changes</button>
</div>
</div>
</form>
</div>
</div>
</div>
main.js
var modalDiv = $("#modal-div");
$(".open-modal").on("click", function () {
$.ajax({
type: 'GET',
url: $(this).attr("data-url"),
success: function (data) {
modalDiv.html(data);
$("#exampleModalCenter").modal();
}
});
});
<form method="post" id="grade-form" action = " The url path where you will handle the submit of form">
<div class="modal-body">
{% csrf_token %}
{{ form.as_p }}
{% comment %} <input type="submit" class="btn btn-sm btn-block btn-primary" value="Save"> {% endcomment %}
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" data-form-url="" class="btn btn-primary" id="save-form">Save changes</button>
</div>
</div>
</form>
just add an attribute action in the following form when you click on submit it will take you to the url equivalent to href url hope you understand

Django using modals for deleting a user

I want to delete users with modals in django. I have a deletion function which I don't know how I should return to template.
views.py:
#login_required(login_url='admin_signin')
#admin_only
def admin_profiles_deletion(request, username):
context = {}
account = Account.objects.get(username=username)
account.delete()
messages.success(request, "User deleted!")
context['account'] = account
return render(request, 'HOW SHOULD I REFER MODALS HERE?', context)
And my urls.py looks:
path('admin/profile/<str:username>/delete', views.admin_profiles_deletion, name='admin_profiles_deletion'),
And finally my template is:
<td class="text-center td-actions">
<i class="la la-eye view"></i>
<i class="la la-edit edit"></i>
<a href="{% url 'admin_profiles_deletion' account.username %}" data-toggle="modal" data-target="#deleteaccount">
<i class="la la-close delete"></i>
</a>
<!-- Modal -->
<div class="modal fade" id="deleteaccount" tabindex="-1" role="dialog" aria-labelledby="deleteaccountTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="deleteaccountTitle">Delete confirmation</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<h5>Do you want to delete?</h5>
</div>
<div class="modal-footer">
<div class="col-6 text-left">
<div class="previous">
<form method="POST">
{% csrf_token %}
<input class="btn btn-danger btn-sm btn-block" type="submit" name="submit" value="Yes">
</form>
</div>
</div>
<div class="col-6 text-left">
<div class="next">
<a class="btn btn-info btn-sm btn-block" href="{% url 'accounts' %}">No</a>
</div>
</div>
</div>
</div>
</div>
</div>
</td>
In modal I want to hit YES and then delete specific account. but I don't know how to do it while I am using modals.
Try this one.
from django.shortcuts import redirect
...
def admin_profiles_deletion(request, username):
...
return redirect("/admin/profile/")
# or to return to same (previous) page:
return redirect(request.META['HTTP_REFERER'])
In your template add action attribute to your form
<form method="POST" action="{% url 'admin_profiles_deletion' account.username %}">
{% csrf_token %}
<input class="btn btn-danger btn-sm btn-block" type="submit" name="submit" value="Yes">
</form>
OR to update action attribute dynamically
<a href="#" data-url="{% url 'admin_profiles_deletion' account.username %}" class="deleteaccount">
<i class="la la-close delete"></i>
</a>
and than with jQuery
<script>
$(document).ready(function() {
$('a.deleteaccount').on( "click", function() {
event.preventDefault();
$('#deleteaccount form').attr('action', $(this).data("url"));
$('#deleteaccount').modal('show');
});
});
</script>
UPDATE - working example http://jsfiddle.net/cbzmewhq/1/
Add <span id="current_username"></span>? to your modal body.
Then with jQuery add your your desired text on click:
$('#deleteaccount #current_username').text($(this).data("username"));
BELOW IS AN EXAMPLE OF YOUR CODE
...<!-- YOUR TABLE -->
<td class="text-center td-actions">
<i class="la la-eye view"></i>
<i class="la la-edit edit"></i>
<a href="#" data-username="{{ account.username }}" data-url="{% url 'admin_profiles_deletion' account.username %}" class="deleteaccount">
<i class="la la-close delete"></i>
</a>
</td>
....<!-- YOUR TABLE -->
<!-- Modal OUT OF TABLE -->
<div class="modal fade" id="deleteaccount" tabindex="-1" role="dialog" aria-labelledby="deleteaccountTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="deleteaccountTitle">Delete confirmation</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<!-- ADD SPAN TO ADD USERNAME dynamically -->
<h5>Do you want to delete <span id="current_username"></span>?</h5>
</div>
<div class="modal-footer">
<div class="col-6 text-left">
<div class="previous">
<form method="POST">
{% csrf_token %}
<input class="btn btn-danger btn-sm btn-block" type="submit" name="submit" value="Yes">
</form>
</div>
<div class="col-6 text-left">
<div class="next">
<a class="btn btn-info btn-sm btn-block" href="{% url 'accounts' %}">No</a>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- ADD BELOW CODE TO THE BOTTOM OF BODY -->
<script>
$(document).ready(function() {
$('a.deleteaccount').on( "click", function() {
event.preventDefault();
$('#deleteaccount form').attr('action', $(this).data("url"));
$('#deleteaccount #current_username').text($(this).data("username"));
$('#deleteaccount').modal('show');
});
});
</script>

Loading form from URL in Bootstrap 3 (Django)

I have a form in a url.
I want to load it in an existing page.
I'm following this tutorial https://www.abidibo.net/blog/2014/05/26/how-implement-modal-popup-django-forms-bootstrap/
This is the form template
{% load i18n widget_tweaks %}
<div class="modal-dialog modal-lg" role="document">
<form action="{% url 'flag_post' %}" method="post" id="flag-form" class="form">{% csrf_token %}
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
<span class="sr-only">Close</span>
</button>
<h4 class="modal-title">Report Post</h4>
</div>
<div class="modal-body">
{{ form.media }}
{% render_field form.reason class="form-control" %}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<input type="submit" class="btn btn-primary" value="Save changes" />
</div>
</div><!-- /.modal-content -->
</form>
</div><!-- /.modal-dialog -->
<script>
var form_options = { target: '#modal', success: function(response) {} };
$('#flag-form').ajaxForm(form_options);
</script>
This is my link that is supposed to load the form
<a class="fa fa-pencil" data-toggle="modal" href="{% url 'flag_post' node.uid %}" data-target="#modal" title="edit item" data-tooltip></a> |
I have the following script tag embedded
<script src="http://malsup.github.com/jquery.form.js"></script>
When I call the url directly the form is displayed, but when I try clicking the button form is not loaded.
What is wrong with my code?
Is this the right way to load a form from an external URL?
I didn't have a modal placeholder.
Now I have
Report
Then at the bottom of the page
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<!-- Content will be loaded here from "remote.php" file -->
</div>
</div>
</div>
And it works! No JS and no other problems.
Now all I need to do is ajaxify my form submission.
Thanks #Sumeet Kumar
This link helped me
https://www.tutorialrepublic.com/codelab.php?topic=bootstrap&file=modal-with-remote-url

How to show wtform validation error on modal

I have a WTF Form inside a Twitter Bootstrap 3 modal, which I need to validate. The problem is that the modal closes when the user submits the form, even if there are validation errors. If I click on the button that triggers the modal again, the validation error is displayed. So my question is, how do I get the modal to stay open when there are validation errors?
Thanks!
<button type="button" class="btn btn-default" data-toggle="modal" role="dialog" data-target="#save">
<span class="glyphicon glyphicon-flash"></span>
</button>
<div class="modal fade" id="save" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 class="modal-title" id="myModalLabel">Archive List and Start New</h3>
</div>
<form role="form_list" class="form form-medium" action="." method="post">
{{ form_save.csrf_token }}
<div class="modal-body">
<h4>Save list as: </h4>
{{ render_field(form_save.list_name, class="input-large") }}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<a href="#">
<button class="btn btn-success">Archive List</button></a>
</div>
</form>
</div><!-- modal content -->
</div><!-- modal-dialog -->
</div><!-- modal -->
<script src="{{ url_for('static', filename='js/jquery.js') }}"></script>
<script src="{{ url_for('static', filename='js/bootstrap.min.js') }}"></script>
You should add some javascript to automatically open the modal when there are errors from the form.
Something like (with jQuery):
var formErrors = {% if form_errors %}true{% else %}false{% endif %};
$(document).ready(function() {
if (formErrors) {
$('.modal').modal('show');
}
});