modal contact form in django does not appear - django

I am trying to add contact form using bootstrap modal, so far contact modal pops up but with out the form. I have already checked couple of examples on internet but still no luck.
Here is my code from files:
in urls.py
url(r'^contact/$', view=ContactFormView.as_view(), name='contact'),
forms.py
class ContactForm(forms.Form):
firstname = forms.CharField()
lastname = forms.CharField()
sender = forms.EmailField(required=True)
subject = forms.CharField(max_length=100, required=True)
message = forms.CharField(widget=forms.Textarea, required=True)
cc_myself = forms.BooleanField(required=False)
def send_email(self):
# send email using the self.cleaned_data dictionary
pass
views.py
class ContactFormView(FormView):
template_name = 'feedme/contact.html'
form_class = ContactForm
success_url = '/thanks/'
success_message = "Congratulations !"
def form_valid(self, form):
# This method is called when valid form data has been POSTed.
# It should return an HttpResponse.
form.send_email()
return super(Contact, self).form_valid(form)
and templates:
contact.html
<!-- Modal -->
<div class="modal fade" id="contact" 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">Formularz kontaktowy</h4>
</div>
<div class="modal-body">
<form id="ContactForm" action="{{ contact }}" method="post">
{% csrf_token %}
{{ form.as_p }}
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Zamknij</button>
<button type="button" class="btn btn-success" id="add-btn">Wyslij</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
_nav.html
{% include "feedme/contact.html" %}
<!-- Fixed navbar -->
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/"><span class="glyphicon glyphicon-globe yellow"></span>Polski Kanal</a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="{% block navbar_class-nl %}{% endblock %}">Holandia</li>
<li class="{% block navbar_class-de %}{% endblock %}">Niemcy</li>
<li class="{% block navbar_class-en %}{% endblock %}">Anglia</li>
<li class="{% block navbar_class-ie %}{% endblock %}">Irlandia</li>
<li class="{% block navbar_class-es %}{% endblock %}">Hiszpania</li>
</ul>
<div class="col-sm-3 col-md-3">
<form class="navbar-form" role="search" name="input" action="{% url 'search' %}" method="get">
<div class="input-group">
<input type="text" class="form-control" name="feed_search_string" id="feed_search_string" value="{% if feed_search_string %}{{ feed_search_string }}{% else %}Szukaj{% endif %}">
<div class="input-group-btn">
<button class="btn btn-success" type="submit"><i class="glyphicon glyphicon-search"></i></button>
</div>
</div>
</form>
</div>
<ul class="nav navbar-nav navbar-right">
<li> <span class="glyphicon glyphicon-info-sign white"></span>About</li>
<!-- modal start here -->
<li> <span class="glyphicon glyphicon-envelope white"></span>Kontakt</li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
As I mentioned, modal is a popup with header and footer. In fireburg I am seeing csrf_token in modal-body but no form.
Pointing my browser to 127.0.0.1/contact/ form is presented.
Could some one help me with this?

Related

How can I remove a particular item using a popup?

