Trigger bootstrap modal after django form submission - django

How can I trigger the bootstrap modal to popup after my django form was submitted?
In my index.html template I have a standard looking modal like this
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
below in the same index.html I have a django form
{{ form.non_field_errors }}
{% csrf_token %}
<ul id="robul">
<div class="form-group">
<div class="col-xs-6">
<li id="name" name="{{ form.name.name }}" class="form-control">{{ form.name }}</li>
</div>
</div>
<div class="form-group">
<div class="col-xs-6">
<li id="email" class="form-control">{{ form.email }}</li>
</div>
</div>
<div class="form-group">
<div class="col-xs-6">
<li id="contactmessage" class="form-control">{{ form.contactmessage }}</li>
</div>
</div>
</ul>
in my view.py it looks like this:
if request.method == 'POST':
form = forms.FormName(request.POST)
if form.is_valid():
contact_name = request.POST.get(
'name', '')
contact_email = request.POST.get(
'email', '')
form_content = request.POST.get('contactmessage', '')
template = get_template('contact_template.txt')
context = {'name': contact_name,
'email': contact_email,
'contactmessage': form_content,}
content = template.render(context)
mail = EmailMessage("New contact form submission", content, "Some Name" +'', ['somegmail#gmail.com'],
headers = {'Reply-To': "noreply#gmail.com" })
mail.send()
return render(request, 'index.html', {'form': form})

The modal and JS code to trigger it live in a different context than your Django form submission code. Rendering 'index.html' is basically starting fresh when you're returning from your form submission, so it essentially amounts to showing the modal on page load. But, maybe you only want to show it after a successful submit. What you'll have to do is have some JS code to show the modal on page load, and have something in your template rendering context to conditionally render that. Here's what I'm thinking:
In index.html:
{% if successful_submit %}
<script type="text/javascript">
$(document).ready(function(){
$("#exampleModal").modal('show');
});
</script>
{% endif %}
In your view function, add the successful_submit context variable to your return:
return render(request, 'index.html', {'form': form, 'successful_submit': True})
Now, that <script> tag will only be rendered if successful_submit is True, which will only be set after a successful form POST.

Related

How to implement change password modal form?

