I'm trying to write a code for deleting an item. But before deleting it i want to popup a message to the user like "are you sure you want to delete?".
I want to delete the item by its ID.
I wrote this code, but i pretty sure its not how it should be.
Please guide me what to do.
HTML FILE
<div id="film_box">
{% if films %}
{% for film in films %}
<div class="card" style="width: 18rem;">
{% if film.image%}
<img src="{{ film.image.url }}" class="card-img-top" alt="...">
{% endif %}
<div class="card-body">
<h5 class="card-title">{{ film.title}}</h5>
<p class="card-text">{{ film.category_name }}</p>
<p class="card-text">{{ film.country_name }}</p>
<p class="card-text">{{ film.director }}</p>
<p class="card-text">{{ film.release_date }}</p>
</div>
<div class="card-body">
{% if request.user.is_superuser %}
<ul style="list-style:none;">
<li>Modify the director
</li>
<li>Modify the film</li>
<li><button onclick="document.getElementById('btn_delete').style.display='block'"
name="{{ film.id }}" class="btn btn-danger">DELETE</button></li>
</ul>
{% endif %}
<!--popup message-->
<div id="btn_delete" class="modal">
<span onclick="document.getElementById('btn_delete').style.display='none'" class="close" title="Close
Modal">×</span>
<form class="modal-content" action="/delete/{{film.id}}">
<div class="container">
<h1>Delete film</h1>
<p>Are you sure you want to delete the film?</p>
<div class="clearfix">
<button type="button" onclick="document.getElementById('btn_delete').style.display='none'" class="cancelbtn">Cancel</button>
<button href="{% url 'delete_film' film.id %}" onclick="document.getElementById('btn_delete').style.display='none'" class="deletebtn">Delete</button>
</div>
</div>
</form>
</div>
{% endfor%}
{% endif %}
JAVASCRIPT FILE
// Get the modal
var modal = document.getElementById('btn_delete');
console.log(model.name)
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
I want to pass the ID in the url, so i can catch it on the python file and manipulate it.
Should i use Javascript?
This is how I would do it. Please note the code is not tested, however the principles should give you a glimpse of understanding of how to proper do it.
from django.http import JsonResponse
from django.views import generic
# urls.py
urlpatterns = [
re_path(r'^delete/(?P<pk>.+)/$', views.DeleteFilmView.as_view(), name='delete'),
]
# models.py
class Film(models.Model):
# ...
def get_delete_url(self):
return reverse('film:delete', args=(self.pk,))
# views.py
class DeleteFilmView(generic.DeleteView):
template_name = 'delete_confirmation.html'
model = Film
context_object_name = 'film'
def delete(self, *args, **kwargs):
self.object = self.get_object()
success_url = self.get_success_url()
self.object.delete()
return JsonResponse({'messages': 'Deleted'})
<!--html file-->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Delete Film</h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div id="film_box">
{% if films %}
{% for film in films %}
<div class="card" style="width: 18rem;">
{% if film.image%}
<img src="{{ film.image.url }}" class="card-img-top" alt="...">
{% endif %}
<div class="card-body">
<h5 class="card-title">{{ film.title}}</h5>
<p class="card-text">{{ film.category_name }}</p>
<p class="card-text">{{ film.country_name }}</p>
<p class="card-text">{{ film.director }}</p>
<p class="card-text">{{ film.release_date }}</p>
</div>
<div class="card-body">
{% if request.user.is_superuser %}
<ul style="list-style:none;">
<li>Modify the director
</li>
<li>Modify the film</li>
<li>Delete</li>
</ul>
{% endif %}
</div>
</div>
</div>
<script type="text/javascript">
(function () {
$('.deletePopup').on('click',function(){
$('.modal-body').load('content.html',function(){
$('#myModal').modal({show:true});
});
});
$('body').on('click', '.delete-film', function(e) {
// make sure you listen on the body and not on the element, because the element doesnt exist when
// DOM is created.
e.preventDefault():
$.ajax({
url: $(this).attr('href');,
type: 'DELETE',
dataType: 'json',
success: function(result) {
// show success message, ie: using toastr
// remove the film from DOM
// close the modal
}
})
})
})();
</script>
<!--delete_confirmation.html-->
<p>Are you sure you want to delete {{ film.title}}?</p>
<a class="delete-film" href="{{ film.get_delete_url }}">Delete</a>
Cancel
Related
I am building a website where users can buy courses and the courses will display on their users library, a site similar to gumroad, but i am getting this error when i clicked on the payment option on my code.
Here is the error messages i am getting
MultipleObjectsReturned at /course/eyime/user_library/
get() returned more than one UserLibrary -- it returned 2!
here is the Views.py codes
#login_required
def user_library(request, username):
user = get_object_or_404(User, username=username)
my_library = UserLibrary.objects.filter(user=user)
if request.method == 'POST':
course_id = request.POST['course_id']
course_price = request.POST['course_price']
course = UserLibrary.objects.get(courses__id=course_id)
"""for c in course.courses.all():
print(c.name)"""
context = {
'course': course,
'course_price': course_price,
'email': request.user.email,
'phone': request.user.phone_number,
}
return render(request, 'courses/content/pay_for_courses.html', context)
return render(request, 'courses/content/user_library.html', {'my_library': my_library})
here is the html codes for payment of the courses
{% extends "jtalks/base.html" %}
{% load static %}
{% block title %}Payment With Paystack{% endblock %}
{% block content %}
<div class='container' onload="payWithPaystack()">
<div class='row justify-content-md-center'>
<div class='col-md-auto'>
<div id="output">
</div>
<div id="success">
</div>
<div id="display_info" style="display: none">
<p>Click Here to print receipt of your purchase</p>
<p id="home">Go Back Home Homepage</p>
</div>
</div>
</div>
</div>
{% endblock content %}
{% block js %}
<script src="https://js.paystack.co/v1/inline.js"></script>
<script>
window.onload=function(){
payWithPaystack();
};
function payWithPaystack(){
var price = '{{ course_price }}';
var handler = PaystackPop.setup({
key: 'pk_test_ce8979497f703eb955ab5ceb19fc54cdcb615e0d',
email:'{{email}}',
amount: parseInt(price) * 100,
currency: "NGN",
metadata: {
custom_fields: [
{
display_name: "Mobile Number",
variable_name: "mobile_number",
value: "{{phone}}",
course_id: "{{ course.id }}"
}
]
},
callback: function(response){
var ref = response.reference;
var course_random_id = '{{ course.order_id }}'
var course_id = '{{ course.id }}'
//console.log(order_id)
// $('div#home').show();
$.ajax({
method: "GET",
url: "/course/pay_for_courses/",
data: {
'id': course_id,
'reference': ref,
},
dataType: "json",
success: function (data) {
if (data.message == "Your Payment was successfully received") {
$('#output').html(data.message)
$('#success').html(`<p>Transaction reference is : <h2>${ref}</h2> and your order id is <h2>${course_random_id}</h2></p>`);
$("#display_info").show();
} else if (data.message == "Your Payment Failed!!!") {
$('#output').html(data.message)
$("#success").html(`Back To Your Library`)
}
},
});
},
onClose: function(){
alert('window closed');
}
});
handler.openIframe();
}
</script>
{% endblock js %}
and here is the html codes for users library
{% extends 'jtalks/base.html' %}
{%load static%}
{% block content %}
<div>
<center>Welcome to your library, {{ request.user.username }}</center>
</div>
<div class="container-fluid">
<div class="row">
<div class="col-6">
<h1>Wish List</h1>
<h3>Courses you are yet to pay for will show up here</h3>
<div class="user_library" style="display: flex; flex-direction: row; flex-wrap: wrap;">
{% for library in my_library %}
{% if not library.paid %}
{% for course in library.courses.all %}
<div class="card" style="width: 18rem;">
<img src="{{ course.content_file.url }}" class="card-img-top" alt="{{ course.name }}">
<div class="card-body">
<h5 class="card-title">{{ course.name }}</h5>
<p class="card-text">{{ course.overview|slice:":50" }}...</p>
</div>
<ul class="list-group list-group-flush">
<li class="list-group-item">An item</li>
<li class="list-group-item">A second item</li>
<li class="list-group-item">A third item</li>
</ul>
<div class="card-body">
Course Details
<form method="post">
{% csrf_token %}
<input type="hidden" name="course_id" value="{{ course.id }}">
<input type="hidden" name="course_price" value="{{ course.price }}">
<input type="submit" class="btn btn-primary" value="Pay ₦{{ course.price}}">
</form>
</div>
</div>
{% endfor %}
{% endif %}
{% endfor %}
</div>
</div>
<div class="col-6">
<h1>Paid Courses</h1>
<h3>All courses you have successfully paid for will show here</h3>
<div class="user_library" style="display: flex; flex-direction: row; flex-wrap: wrap;">
{% for library in my_library %}
{% if library.paid %}
{% for course in library.courses.all %}
<div class="card" style="width: 18rem;">
<img src="{{ course.content_file.url }}" class="card-img-top" alt="{{ course.name }}">
<div class="card-body">
<h5 class="card-title">{{ course.name }}</h5>
<p class="card-text">{{ course.overview|slice:":50" }}...</p>
</div>
<ul class="list-group list-group-flush">
<li class="list-group-item">An item</li>
<li class="list-group-item">A second item</li>
<li class="list-group-item">A third item</li>
</ul>
<div class="card-body">
Course Details
<a id="download_pdf" href="/media/pdf_courses/{{ course.slug }}.pdf" class="btn btn-primary" download>Download PDF</a>
</div>
<div>
<video width="300" height="240" controls controlsList="nodownload">
<source src="{{ MEDIA_URL}}{{ course.course_video }}" type="video/mp4">
Your browser does not support the video tag.
</video>
</div>
</div>
{% endfor %}
{% endif %}
{% endfor %}
</div>
</div>
</div>
</div>
{% endblock %}
{% block js %}
<script src="{% static 'jtalks/home.js' %}"></script>
{% endblock js %}
It seems that this line is returning 2 records instead of one:
course = UserLibrary.objects.get(courses__id=course_id)
Use filter instead of get and iterate through the course variable in a template tag such as:
{% for c in course %}
and access c's fields instead.
I'm trying to create a social media news feed, with the posts, but I dont want to show the comments just if the user presses the button Show Comments. The problem is that when I press the button of one post, all the post will extend comments. I don't really know how to solve this...
{% for post in posts %}
<div class="container">
<div class="row">
<div class="[ col-xs-12 col-sm-offset-1 col-sm-5 ]">
<div class="[ panel panel-default ] panel-google-plus">
<div class="panel-heading">
<img class="[ img-circle pull-left ]" width="50" height="50" src="{{post.author.profile.image.url}}" alt="Mouse0270" />
<h3 class="author">{{post.author}}</h3>
<h5><span>Shared publicly</span> - <span> {{post.date_posted}} </span> </h5><br>
</div>
<div class="panel-body">
{% if user == post.author %}
<a class="text-right" href="{% url 'post-update' post.id %}"><p>Update</a>
<a class="text-danger text-right" href="{% url 'post-delete' post.id %}">Delete post</a>
{% endif %}
<p>{{post.content}}</p>
{% if post.image %}
<img src ="{{post.image.url}}" width="300" height="300" border="0" class="img-thumbnail">
{% endif %}
{% if post.video %}
<video width="250" controls >
<source src="{{post.video.url}}" type="video/mp4" >
</video>
{% endif %}
</div>
<br/>
<div class="container" >
<button class="btn btn-primary">Add comment</button>
</div>
<br>
<button type="button" class="btn btn-danger btn-block" data-toggle="collapse" data-target="#demo">See comments</button>
<div id="demo" class="collapse">
{% for comment in post.comments.all %}
<div class="container">
<div class="row">
<div class="col-sm-5">
<div class="panel panel-default">
<div class="panel-heading">
<strong>{{comment.author}}</strong> <span class="text-muted">commented at {{comment.created_on|date:"d M g:i a"}}</span>
</div>
<div class="panel-body">
<img class=" img-circle" width="30" height="30" src="{{comment.author.profile.image.url}}">
{{comment.body}}
</div><!-- /panel-body -->
</div><!-- /panel panel-default -->
</div><!-- /col-sm-5 -->
</div>
</div>
{% endfor %}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
The problem is with the collapsable button above {% for comment in post.comments.all %}, but I dont know how to make it unique for every post.
I'm learning programming and following a tutorial using django 3, the same I'm using.
The text and images are not displaying on the frontend on one particular html file.
1.-In settings.py I have this:
MEDIA_ROOT= os.path.join(BASE_DIR,"media")
MEDIA_URL= "/media/"
2.-In models.py:
class Property(models.Model):
title = models.CharField(max_length=200)
main_photo = models.ImageField(upload_to='photos/%Y/%m/%d/')
3.-In admin.py:
from django.contrib import admin
from .models import Property
class PropertyAdmin(admin.ModelAdmin):
list_display = ('id', 'title', 'is_published')
list_display_links = ('id', 'title')
search_fields = ('title', 'town')
list_editable = ('is_published',)
list_per_page = 30
admin.site.register(Property, PropertyAdmin)
Then I migrated to the DB, I created a properties.html and the loop {{ property.main_photo.url }} or {{ property.title }} is working and getting images and texts on this properties file:
{% extends 'base.html' %}
{% load humanize %}
{% block content %}
<section id="showcase-inner" class="py-5 text-white">
<div class="container">
<div class="row text-center">
<div class="col-md-12">
<h1 class="display-4">Browse Our Properties</h1>
<p class="lead">Lorem ipsum dolor sit, amet consectetur adipisicing elit. Sunt, pariatur!</p>
</div>
</div>
</div>
</section>
<!-- Listings -->
<section id="listings" class="py-4">
<div class="container">
<div class="row">
{% if properties %}
{% for property in properties %}
<div class="col-md-6 col-lg-4 mb-4">
<div class="card listing-preview">
<img class="card-img-top" src="{{ property.main_photo.url }}" alt="">
<div class="card-img-overlay">
<h2>
<span class="badge badge-secondary text-white">From {{ property.price_per_week | intcomma }}€ per week</span>
</h2>
</div>
<div class="card-body">
<div class="listing-heading text-center">
<h4 class="text-primary">{{ property.title }}</h4>
<p>
<i class="fas fa-map-marker text-secondary"></i> {{ property.town }}</p>
</div>
<hr>
<div class="row py-2 text-secondary">
<div class="col-6">
<i class="fas fa-check"></i> {{ property.swimming_pool }}</div>
<div class="col-6">
<i class="fas fa-wifi"></i> {{ property.free_wifi }}</div>
</div>
<div class="row py-2 text-secondary">
<div class="col-6">
<i class="fas fa-bed"></i> Bedrooms: {{ property.bedrooms }}</div>
<div class="col-6">
<i class="fas fa-bath"></i> Bathrooms: {{ property.bathrooms }}</div>
</div>
More Info
</div>
</div>
</div>
{% endfor %}
{% else %}
<div class="col-md-12">
<p>No Properties available</p>
</div>
{% endif %}
</div>
<div class="row">
<div class="col-md-12">
{% if properties.has_other_pages %}
<ul class="pagination">
{% if properties.has_previous %}
<li class="page-item">
<a href="?page={{properties.previous_page_number}}" class="page-link">«
</a>
</li>
{% else %}
<li class="page-item-disabled">
<a class="page-link">«</a>
</li>
{% endif %}
{% for i in properties.paginator.page_range %}
{% if properties.number == i %}
<li class="page-item active">
<a class="page-link">{{i}}</a>
</li>
{% else %}
<li class="page-item">
{{i}}
</li>
{% endif %}
{% endfor %}
</ul>
{% endif %}
</div>
</div>
</div>
</section>
{% endblock %}
The next step is to create a property.html file and also use loop, but everything that uses the loop doble curly braces are not displaying:
{% extends 'base.html' %}
{% load humanize %}
{% block content %}
<section id="showcase-inner" class="py-5 text-white">
<div class="container">
<div class="row text-center">
<div class="col-md-12">
<h1 class="display-4">{{ property.title }}</h1>
<p class="lead">
<i class="fas fa-map-marker"></i> {{ property.town }}</p>
</div>
</div>
</div>
</section>
{% endblock %}
I checked multiple times and my code is exactly like on the tutorial but my frontend is not displaying.
Views.py:
from django.shortcuts import get_object_or_404, render
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from .models import Property
def index(request):
properties = Property.objects.get_queryset().order_by('id').filter(is_published=True)
paginator = Paginator(properties, 30)
page = request.GET.get('page')
paged_properties = paginator.get_page(page)
context = {
'properties': paged_properties
}
return render(request, 'properties/properties.html', context)
def property(request, property_id):
property = get_object_or_404(Property, pk=property_id)
context = {
'property': property
}
return render(request, 'properties/property.html')
def search(request):
return render(request, 'properties/search.html')
You are not passing the context to properties/property.html inside def property(..., ...)
Change:
return render(request, 'properties/property.html')
To:
return render(request, 'properties/property.html', context)
I'm trying to activate add to the favorite button with ajax, also the same button should remove from favorite if it is already there, here is my full files:
models.py
class Favorite(models.Model):
item = models.ForeignKey(Item, on_delete='CASCADE')
user = models.ForeignKey(UserModel, on_delete='CASCADE')
class Meta:
unique_together = (('item', 'user'), )
urls.py
path('<int:pk>/favorite_item/', views.favorite_item, name='favorite_item'),
views.py
#login_required
def favorite_item (request, pk):
favitem = get_object_or_404(Item, pk=pk)
data = {
'is_fav': Favorite.objects.get(user=request.user, item=favitem).exists(),
}
if data ['is_fav']:
Favorite.objects.get(user=request.user, item=favitem).delete()
else:
new_entry = Favorite.objects.create(item=favitem, user=request.user)
return JsonResponse(data)
home.html
{% extends 'fostania_web_app/base.html' %}
{% block javascript %}
<script>
$("#add_to_fav").click(function () {
console.log( $(this).val() );
});
$.ajax({
url: form.attr("data-favorite_item-url"),
data: form.serialize(),
dataType: 'json',
success: function (data) {
if (data.is_fav) {
alert('تم');
}
}
});
});
</script>
</script>
{% endblock %}
{% block content %}
{% load static %}
{% include 'fostania_web_app/slide.html' %}
<!-- Page Content -->
<div class="container">
<h1 class="my-4" align="right" dir="rtl">إستثمرى فساتينك القديمة مع Fostania</h1>
<!-- Marketing Icons Section -->
<div class="row">
<div class="col-lg-4 mb-4">
<div class="card h-100">
<h4 class="card-header" align="right">إنشاء حساب جديد</h4>
<div class="card-body">
<p class="card-text" align="center"><img src="{% static 'img/add_user_big.png' %}"><Br>
قم بإنشاء حساب جديد على فوستانيا حتى تستطيع عرض الفستان على الموقع</p>
</div>
<div class="card-footer" align="right">
تسجيل حساب جديد
</div>
</div>
</div>
<div class="col-lg-4 mb-4">
<div class="card h-100">
<h4 class="card-header" align="right">عرض الفستان على الموقع</h4>
<div class="card-body">
<p class="card-text" align="center"><img src="{% static 'img/plus_big.png' %}"><Br>
قم بإضافة الفستان مجاناً على الموقع حتى يصل الى مئات المشتريين و المهتمين
</p>
</div>
<div class="card-footer" align="right">
عرض الفستان على الموقع
</div>
</div>
</div>
<div class="col-lg-4 mb-4">
<div class="card h-100">
<h4 class="card-header" align="right">إبحثى عن الفستان المطلوب</h4>
<div class="card-body">
<p class="card-text" align="center"><img src="{% static 'img/search_big.png' %}"><Br>
او يمكن البحث عن الفستان المراد شرائه او تأجيره من وسط مئات الفساتين المعروضة</p>
</div>
<div class="card-footer" align="right">
إبدأ البحث
</div>
</div>
</div>
</div>
<!-- /.row -->
<!-- adsense -->
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Fostania-main -->
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-4202417439740489"
data-ad-slot="1170851377"
data-ad-format="auto"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<!-- end -->
<!-- Portfolio Section -->
<h2 align="right"> اخر الفساتين المضافة للموقع</h2>
<div class="row">
{% for dress in dresss %}
<div class="col-lg-4 col-sm-6 portfolio-item">
<div class="card h-100" >
<img class="card-img-top" src="{{ dress.dress_image1.url }}" style='width: 200px;height: 200px;' alt="">
<div class="card-body">
<h4 class="card-title" align="center">
{% if user.is_authenticated %}
{% if user_favs %}
{% for item in user_favs %}
{% if item.item == dress %}
<a href="{% url 'favorite_item' dress.id %}" id="add_to_fav">
<img src="{% static 'img/star-yes.png' %}" title="مسح من الفساتين المفضلة"></a>
{% else %}
<a href="{% url 'favorite_item' dress.id %}" id="add_to_fav">
<img src="{% static 'img/star_no.png' %}" title="إضافة إلى الفساتين المفضلة"></a>
{% endif %}
{% endfor %}
{% else %}
<a href="{% url 'favorite_item' dress.id %}" id="add_to_fav">
<img src="{% static 'img/star_no.png' %}" title="إضافة إلى الفساتين المفضلة"></a>
{% endif %}
{% endif %}
{{ dress.dress_name }}
<Br>
<h3><span class="badge badge-warning">{{ dress.dress_price }} EGP</span></h3>
</h4>
<p class="card-text" align="right">
معروض {{ dress.dress_action }} <br>
فى محافظة {{ dress.dress_town }}
</p>
</div>
</div>
</div>
{% endfor %}
</div>
<!-- paginator part -->
<div align="right">
{% if dresss.has_previous %}
<button class="btn btn-success">« الأولى </button>
<button class="btn btn-success">السابقة</button>
{% endif %}
</div>
<div align="center">
<span class="current" >
صفحة رقم {{ dresss.number }} من إجمالى {{ dresss.paginator.num_pages }}
</span>
</div>
<div align="left">
{% if dresss.has_next %}
<button class="btn btn-success">التالية</button>
<button class="btn btn-success">الاخيرة »</button>
{% endif %}
</div>
<!-- paginator part ends -->
<hr>
<!-- Call to Action Section -->
<!-- /.container -->
{% endblock %}
And finally it gives me an error
DoesNotExist at /3/favorite_item/
Favorite matching query does not exist.
I made it as normal request which reloads when the user clicks it and it is working perfectly, but i need to Use Ajax to prevent the page from reloading.
If a Favorite doesn't exist for an Item, this will raise because you're using get(). get() raises if an object is not found: https://docs.djangoproject.com/en/2.0/ref/models/querysets/#django.db.models.query.QuerySet.get
What I think you want is a combination of filter() and exists() like this:
data = {
'is_fav': Favorite.objects.filter(user=request.user, item=favitem).exists(),
}
i think that you need to use POST method for you ajax call
<script>
$("#add_to_fav").click(function () {
console.log( $(this).val() );
});
$.ajax({
url: form.attr("data-favorite_item-url"),
data: form.serialize(),
dataType: 'json',
method: 'POST', # <- here
...
});
});
</script>
I'm building a website using Django.
And for somereason, the dictionary using all the forms is not showing at all..
When I click my Edit button the modal is showing without the forms...
forms.server_id needs to contain all the forms using server_id...
the server_id I use to show the previous data when I edit.
But for some reason, it doesn't show any form at all...
index.html -
{% load static i18n util_filters %}
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs4/jq-3.2.1/jq-3.2.1/dt-1.10.16/af-2.2.2/b-1.4.2/fc-3.2.3/fh-3.1.3/kt-2.3.2/r-2.2.0/rg-1.0.2/rr-1.2.3/sc-1.4.3/sl-1.2.3/datatables.min.css"/>
<script src="https://use.fontawesome.com/3c2c6890cf.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/v/bs4/jq-3.2.1/jq-3.2.1/dt-1.10.16/af-2.2.2/b-1.4.2/fc-3.2.3/fh-3.1.3/kt-2.3.2/r-2.2.0/rg-1.0.2/rr-1.2.3/sc-1.4.3/sl-1.2.3/datatables.min.js"></script>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="{% url 'serverlist' %}">DevOps Map</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="{% url 'serverlist' %}">Servers</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'serverlist' %}">Switches</a>
</li>
</ul>
</div>
</nav>
<style type="text/css">
.wrapper {
display:flex;
}
</style>
</head>
<body>
<div class="container">
<br>
<center><h1 class="display-4">DevOps Server List</h1></center>
<br>
<center><button type="button" class="save btn btn-outline-success btn-lg" data-toggle="modal" data-target=".AddServer">Add Server <i class="fa fa-server fa-lg" aria-hidden="true"></i></button></center>
<table class="table table-hover table-bordered table-condensed" cellspacing="0" width="1300" id="ServerTable">
<thead>
<tr>
<th><center> #</center></th>
<th><center> Server Name </center></th></center>
<th><center> Owner </center></th></center>
<th><center> Project </center></th></center>
<th><center> Description </center></th></center>
<th><center> IP Address </center></th></center>
<th><center> ILO </center></th></center>
<th><center> Rack </center></th></center>
<th><center> Status </center></th></center>
<th><center> Actions </center></th></center>
</tr>
</thead>
<tbody>
{% for server in posts %}
<tr>
<div class ="server">
<td></td>
<td><center>{{ server.ServerName }}</center></td>
<td><center>{{ server.Owner }}</center></td>
<td><center>{{ server.Project }}</center></td>
<td><center>{{ server.Description }}</center></td>
<td><center>{{ server.IP }}</center></td>
<td><center>{{ server.ILO }}</center></td>
<td><center>{{ server.Rack }}</center></td>
<td><h4><span class="badge badge-success">Online</span></h4></td></center>
<td>
<button type="button" class="btn btn-outline-danger" data-toggle="modal" href="#delete-server-{{server.id}}"
data-target="#Del{{server.id}}">Delete <i class="fa fa-trash-o"></i></button>
<button type="button" class="btn btn-outline-primary" data-toggle="modal" href="#edit-server-{{server.id}}"
data-target="#Edit{{server.id}}"> Edit <i class="fa fa-pencil"></i></button>
<div id ="Del{{server.id}}" class="modal fade" role="document">
<div class="modal-dialog" id="delete-server-{{server.id}}">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">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">
<form action="{% url 'delete_post' server.id %}" method="post">{% csrf_token %}
<h6>Are you sure you want to delete {{ server.ServerName }}?</h6>
<br>
<center><input type="submit" class="btn btn-danger btn-md" value="Confirm"/>
<button type="submit" class="btn btn-secondary" data-dismiss="modal">Cancel</button></center>
</form>
</div>
</div>
</div>
</div>
<div class="modal fade bd-example-modal-sm" id="Edit{{server.id}}" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Edit Server <strong>{{ server.ServerName }}</strong> </h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
{% with server.id as server_id %}
{% with forms|get_by_key:server_id as edit_form %}
<form action="{% url 'edit_post' server_id %}" method="post"> {% csrf_token %}
<!--<center> {{ edit_form.as_p }} </center> -->
{% for field in forms.server_id %}
<div class="fieldWrapper">
{{ field.errors }}
<!-- {{ field.label_tag }} -->
<small><strong>{{ field.html_name }}<p align="left"></b> {{ field }}</small> </strong>
{% if field.help_text %}
<p class="help">{{ field.help_text|safe }}</p>
{% endif %}
</div>
{% endfor %}
</div>
<div class="wrapper">
<h2><button type="submit" class="save btn btn-success btn-lg">Confirm</button></h2>
<h2><button type="submit" class="btn btn-secondary btn-lg" data-dismiss="modal">Cancel</button></h2>
</div>
</form>
{% endwith %}
{% endwith %}
</div>
</td>
</tr>
{% endfor %}
</tbody>
</h5>
</table>
<div class="modal fade AddServer" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Add Server</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form method="post" novalidate> {% csrf_token %}
<!--<center> {{ form.as_p }} </center> -->
{% for field in form %}
<div class="fieldWrapper">
{{ field.errors }}
<!-- {{ field.label_tag }} -->
<small><strong>{{ field.html_name }}</strong></small><p align="left"></b> {{ field }} </p>
{% if field.help_text %}
<p class="help">{{ field.help_text|safe }}</p>
{% endif %}
</div>
{% endfor %}
</div>
<div class="wrapper">
<h2><button type="submit" class="save btn btn-success btn-lg" >Confirm</button></h2>
<h2><button type="submit" class="btn btn-secondary btn-lg" data-dismiss="modal">Cancel</button></h2>
</div>
</div>
</form>
</div>
</div>
</div>
views.py -
# Create your views here.
from django.shortcuts import render_to_response
from django.shortcuts import get_object_or_404
from django.shortcuts import render, redirect
from django.template import RequestContext
from django.views.generic import TemplateView, UpdateView, DeleteView, CreateView
from DevOpsWeb.forms import HomeForm
from DevOpsWeb.models import serverlist
from django.core.urlresolvers import reverse_lazy
from simple_search import search_filter
from django.db.models import Q
class HomeView(TemplateView):
template_name = 'serverlist.html'
def get(self, request):
form = HomeForm()
query = request.GET.get("q")
posts = serverlist.objects.all()
forms = {}
if query:
posts = serverlist.objects.filter(Q(ServerName__icontains=query) | Q(Owner__icontains=query) | Q(Project__icontains=query) | Q(Description__icontains=query) | Q(IP__icontains=query) | Q(ILO__icontains=query) | Q(Rack__icontains=query))
else:
posts = serverlist.objects.all()
#for post in posts:
# form = HomeForm(instance=post)
for post in posts:
forms[post.id] = HomeForm(instance=post)
args = {'form' : form,'forms': forms, 'posts' : posts}
#args = {'form' : form, 'forms': forms, 'posts' : posts}
return render(request, self.template_name, args)
def post(self,request):
form = HomeForm(request.POST)
posts = serverlist.objects.all()
if form.is_valid(): # Checks if validation of the forms passed
post = form.save(commit=False)
post.save()
#form = HomeForm()
return redirect('serverlist')
for post in posts:
forms[post.id] = HomeForm(instance=post)
args = {'form' : form, 'forms': forms, 'posts' : posts}
#args = {'form' : form,'forms': forms, 'posts' : posts}
return render(request, self.template_name,args)
class PostDelete(DeleteView):
model = serverlist
success_url = reverse_lazy('serverlist')
class PostEdit(UpdateView):
template_name = 'serverlist.html'
model = serverlist
form_class = HomeForm
#fields = ['ServerName','Owner','Project','Description','IP','ILO','Rack','Status']
success_url = reverse_lazy('serverlist')
#def get_object(self):
# obj = get_object_or_404(Calification, pk=self.request.POST.get('pk'))
# return obj
This :
{% with server.id as server_id %}
{# ... #}
{{ forms.server_id.as_p }}
just cannot work - it will look for forms["server_id"] (=> use the literal string "server_id" as key). You will need a custom template filter, such as the one described here. And as Daniel Roseman rightly mentions in a comment, you'll have to pass whatever server is supposed to be to your template's context too.
Also note that you're going to get a NameError in HomeView.post - you copy-pasted part of the code filling in your posts dict but not the part instanciating it. You should really factor this out instead of copy-pasting.