I have many items and I want to delete one of them but when I delete one item it turns out that it deletes the last item which exists based on ordering so, if I have 10 records of id which start from 1 to 10 record so, it will remove the item number 10 til if I remove item number 5 will remove the number 10. this case occurs because of popup but if I remove popup and delete the items directly it will remove with no mistake so, How can I remove a particular item using popup?
profile.html
{% if request.user == profile.user %}
<div class="col-lg-7 offset-lg-1 col-12">
{% if profile.user.user_history.all.count != 0 %}
<form method="post">
{% csrf_token %}
<div class="clear_all fl-left">
<input class="global_checkbox" type="checkbox" name="remove_all_history" id="remove_all_history">
<label for="remove_all_history" class="ml">Remove All</label>
</div>
<div class="fl-right">
<input type="submit" value="Remove" class="clear_button btn btn-danger invisible"/>
</div>
</form>
{% else %}
<p class="text-center">you have no history yet!</p>
{% endif %}
<div class="clearfix"></div>
<div class="mt-6"></div>
{% for history in history_pages %}
{% if history.deleted_history == False %}
<div class="history">
<div class="row">
<div class="col-4">
<form method="post">
{% csrf_token %}
<input class="global_checkbox" type="checkbox" name="remove_one_history" id="remove_all_history">
<span class="ml-2">{{ history.history_time|time }}</span>
<div class="ml ml-4">{{ history.history_time|date:'d M Y' }}</div>
</form>
</div>
<div class="history-content col-7">
<p><strong>text:</strong> {{ history.history }}</p>
<p><strong>action:</strong> {{ history.action_option }}</p>
<p><strong>position:</strong>
{% if history.verb_option == "" %}
POS
{% else %}
{{ history.verb_option }}
{% endif %}
</p>
</div>
<form method="post" action="{% url 'accounts:remove_history' history.id %}">
{% csrf_token %}
<div class="history-list col-1">
<span class="fa fa-ellipsis-v" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></span>
<div class="dropdown-menu">
<a type="button" class="dropdown-item" data-toggle="modal" data-target="#exampleModal">Remove this item</a>
</div>
</div>
{% include 'accounts/popup.html' %}
</form>
</div>
</div>
{% endif %}
{% endfor %}
</div>
{% endif %}
popup.html
<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">Warning!!</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Do you want to remove this history item?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-outline-danger">Remove</button>
</div>
</div>
</div>
</div>
views.py
#login_required
def userProfile(request, slug=None):
profile = None
try:
profile = Profile.objects.get(user__slug=slug)
paginator = Paginator(profile.user.user_history.all(), 100)
page_number = request.GET.get('page_number')
history_pages = paginator.get_page(page_number)
except:
return redirect('accounts:index_404')
return render(request, 'accounts/profile.html', {'profile': profile, 'history_pages': history_pages})
def remove_history(request, id=None):
if id and id is not None:
# History.objects.get(id=id)
print(id)
return redirect("accounts:profile", request.user.username)
Note: I tested the delete using print(id)
In your current code you have included popup.html mutliple times so when you click on a tag its not confirm which modal will get open has all are triggering exampleModal i.e :data-target="#exampleModal" .
So , to overcome this one way would be including only one modal and adding form tags around submit button . Then , whenever user click on a tag you can get action value from form where a tag has been clicked and then add this action value inside modal form tag .
Demo Code :
//on click of `a` tag
$(".dropdown-item").on("click", function() {
//get closest form from `a` tag then get action from it
var action_ = $(this).closest("form").attr("action");
$("#exampleModal form").attr("action", action_) //add that action inside modal form tag
console.log(action_)
})
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<div class="history">
<div class="">
<div class="">
<form method="post">
{% csrf_token %}
<input class="global_checkbox" type="checkbox" name="remove_one_history" id="remove_all_history">
<span class="">12:30</span>
<div class="">12-04-21</div>
</form>
</div>
<div class="history-content">
<p><strong>text:</strong> Somethigs</p>
<p><strong>action:</strong>Ok</p>
<p><strong>position:</strong> POS
</p>
</div>
<form method="post" action="{% url 'accounts:remove_history' 1 %}">
<div class="history-list">
<span class="fa fa-ellipsis-v" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></span>
<div class="dropdown-menu">
<a type="button" class="dropdown-item" data-toggle="modal" data-target="#exampleModal">Remove this item</a>
</div>
</div>
<!--remove this line {% include 'accounts/popup.html' %}-->
</form>
</div>
</div>
<div class="history">
<div class="">
<div class="">
<form method="post">
{% csrf_token %}
<input class="global_checkbox" type="checkbox" name="remove_one_history" id="remove_all_history">
<span class="">12:32</span>
<div class="">22-04-21</div>
</form>
</div>
<div class="history-content">
<p><strong>text:</strong> Somethigs2</p>
<p><strong>action:</strong>Ok2</p>
<p><strong>position:</strong> POS
</p>
</div>
<form method="post" action="{% url 'accounts:remove_history' 2 %}">
<div class="history-list">
<span class="fa fa-ellipsis-v" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></span>
<div class="dropdown-menu">
<a type="button" class="dropdown-item" data-toggle="modal" data-target="#exampleModal">Remove this item</a>
</div>
</div>
<!--remove this line {% include 'accounts/popup.html' %}-->
</form>
</div>
</div>
<!--just use only one modal no need to include it every time on your page-->
<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">Warning!!</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<!--added form tag-->
<form method="post" action="">
<!--added csrf token-->
{% csrf_token %}
<div class="modal-body">
Do you want to remove this history item?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-outline-danger">Remove</button>
</div>
</form>
</div>
</div>
</div>