EDIT 14/07/2021
Reading this blog post (https://simpleisbetterthancomplex.com/tips/2016/08/04/django-tip-9-password-change-form.html) I understand how to prevent user logout (update_session_auth_hash(self.request, self.object) added to form_valid function) and I am very close to the solution using attempt #2
BUT
there still have "grey" screen after user pasword successfully changed and user have to click on screen to make it disappeared...
EDIT 14/07/2021
I quite closeto the solution following this tutorial https://www.abidibo.net/blog/2015/11/18/modal-django-forms-bootstrap-4/
Neverthless it is not working correctly.
attempt #1: get_success_url
I override get_success_url funtion of PasswordChangeView to redirectto index page and use SuccessMessageMixin to confirm password change. Password is correctly changed but somthig is going wrong with return (see capture below)
attemp #2: form_valid
I've tried another way overriding form_valid function that return JsonObject. Password is also changed but screen stay as modal was still opened. When I click on screen, "grey" diappeared but if I refresh page (F5) i am redirected to home page and I am disconnected without error... and message "Your password has been successfully changed" is displayed even if modal return error...
I have implemented authentification using Django django.contrib.auth and it work but I would like change_password to be displayed using modal form and Ajax.
And I do not manage to even display the form inside modal (with all validation stuff).
I have already use bootstrap modal to display information but not for form submission. As it did not call a change_password view that render change_password_form.html template, form is not available and I got an error Parameter "form" should contain a valid Django Form.
How should I do this?
urls.py
class PasswordChangeView(SuccessMessageMixin, auth_views.PasswordChangeView):
<!-- attempt #1 -->
success_message = "Your password have been changed successfully."
def get_success_url(self):
return reverse('export:index')
<!-- attempt #2 -->
# def form_valid(self, form):
# self.object = form.save()
# update_session_auth_hash(self.request, self.object) # prevent user’s auth session to be invalidated and user have to log in again
# return JsonResponse ({'data': 'success'},status = 200)
app_name = 'registration'
urlpatterns = [
...
path('change_password/', PasswordChangeView.as_view(), name='password_change'),
...
]
password_change_form.html (modified)
{% load bootstrap4 %}
<div id = "password_change" class="modal-dialog modal-lg" role="document">
<form action="{% url 'registration:password_change' %}" method="post" id="password_change" class="form">{% csrf_token %}
<div class="modal-content">
<div class='card' style="border-top-width: 0px;border-left-width: 0px;border-bottom-width: 0px;border-right-width: 0px;">
<div style="background-color:#326690;padding:5px 5px 5px 16px;color:white;font-weight:bold;border-radius: 2px 2px 0 0;">Change password</div>
<form method="post" class="form-signin">
<div class='card-body' style="padding-bottom:0px">
{% csrf_token %}
{% bootstrap_form form layout="horizontal" placeholder="None" size="medium" label_class="form-label col-md-3" %}
</div>
<hr style="margin:1px">
<div class='card-body' style="padding-top:5px;padding-bottom:5px;">
<div>
<button type="submit" class="btn block" style="float:right;background-color:#326690;color:white;min-width:110px;">{% trans 'Confirm' %}</button>
<!--<i class="fa fa-times" aria-hidden="true"></i> {% trans 'Cancel' %} -->
<span data-dismiss="modal" class="btn btn-light border" style="float:right;color:#326690;min-width:110px;margin-right:5px;"><i class="fa fa-times" aria-hidden="true"></i> {% trans 'Cancel' %}</span>
</div>
</div>
</form>
</div>
</form>
</div>
<script>
var form_options = { target: '#modal', success: function(response) {
console.log('response',response);
//obj = JSON.parse(response);
$("#password_change_confirm").append('<div class="alert alert-success"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button><span>Your password has been changed successfully.</span></div>');
} };
$('#password_change').ajaxForm(form_options);
</script>
base.html (modified)
<a data-toggle="modal" data-target="#modal" class="dropdown-item" href="{% url 'registration:password_change' %}"><i class="fa fa-key" aria-hidden="true"></i>
{% trans 'Change password' %}</a>
<div class="modal" id="modal"></div>
index.html (added)
{% extends 'layouts/base.html' %}
...
<!-- message for change password in authentification module -->
<div id="password_change_confirm" style="padding-top:10px;padding-left:10px;padding-right:10px;"></div>
{% for message in messages %}
<div class="container-fluid" style="padding:10px 10px 10px 10px;">
<div id = 'msg' class="alert {{ message.tags }} alert-dismissible" role="alert" >
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
{{ message }}
</div>
</div>
{% endfor %}
<!-- end message for change password in authentification module -->
OK, I finally find a 'hack' solution that works, do know if it is the better way but it's works:
base.html
<!-- https://www.abidibo.net/blog/2015/11/18/modal-django-forms-bootstrap-4/ -->
<div class="modal" id="modal" style="margin-top:150px;"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.3.0/jquery.form.min.js" integrity="sha384-qlmct0AOBiA2VPZkMY3+2WqkHtIQ9lSdAsAn5RUJD/3vA5MKDgSGcdmIv4ycVxyn" crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#modal').on('show.bs.modal', function (event) {
var modal = $(this)
$.ajax({
url: "{% url 'registration:password_change' %}",
context: document.body
}).done(function(response) {
modal.html(response);
});
})
)};
registration/views.py
class PasswordChangeView(auth_views.PasswordChangeView):
def form_valid(self, form):
self.object = form.save()
update_session_auth_hash(self.request, self.object) # prevent user’s auth session to be invalidated and user have to log in again
return JsonResponse ({'data': form.is_valid()},status = 200)
registration/urls.py
app_name = 'registration'
urlpatterns = [path('change_password/', PasswordChangeView.as_view(), name='password_change'),]
registration/template/registration/password_change_form.html
<!-- https://www.abidibo.net/blog/2015/11/18/modal-django-forms-bootstrap-4/ -->
{% load i18n widget_tweaks %}
{% load bootstrap4 %}
<div id = "password_change" class="modal-dialog modal-lg" role="document">
<form action="{% url 'registration:password_change' %}" method="post" id="password_change" class="form">{% csrf_token %}
<div class="modal-content">
<div class='card' style="border-top-width: 0px;border-left-width: 0px;border-bottom-width: 0px;border-right-width: 0px;">
<div style="background-color:#326690;padding:5px 5px 5px 16px;color:white;font-weight:bold;border-radius: 2px 2px 0 0;">Change password</div>
<form method="post" class="form-signin">
<div class='card-body' style="padding-bottom:0px">
{% csrf_token %}
{% bootstrap_form form layout="horizontal" placeholder="None" size="medium" label_class="form-label col-md-3" %}
</div>
<hr style="margin:1px">
<div class='card-body' style="padding-top:5px;padding-bottom:5px;">
<div>
<button type="submit" class="btn block" style="float:right;background-color:#326690;color:white;min-width:110px;">{% trans 'Confirm' %}</button>
<span data-dismiss="modal" class="btn btn-light border" style="float:right;color:#326690;min-width:110px;margin-right:5px;"><i class="fa fa-times" aria-hidden="true"></i> {% trans 'Cancel' %}</span>
</div>
</div>
</form>
</div>
</form>
</div>
<script>
var form_options = { target: '#modal', success: function(response) {
<!-- test for form validation status: password changed confirmation message displayed only if form is valid -->
if(response.data == true){
<!-- remove grey background -->
$('body').removeClass('modal-open');
$('.modal-backdrop').remove();
$("#password_change_confirm").append('<div class="alert alert-success"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button><span>Your password has been changed successfully.</span></div>');
}
} };
$('#password_change').ajaxForm(form_options);
</script>
myapp/emplate/myapp/index.html
<!-- message for change password in authentification module -->
<div id="password_change_confirm" style="padding-top:10px;padding-left:10px;padding-right:10px;"></div>

Using Bootstrap Modal as Register and Login Form. On error the full page is served

I am using jquery.bootstrap.modal.forms.js to load Login and Register form from their url as Modals using the code below:
<script>
$(function ($, undefined) {
// log in & sign up buttons
$(".register-btn").modalForm({
modalID: "#registerModal",
formURL: "/register-modal/",
});
});
$(function ($, undefined) {
// log in & sign up buttons
$(".login-btn").modalForm({
modalID: "#registerModal",
formURL: "/login-modal/",
});
});
$(function ($, undefined) {
// log in & sign up buttons
$(".forgot-password").modalForm({
modalID: "#registerModal",
formURL: "/recover-modal/",
});
});
</script>
HTML code for the modal
<div class="modal fade" id="registerModal" tabindex="-1" role="dialog" aria-labelledby="registerModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document" style="width:400px;">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="registerModalLabel">Register</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Modal Code :
{% extends 'base.html' %}
{% load static %}
{% block title %} Login {% endblock %}
{% block style %}
{% endblock %}
{% block content %}
<div class="container-fluid ">
<div class="row ">
<div class="col-sm-12 col-xs-12 col-md-12">
<form class="account-register form-narrow p-3 mb-4 bg-white" id="login_form" method="POST"
action="" autocomplete="off">
{% if messages %}
<div id="messages">
{% for message in messages %}
<div class="alert alert-dismissible alert-info"
role="alert">
<button type="button" class="close" data-dismiss="alert"
aria-label="Close">
<span aria-hidden="true">×</span>
</button>
{{ message|escape }}
</div>
{% endfor %}
</div>
{% endif %}
{% if form.non_field_errors %}
<div id="messages">
{% for message in form.non_field_errors %}
<div class="alert alert-dismissible alert-danger"
role="alert">
<button type="button" class="close" data-dismiss="alert"
aria-label="Close">
<span aria-hidden="true">×</span>
</button>
{{ message|escape }}
</div>
{% endfor %}
</div>
{% endif %}
<div class="text-center">
<h4><i class="fa fa-lock fa-3x"></i></h4>
</div>
<h4 class="text-center mb-5">Login </h4>
{% csrf_token %}
<div class="form-group{% if form.username.errors %} has-error{% endif %}" >
<label class="control-label" for="id_username">Email Address</label>
<input class="form-control input-lg" id="id_username" maxlength="150" name="username" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$" type="text" required />
<div class="error-block">{{ form.username.errors }}</div>
</div>
<div class="form-group{% if form.password.errors %} has-error{% endif %}">
<label class="control-label" for="id_password">Password</label>
<div class="input-group input-group-lg">
</div>
<input class="form-control input-lg" id="id_password" name="password" type="password" required />
<div class="error-block">{{ form.password.errors }}</div>
</div>
<div class="g-recaptcha mb-2" data-sitekey="6LebmPsZAAAAADT_1QjnC70TJ2aiBX1a9rqWmhev"
style="transform:scale(1.1);-webkit-transform:scale(1.1);transform-origin:0 0;-webkit-transform-origin:0 0;">
</div>
<button type="submit" name="login"
class="btn btn-danger btn-sm btn-block text-uppercase shadow-4 mb-4" >
Login<i class="fa fa-sign-in" aria-hidden="true"></i>
</button>
<br/>
<p class="text-center">
Don't have an account?<button type="button" class="register-btn a btn btn-link" style="font-size:14px; margin-top:-4px;">Register </button>
</p>
<br/>
<p class="text-center text-primary">
<button type="button" class="forgot-password a btn btn-link" style="font-size:14px; text-decoration:none;">Forgot user ID and/or password? </button>
</p>
</form>
</div>
</div>
</div>
<!-- /container -->
{% endblock %}
{% block scripts %}
<script src="{% static 'js/toggle.js' %}"></script>
<script src="{% static 'js/floating-wpp.min.js' %}"></script>
<script src="{% static 'js/jquery.magnific-popup.js' %}"></script>
<script src="{% static 'js/qoc_home.js' %}"></script>
<script src='https://www.google.com/recaptcha/api.js'></script>
<script src="{% static 'js/jquery.bootstrap.modal.forms.js' %}"></script>
<script>
$(document).ready(function(){
$("#login_form").on("submit", function(){
$("#pageloader").css('visibility', 'visible');
});//submit
});
$(function ($, undefined) {
// log in & sign up buttons
$(".register-btn").modalForm({
modalID: "#registerModal",
formURL: "/register-modal/",
});
});
$(function ($, undefined) {
// log in & sign up buttons
$(".forgot-password").modalForm({
modalID: "#registerModal",
formURL: "/recover-modal/",
});
});
</script>
{% endblock %}
LoginView Code
class LoginViewModal(FormView):
template_name = 'login-modal.html'
form_class = LoginForm
success_url = '/dashboard'
def get(self, request, *args, **kwargs):
if request.user.is_authenticated:
return redirect ("/dashboard")
else:
return super(LoginViewModal, self).get(request, *args, **kwargs)
def dispatch(self, request, *args, **kwargs):
if (self.request.user.is_authenticated) and (self.request.user.user_type==4):
return redirect('/dashboard')
else:
return super().dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
"""Use this to add extra context."""
context = super(LoginViewModal, self).get_context_data(**kwargs)
if 'show_captcha' in self.request.session:
show_captcha = self.request.session['show_captcha']
context['show_captcha'] = True
return context
def form_valid(self, form):
user = form.login(self.request)
recaptcha_response = self.request.POST.get('g-recaptcha-response')
url = 'https://www.google.com/recaptcha/api/siteverify'
payload = {
'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,
'response': recaptcha_response
}
data = urllib.parse.urlencode(payload).encode()
req = urllib.request.Request(url, data=data)
# verify the token submitted with the form is valid
response = urllib.request.urlopen(req)
result = json.loads(response.read().decode())
if result['success']:
if user.two_factor_auth is False and (user.phone_number_verified is True):
login(self.request, user)
try:
UserLog.objects.filter(username=user.id).update(failed_attempt=0)
except Exception:
print("No failed attempts ")
return redirect('/dashboard')
else:
try:
response = send_verfication_code(user)
pass
except Exception as e:
messages.add_message(self.request, messages.ERROR,
'verification code not sent. \n'
'Please retry logging in.')
return redirect('/login')
data = json.loads(response.text)
if data['success'] == False:
messages.add_message(self.request, messages.ERROR,
data['message'])
return redirect('/login')
if data['success'] == True:
self.request.method = "GET"
print(self.request.method)
kwargs = {'user':user}
return PhoneVerificationView(self.request, **kwargs)
else:
messages.add_message(self.request, messages.ERROR,
data['message'])
return redirect('/login')
else:
messages.add_message(self.request, messages.ERROR, 'Invalid reCAPTCHA. Please try again.')
return redirect('/login')
When an error occurs in the form (for example if the user enters incorrect password. The modal redirects to /login-modal/ and a full page with login form is seen instead of returning to the same modal. What can I do in order to stay on the modal when error occurs ?
Correct me if I am wrong, what you are trying to achieve here is that when a user enters incorrect credentials, for example, you want to show an error message on the page without having to reload so that the credentials are not lost? if that is the case, you must use AJAX/fetch API, I'd go for AJAX since you're already using jquery, you can send the data using jquery $.post
Implementing AJAX with Django is a bit complicated but a simple google search would do, this tutorial explains how to implement a login and signup mechanism using ajax and Django.
Now if you just want to show the modal again when an error you could have an error variable as a boolean, with 0 being no errors and 1 being the opposite, and pass it to your front-end, and have a script tag in your HTML that will trigger the modal when there is an error.

Form Validation Not Displaying on Form

I have a custom form validation that runs on my popup window form. If the form validation occurs i get a bad request error which is what i have programmed in my views.py . How do i render it so the user stays on the form and the validation message displays. Thanks for the help. Here is my code.
#login_required
def K8_Points_Classroom(request):
#context_from_k8_points = request.session['k8_points_context']
if request.method == 'POST':
form = K8Points_ClassroomForm(request.POST)
if form.is_valid():
form.save(commit=False)
form.save()
class_name = form.cleaned_data.get('class_name')
getstudents = Student.objects.filter(class_name = class_name)
students = getstudents.all()
form = K8Points_ClassroomForm()
context = {'form': form ,'students' : students, 'class_name': class_name,}
return render(request,'points/k8_points_classroom.html', context)
else:
return HttpResponseBadRequest("Bad Request")
else:
return render(request, 'points/k8_points_classroom.html', {'form': form} )
Updated form.html
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% crispy K8Points_ClassroomForm %}
{% load static %}
{% block content %}
<br>
<h2>{% load static %}
<img src="{% static 'forms/star.png' %}" alt="chain" height="62" width="62"> {{class_name}}</h2>
<br>
<br>
<form action="/points/k8_points_classroom" method="POST">
{% csrf_token %}
<!-- Start Date -->
<div class="container">
<div class="container">
<div class='row'>
<div class="col-4">
<p> Recording Data as User : {{user.username}} </p>
</div>
</div>
<div class='row'>
<div class = "col-2">
{{form.date|as_crispy_field }}
</div>
<div class = "col-2">
{{form.week_of|as_crispy_field }}
</div>
<div class = "col-2">
{{form.day|as_crispy_field }}
</div>
</div>
</div>
</form>
<div class="jumbotron" align="middle">
<img src="{% static 'forms/levelup.png' %}" alt="levelup" height="120" width= "120">
<h1>My Students</h1>
<!-- Line Break -->
<hr style="border: 1px solid black;"/>
<!-- Line Break -->
<div class="row mb-3">
{% for i in students%}
<div class="col-md-4 themed-grid-col"><h2>{{i.student_name}}</h2>
<p align="left"> Today's Score: {{total}}</p>
<h4>
<button type="button" class="btn btn-primary btn-lg btn-block" data-toggle="modal"
data-target="#PointsBox{{ student.pk }}">Level Up
</button>
</h4>
<div id="PointsBox{{ student.pk }}" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<img src="{% static 'forms/star.png' %}" align="left" alt="chain" height="42"
width="42">
<h4 class="modal-title">Points Confirmation </h4>
<button type="button" class="close" data-dismiss="modal"> ×</button>
</div>
<div class="modal-body">
<h6>
<div class="modal-body">Please add the selected points for the current
student.</div>
</h6>
<form action="/points/k8_points_classroom" method="POST">
{% csrf_token %}
<div class="form-row" align='left'>
<div class="col-7">
{{form.class_name|as_crispy_field }}
<input type="student_name" class="form-control" value ="{{i}}" >
{{form.time_frame|as_crispy_field }}
</div>
</div>
<div class="form-row">
<div class="col-3" align='left'>
{{form.behavior|as_crispy_field }}
{{form.academic|as_crispy_field }}
<button type="submit" class="btn btn-success" ><i
class="fas fa-star"></i> Level Up
</button>
</div>
</div>
</div>
<div class="modal-foot"></div>
</div>
</div>
</div>
</div>
</form>
{% endfor %}
{% endblock %}
You can't return a bad response if the form is invalid. Instead, render the page again with the invalid form and in the temolate you will be able to render the errors. Try starting rendering the form just using {{ form.as_p }} and you will see the errors. The form errors are in form.errors and each field has its own errors, you can access to them form.field.erorrs
if request.method == 'POST':
form = K8Points_ClassroomForm(request.POST)
if form.is_valid():
form.save(commit=False)
form.save()
class_name = form.cleaned_data.get('class_name')
getstudents = Student.objects.filter(class_name = class_name)
students = getstudents.all()
form = K8Points_ClassroomForm()
context = {'form': form ,'students' : students, 'class_name': class_name,}
return render(request,'points/k8_points_classroom.html', context)
return render(request, 'points/k8_points_classroom.html', {'form': form} )