Django and Bootstrap Modal

Please help me to progress with my project. I'm new to Django and bootstrap and i'm currently working on a project. For the Registration of the user i'm using a popup modal.
I've set up the following:
Html file with modal
{% load static %}
<!-- Register Modal Starts -->
<div class="row mt25 tab-pane fade" id="profile" role="tabpanel" aria-labelledby="profile-tab">
<div class="col-lg-6 col-xl-6">
<div class="regstr_thumb">
<img class="img-fluid w100" src="{% static 'images/resource/regstr.jpg' %}" alt="regstr.jpg">
</div>
</div>
<div class="col-lg-6 col-xl-6">
<div class="sign_up_form">
<form action="{% url 'register' %}" method="POST" id="register-form">
{% csrf_token %}
<div class="heading">
<h4>Register</h4>
</div>
<div class="row">
<div class="col-lg-12">
<button type="submit" class="btn btn-block btn-fb"><i class="fa fa-facebook float-left mt5"></i> Login with Facebook</button>
</div>
<div class="col-lg-12">
<button type="submit" class="btn btn-block btn-googl"><i class="fa fa-google float-left mt5"></i> Login with Google</button>
</div>
</div>
<hr>
<div class="form-group ui_kit_select_search mb0">
<select class="selectpicker" data-live-search="true" data-width="100%">
<option data-tokens="SelectRole">Landlord</option>
<option data-tokens="Agent/Agency">Property Manager</option>
<option data-tokens="SingleUser">Homeowner</option>
</select>
</div>
<div class="form-group input-group">
<p>{{ form.errors.email}}</p>
{{form.email}}
<input type="email" class="form-control" id="exampleInputEmai" placeholder="Email">
<div class="input-group-prepend">
<div class="input-group-text"><i class="fa fa-envelope-o"></i></div>
</div>
</div>
<div class="form-group input-group">
<p>{{ form.errors.password1 }}</p>
{{ form.password1 }}
<input type="password" name="password1" class="form-control" id="exampleInputPassword2" placeholder="Password">
<div class="input-group-prepend">
<div class="input-group-text"><i class="flaticon-password"></i></div>
</div>
</div>
<div class="form-group input-group">
<p>{{ form.errors.password2 }}</p>
{{ form.password2 }}
<input type="password" name="password2" class="form-control" id="exampleInputPassword3" placeholder="Re-enter password">
<div class="input-group-prepend">
<div class="input-group-text"><i class="flaticon-password"></i></div>
</div>
</div>
<div class="form-group input-group">
<p>{{ form.errors.country }}</p>
{{ form.country }}
<input type="country" name="country" class="form-control" id="exampleInputCountry" placeholder="Country">
<div class="input-group-prepend">
<div class="input-group-text"><i class="flaticon-country"></i></div>
</div>
</div>
<div class="form-group input-group">
<p>{{ form.errors.city }}</p>
{{ form.city }}
<input type="city" name="city" class="form-control" id="exampleInputCity" placeholder="City">
<div class="input-group-prepend">
<div class="input-group-text"><i class="flaticon-city"></i></div>
</div>
</div>
<div class="form-group input-group">
<p>{{ form.errors.phone_number }}</p>
{{ form.phone_number }}
<input type="phone" name="phone_number" class="form-control" id="exampleInputPhone" placeholder="Phone Number">
<div class="input-group-prepend">
<div class="input-group-text"><i class="flaticon-phone"></i></div>
</div>
</div>
<div class="form-group custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" id="exampleCheck2">
<label class="custom-control-label" for="exampleCheck2">I have read and accept the Terms and Privacy Policy?</label>
</div>
<button type="submit" class="btn btn-log btn-block btn-thm">Sign Up</button>
<p class="text-center">Already have an account? <a class="text-thm" href="#">Log In</a></p>
</form>
</div>
</div>
</div>
The views.py file:
from django.shortcuts import render, redirect
from .forms import UserAdminCreationForm
from django.contrib import messages
def login(request):
return render(request, 'login.html')
def register(request):
form = UserAdminCreationForm()
if request.method == 'POST':
form = UserAdminCreationForm(request.POST)
if form.is_valid():
form.save()
user = form.cleaned_data.get('email')
messages.success(request, 'Account was created for ' + user)
return redirect('index')
return render(request, 'accounts/register.html', {'form': form})
The urls.py file
from django.urls import path, include
from . import views
urlpatterns = [
path('accounts/', include('django.contrib.auth.urls')),
path('register', views.register, name='register'),
path('logout', views.logout, name='logout'),
path('dashboard', views.dashboard, name='dashboard'),
]
The forms.py file:
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm
from django import forms
class UserAdminCreationForm(UserCreationForm):
"""A Custom form for creating new users."""
email = forms.EmailField(label="", widget=forms.EmailInput(attrs={'class': 'form-control', 'placeholder': 'Email Address'}), )
password1 = forms.CharField(label="", widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password'}))
password2 = forms.CharField(label="", widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Repeat Password'}))
country = forms.CharField(label="", max_length=50, widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Country'}))
city = forms.CharField(label="", max_length=50, widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'City'}))
phone_number = forms.CharField(label="", max_length=20, widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Phone Number'}))
class Meta:
model = get_user_model()
fields = ['user_types', 'email', 'password1', 'password2', 'country', 'city', 'phone_number']
When the popup modal with the registration form is opened and click SignUp i have setup a new page accounts/register page just for testing. But i do not want this page, i want to complete the form above and add user in the database. How can i configure that?
My problems that i cannot solve are:
how when i fill in the popup registration (inside the modal) and press SignUp to add user in the database without the accounts/register page?
Please help! Thank you for your time!
change input fields with form.{field name} and add {{ form.errors.{fieldname} }}
here your code:
<!-- Login/Register Starts -->
<!-- Modal -->
<div class="sign_up_modal modal fade" tabindex="-1" role="dialog" aria-hidden="true" id=bd-example-modal-lg>
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body container pb20">
<div class="row">
<div class="col-lg-12">
<ul class="sign_up_tab nav nav-tabs" id="myTab" role="tablist">
<li class="nav-item">
<a class="nav-link active" id="home-tab" data-toggle="tab" href="#home" role="tab" aria-controls="home" aria-selected="true">Login</a>
</li>
<li class="nav-item">
<a class="nav-link" id="profile-tab" data-toggle="tab" href="#profile" role="tab" aria-controls="profile" aria-selected="false">Register</a>
</li>
</ul>
</div>
</div>
<!-- Register Modal Starts -->
<div class="row mt25 tab-pane fade" id="profile" role="tabpanel" aria-labelledby="profile-tab">
<div class="col-lg-6 col-xl-6">
<div class="regstr_thumb">
<img class="img-fluid w100" src="{% static 'images/resource/regstr.jpg' %}" alt="regstr.jpg">
</div>
</div>
<div class="col-lg-6 col-xl-6">
<div class="sign_up_form">
<form action="{% url 'register' %}" method="POST" id="register-form">
{% csrf_token %}
{{form.as_p}}
<div class="heading">
<h4>Register</h4>
</div>
<div class="row">
<div class="col-lg-12">
<button type="submit" class="btn btn-block btn-fb"><i class="fa fa-facebook float-left mt5"></i> Login with Facebook</button>
</div>
<div class="col-lg-12">
<button type="submit" class="btn btn-block btn-googl"><i class="fa fa-google float-left mt5"></i> Login with Google</button>
</div>
</div>
<hr>
<div class="form-group ui_kit_select_search mb0">
<select class="selectpicker" data-live-search="true" data-width="100%">
<option data-tokens="SelectRole">Landlord</option>
<option data-tokens="Agent/Agency">Property Manager</option>
<option data-tokens="SingleUser">Homeowner</option>
</select>
</div>
<div class="form-group input-group">
<p>{{ form.errors.email}}</p>
{{ form.email }}
<div class="input-group-prepend">
<div class="input-group-text"><i class="fa fa-envelope-o"></i></div>
</div>
</div>
<div class="form-group input-group">
<p>{{ form.errors.password1 }}</p>
{{ form.password1 }}
<div class="input-group-prepend">
<div class="input-group-text"><i class="flaticon-password"></i></div>
</div>
</div>
<div class="form-group input-group">
{{ form.password2 }}
<div class="input-group-prepend">
<div class="input-group-text"><i class="flaticon-password"></i></div>
</div>
</div>
<div class="form-group input-group">
<p>{{ form.errors.country }}</p>
{{ form.country }}
<div class="input-group-prepend">
<div class="input-group-text"><i class="flaticon-country"></i></div>
</div>
</div>
<div class="form-group input-group">
<p>{{ form.errors.city }}</p>
{{ form.city }}
<div class="input-group-prepend">
<div class="input-group-text"><i class="flaticon-city"></i></div>
</div>
</div>
<div class="form-group input-group">
<p>{{ form.phone_number }}</p>
{{ form.phone_number }}
<div class="input-group-prepend">
<div class="input-group-text"><i class="flaticon-phone"></i></div>
</div>
</div>
<div class="form-group custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" id="exampleCheck2">
<label class="custom-control-label" for="exampleCheck2">I have read and accept the Terms and Privacy Policy?</label>
</div>
<button type="submit" class="btn btn-log btn-block btn-thm">Sign Up</button>
<p class="text-center">Already have an account? <a class="text-thm" href="#">Log In</a></p>
</form>
</div>
</div>
</div>

how to run a function from a link within popup modal bootstrap

I have a django project that includes a popup modal. The modal has tabs as links. When the user clicks on one of the tabs, it must perform a function and retrieve data from the database.
The problem is that once the user clicked on the tab nothing happened, and the function isn't initialized.
urls.py
path("events/<int:id>/", getEvents, name = "getEvents"),
views.py
def getEvents(request,id):
q1 = cursor.execute('SELECT Person_.ID FROM Person_ WHERE Person_.ID = {0}'.format(id))
print('q1==>',q1)
qresult = q1.fetchone()
print("qresult==>",qresult)
print("query is not empty!")
eventQ = cursor.execute('SELECT Person_.ID, Person_.Full_Name, Events.ID, Events.Event_Title, Events.Event_Details, Links.document_id from Person_, Events, Links where ( Person_.ID = {0}) and (Person_.ID = Links.A_Person or Person_.ID = Links.B_Person) and (Events.ID = Links.A_Event or Events.ID = Links.B_Event) ORDER BY Events.ID DESC '.format(id))
resultEvents = eventQ.fetchall()
return render(request,'pictureCard.html',{
"resultEvents":resultEvents,
"qresult":qresult,
})
pictureCrads.html
<!-- Popup Modal -->
{% for obj in object_list %}
<div id="popModel{{obj.0}}" class="modal fade modal-rtl" role="dialog">
<div class="modal-dialog modal-lg">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header Modal-Pic">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">{{ obj.1 }}</h4>
<img src="{% static '/img/card/1.png'%}"/>
</div>
<ul class="nav nav-tabs" id="myTab" role="tablist">
<li class="nav-item">
<a class="nav-link" id="contact-tab" data-toggle="tab" href="#contact{{ obj.0 }}" role="tab" aria-controls="contact" aria-selected="false">contact us</a>
</li>
<li class="nav-item">
<a class="nav-link" id="event-tab" data-toggle="tab" href="{% url 'getEvents' obj.0 %}" role="tab" aria-controls="event" aria-selected="false">Events</a>
</li>
<li class="nav-item mr-auto btn-warning">
<a class="nav-link text-dark" id="contact-tab" data-toggle="tab" href="#picture" role="tab" aria-controls="contact" aria-selected="false">Picture</a>
</li>
</ul>
<div class="modal-body tab-content" id="myTabContent">
<div class="tab-pane fade" id="contact{{ obj.0 }}" role="tabpanel" aria-labelledby="contact-tab">{{ obj.9 }}</div>
{% for event in resultEvents %}
<div class="tab-pane fade" id="event{{ obj.0 }}" role="tabpanel" aria-labelledby="event-tab">
<button class="btn btn-primary" > events</button>
{{ event.2 }}
</div>
{% endfor %}
<div class="tab-pane fade" id="picture" role="tabpanel" aria-labelledby="contact-tab">
<a class="" href="#"><img class="" src="{% static '/img/card/1.png'%}"/></a>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
......
<footer class="card-footer card-footer-buttom text-center bg-info">
<form method="GET" action="{% url 'getEvents' obj.0 %}">
detais
</form>
</footer>
Probably django does not know {% for obj in object_list %}. Because you are sending 2 variables which are resultEvents and qresult, but your html file is looking for 'object_list' dictionary or list. This might be the problem.
Hope this helps,

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

Delete data form after sending post request

I'm coding user management page. In page, I have form to add new user with post request and delete button with comfirmation form. I add new user successfully, page is reloaded, then I delete any account, but data in form I sent request to create new user is sent again with new user ID. How to fix?
user_management.html
{% extends 'pages/base.html' %}
{% block title %} Quản lý người dùng{% endblock %}
{% block active %}
{% endblock %}
{% block link %}
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css"
integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"
integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
crossorigin="anonymous"></script>
{% endblock %}
{% load static %}
{% block css %}
<link rel="stylesheet" type="text/css" href="{% static 'css/user_management.css' %}">
<style>
#messages {
width: 200px;
height: 50px;
text-align: center;
}
</style>
{% endblock %}
{% block content %}
<div class="container">
<div class="table-wrapper">
<div class="table-title">
<div class="row">
<div class="col-sm-5">
<h2>Quản lý người dùng</h2>
</div>
<div class="col-sm-7">
<button type="button" class="btn btn-primary" data-toggle="modal"
data-target="#modalRegisterForm">
<i class="material-icons"></i>
<span>Thêm mới</span></button>
</div>
</div>
</div>
{% ifequal msg null %}
{% else %}
<div id="messages" class="alert alert-success" role="alert">
<span class="">{{ msg }}</span>
</div>
{% endifequal %}
<p id="delete-notifa"></p>
<table class="table table-striped table-hover">
<thead>
<tr>
<th>User ID</th>
<th>Name</th>
<th>Date Created</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{% for user in users %}
<tr>
<td>{{ user.id }}</td>
<td> {{ user.first_name }} {{ user.last_name }}</td>
<td>{{ user.date_joined }}</td>
<td>
<a href="{% url 'profile' user.id %}" class="edit" title="Edit" data-toggle="tooltip"><i
class="material-icons"></i></a>
<a href="#comfirmationForm" class="delete" title="Delete" data-toggle="modal"
data-id="{{ user.id }}"><i
class="material-icons"></i></a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<div class="clearfix">
<div class="hint-text">Showing <b>5</b> out of <b>25</b> entries</div>
<ul class="pagination">
<li class="page-item disabled">Previous</li>
<li class="page-item">1</li>
<li class="page-item">2</li>
<li class="page-item active">3</li>
<li class="page-item">4</li>
<li class="page-item">5</li>
<li class="page-item">Next</li>
</ul>
</div>
</div>
</div>
<div class="modal fade mt-5" id="modalRegisterForm" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header text-xs-center">
<h5 class="modal-title font-weight-bold" id="myModalLabel">Thêm người dùng</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body mx-3">
<form action="{% url 'user_management' %}" method="post" id="addNewUser">
{% csrf_token %}
<div class="form-group">
<div class="row">
<div class="col-xs-6">
<input type="text" class="form-control" name="first_name" id="first_name"
placeholder="First Name">
</div>
<div class="col-xs-6">
<input type="text" class="form-control" name="last_name" id="last_name"
placeholder="Last Name">
</div>
</div>
</div>
<div class="form-group">
<input type="email" class="form-control" name="email" placeholder="Email" id="email"
required="required">
</div>
<div class="form-group">
<input type="password" class="form-control" name="password" placeholder="Password"
id="id_password"
required="required">
</div>
<div class="form-group">
<input type="password" class="form-control" name="confirm_password" id="id_comfirm_pass"
placeholder="Confirm Password" required="required"
onkeyup="matchingPassword('id_password', 'id_comfirm_pass', 'msg');">
</div>
<p id="msg"></p>
<div class="form-group">
<button type="submit" class="btn btn-success btn-lg btn-block" name="add">Thêm</button>
</div>
</form>
</div>
</div>
</div>
</div>
<div id="comfirmationForm" class="modal fade">
<div class="modal-dialog modal-confirm">
<div class="modal-content">
<div class="modal-header">
<div class="icon-box">
<i class="material-icons"></i>
</div>
<h4 class="modal-title">Xác nhận</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<p>Do you really want to delete this user?</p>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-danger" id="btn_button">Delete</button>
<button type="button" class="btn btn-info" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
{% endblock %}
{% block script %}
<script>
function matchingPassword(id_pass, id_comfirm_pass, id_msg) {
var pass = document.getElementById(id_pass).value;
var comfirm_pass = document.getElementById(id_comfirm_pass).value;
if (pass != comfirm_pass) {
document.getElementById(id_msg).style.color = 'red';
document.getElementById(id_msg).innerHTML = "Mật khẩu không trùng nhau";
} else {
document.getElementById(id_msg).innerHTML = "";
}
}
</script>
<script>
var tmp;
$('.delete').click(function () {
tmp = $(this).attr('data-id');
});
$('#btn_button').click(function () {
$.ajax({
url: '/delete_user',
type: 'get',
dataType: 'json',
data: {
user_id: tmp,
},
success: function (data) {
if (data.is_error) {
alert("Xóa không thành công");
window.location.reload();
} else {
alert("Xóa thành công");
location.reload();
}
}
})
})
setTimeout(function () {
$('#messages').hide()
}, 1000);
setTimeout(function () {
$('#delete-notifa').hide()
}, 1000);
</script>
{% endblock %}
views.py
def user_management(request):
if request.method == "POST":
if 'add' in request.POST:
first_name = request.POST.get('first_name')
last_name = request.POST.get('last_name')
username = request.POST.get('email')
password = request.POST.get('password')
user = User.objects.create_user(username=username, email=username, password=password, first_name=first_name,
last_name=last_name)
user.save()
user_info = UserInfor(user=user)
user_info.save()
user_list = User.objects.all()
msg = "Thêm thành công"
return render(request, 'pages/user_management.html', {'users': user_list, 'msg': msg})
else:
user_list = User.objects.all()
msg = "Thất bại"
return render(request, 'pages/user_management.html', {'users': user_list, 'msg': msg})
else:
user_list = User.objects.all()
return render(request, 'pages/user_management.html', {'users': user_list})
def delete_user(request):
data = {}
user_id = request.GET.get('user_id')
user = User.objects.get(id=user_id)
user_info = UserInfor.objects.get(user_id=user.id)
user.delete()
user_info.delete()
data['is_error'] = User.objects.filter(id=user_id).exists()
return JsonResponse(data)
I believe your problem is that you're using
type="submit" id="btn_button" and $('#btn_button').click(... together
I believe your modal-footer is triggering your form tag that's why when you click Delete button your page get's reloaded.
and at the same time $('#btn_button').click(function () {... is doing it's job by sending GET request to the server.
So as soon as you hit delete button, POST request to create user via form submission is sent and GET request to delete user is also sent.
Try changing this:
<button type="button" class="btn btn-danger" id="btn_button">Delete</button>
to
<button type="submit" class="btn btn-danger" id="btn_button">Delete</button>
Happy coding :)