How do you implement a Form in a ListView

I'm new to Django, I basically have a homepage which has a search bar that is being implement using a Django Form. Additionally, in the homepage I have bootstrap card whichis being used to display data from my model.
I'm using the def_get to render the form (since it's being used to query the DB). The form is very basic, it's just a CharField. However, when I use the def_get to render the Form in my class based view it now doesn't retrieve any of the data that goes into the bootstrap card which is causing the card to not display.
I've tried to render both the form and data in the card by using ModelFormMixin but it seems like this hasn't solved my issue yet, not sure whether this is the way to achieve this?
Forms.py
from django import forms
class SearchBarForm(forms.Form):
q = forms.CharField(label="", max_length=150, required=True)
Views.py
from django.views.generic import TemplateView
from django.views.generic.list import ListView
from property.models import Property
from pages.forms import SearchBarForm
from django.shortcuts import render
class HomePageView(ListView):
model = Property
template_name = 'home.html'
def get(self, request):
form = SearchBarForm()
return render(request, self.template_name, {'form': form})
Home.html
{% extends 'base.html' %}
{% block title %}Home{% endblock %}
{% block content %}
<div class="container">
<!-- search bar -->
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-8 custom-search-bar">
<form action="{% url 'property_for_rent' %}" method="get" id="search-form">
{{ form.as_p }}
</form>
</div>
<div class="col-xs-6-md-4 custom-search-bar-button">
<button type="submit" form="search-form" class="btn btn-light" value="For sale">For rent</button>
<button form="rent" type="submit" class="btn btn-light" value="For sale">For Sale</button>
</div>
</div>
<!-- search bar -->
<!-- property card -->
<div class="row">
{% for property in object_list|slice:"3" %}
<div class="col-lg-4 d-flex align-items-stretch custom-cards">
<div class="card" style="width: auto;">
<div class="card-img">
{% if property.image %}
<img class="card-img-top" src="{{property.image.url}}" alt="Card image cap"> {% endif %}
</div>
<div class="card-body">
<h5 class="card-title"> {{ property.location }} </h5>
<p class="card-text">{{ property.description }} </p>
<button type="button" class="btn btn-primary waves-effect waves-light" data-toggle="modal" data-target="#modal-{{ property.id }}">View</button>
</div>
<div class="card-footer">
<small class="text-muted">Last updated</small>
</div>
</div>
<!-- property card -->
<!-- Full Height Modal Right -->
<div class="modal fade right" id="modal-{{ property.id }}" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<!-- Add class .modal-full-height and then add class .modal-right (or other classes from list above) to set a position to the modal -->
<div class="modal-dialog modal-full-height modal-right" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title w-100" id="myModalLabel">{{ property.location }}</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>{{ property.description }}</p>
<ul class="list-group z-depth-0">
<li class="list-group-item justify-content-between">
Bedrooms
<span class="badge badge-primary badge-pill">14</span>
</li>
<li class="list-group-item justify-content-between">
Price
<span class="badge badge-primary badge-pill">2</span>
</li>
<li class="list-group-item justify-content-between">
Location
<span class="badge badge-primary badge-pill">1</span>
</li>
<li class="list-group-item justify-content-between">
Property Type
<span class="badge badge-primary badge-pill">14</span>
</li>
</ul>
</div>
<div class="modal-footer justify-content-center">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
<!-- Full Height Modal Right -->
</div>
{% endfor %}
</div>
</div>
{% endblock %}
What I want to achieve is to both display the search bar and the cards which are using data from my models.
Any hints on how to achieve this is much appreciated as i'm just a beginner :) Thanks!
You can just pass your form in the get_context_data method [Django-doc]:
class HomePageView(ListView):
model = Property
template_name = 'home.html'
def get_context_data(self, *args, *kwargs):
context = super().get_context_data(*args, **kwargs)
context['form'] = SearchBarForm()
return context
or you can make this more declarative, by making use of the FormMixin mxin [Django-doc]:
from django.views.generic.edit import FormMixin
class HomePageView(FormMixin, ListView):
model = Property
template_name = 'home.html'
form_class = SearchBarForm

how to render a djangoform into bootstrap modal window

I am strating to learn Django and I want to display some forms in bootstrap modal view.
I have a template with a HTML table, this table have a column with a drop down button with several options.
the table is rendered with django-tables2 and the forms are rendered with django-crispy-forms
My form definition for the modal form:
class RecepcionForm(forms.ModelForm):
fecha_recepcion = forms.DateField(widget=DateInput())
def __init__(self,*args,**kwargs):
super(RecepcionForm,self).__init__(*args,**kwargs)
self.helper = FormHelper(self)
self.helper.layout = Layout(
Field('id_proveedor',
'anio',
'mes',
'usuario',
readonly = True
),
Fieldset('',
'fecha_recepcion',
'num_archivos',
Submit('save','Grabar'),
HTML('<a class="btn btn-danger" href={% url "monitor" %}>Cancelar</a>')
)
)
class Meta:
model = DetalleRecepcion
My view for the modal form:
#login_required(login_url='/login/')
def RecepModalView(request):
idp = request.GET.get('i')
anio = request.GET.get('a')
mes = request.GET.get('m')
if request.method == 'POST':
r = DetalleRecepcion.objects.get(id_proveedor=idp,anio=anio,mes=mes)
form = RecepcionForm(request.POST, instance=r)
if form.is_valid():
form.save()
return HttpResponseRedirect('/monitor/')
else:
r = DetalleRecepcion.objects.get(id_proveedor=idp,anio=anio,mes=mes)
r.usuario = request.user
form = RecepcionForm(instance=r)
return render_to_response('recepmodal.html',
{'form':form},
context_instance=RequestContext(request))
My template for the modal form
{% load crispy_forms_tags %}
<div class="modal fade" id="recmodal" 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>
<h4 class="modal-title" id="myModalLabel">Register </h4>
</div>
<div class="modal-body">
<form action="" method=post">
<div class="tab-content">
<div class="tab-pane active" id="tab1">
{% crispy form %}
</div>
</form>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary">Submit</button>
</div>
</div>
</div>
</div>
I don't know how to open and pass arguments to the modal form.
I try using the django tag include
Example snippet:
<body>
<table>
.
.
.
</table>
{% include 'recmodal.html' %}
</body>
but I get this error
Exception Value: Failed lookup for key [form] in
In simple word how can I pass values and open a bootstrap modal form in django using django-crispy-forms.
Any advice
Thansk in advance
I know it's too late to answer, but I render my forms in a modal using this into a "modal-body" tag:
<form method="post">
{% csrf_token %}
{% form.as_p %}
</form>
I hope this work for all people like me that we came here finding an answer.
Regards.