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>
Related
I am writing a website on Flask, and I encountered a problem that when I send an email with a link to a password recovery page, the http address of which has a token that changes every time, the template that I connected is not generated at all. with completely wrong css styles.
Although the same template is connected in the same way to other pages and everything is fine, what is needed is generated
Here is my view function to handle this page
#app.route('/reset_password/<token>', methods=['POST', 'GET'])
def reset_token(token):
if current_user.is_authenticated:
return redirect(url_for('index_page'))
user = User.verify_reset_token(token)
if user is None:
flash('Неправильний,або застарілий токен', category='error')
return redirect(url_for('reset_password'))
form = ResetPasswordForm()
if form.validate_on_submit():
hash_password = generate_password_hash(form.password.data)
user.password = hash_password
db.session.commit()
return render_template('reset_password.html', title='Відновлення паролю', form=form,
css_link=css_file_reset_password_request_page)
For comparison, here is a function that connects to the same css-style
#app.route('/reset_password', methods=['POST', 'GET'])
def reset_password():
if current_user.is_authenticated:
return redirect(url_for('index_page'))
form = RequestResetForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user is None:
flash('Неправильний email', category='error')
else:
send_reset_email(user)
flash('Повідомлення було надіслано на вашу електронну пошту,зайдіть туди,щоб отримати '
'інструкції', category='success')
return render_template('reset_password_request.html', title='Відновлення паролю', form=form,
css_link=css_file_reset_password_request_page)
But as a result, these pages have a completely different look
Here is the html template of this page(It is the same as reset_password_request from the previous function, only with some changes)
{% extends 'base.html' %}
{% block body %}
{{ super() }}
{% for cat, msg in get_flashed_messages(True) %}
<div class="flash {{cat}}">{{msg}}</div>
{% endfor %}
<div class="container">
<form class="box" method="POST">
{{ form.hidden_tag() }}
<h1 title="Будь ласка,придумайте новий надійний
пароль">Оновлення паролю</h1>
<div class="group">
<label>{{ form.password.label }}</label>
{{ form.password }}
</div>
<div class="group">
<label>{{ form.double_password.label }}</label>
{{ form.double_password }}
</div>
<div class="group">
<center><button>Відновити</button></center>
</div>
</form>
</div>
{% endblock %}
THIS IS MY base.html FILE
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="{{ css_link }}" type="text/css"/>
<script src="https://kit.fontawesome.com/b8991598b2.js"></script>
{% block title %}
{% if title %}
<title>{{ title }}</title>
{% else %}
<title>Сайт</title>
{% endif %}
{% endblock %}
</head>
<body>
<div class="content">
<header class="p-3 bg-dark text-white">
<div class="container">
<div class="d-flex flex-wrap align-items-center justify-content-center justify-content-lg-start">
<a href="/" class="d-flex align-items-center mb-2 mb-lg-0 text-white text-decoration-none">
<svg class="bi me-2" width="40" height="32" role="img" aria-label="Bootstrap"><use xlink:href="#bootstrap"></use></svg>
</a>
<ul class="nav col-12 col-lg-auto me-lg-auto mb-2 justify-content-center mb-md-0">
<li>Home</li>
<li>Features</li>
<li>Pricing</li>
<li>FAQs</li>
<li>About</li>
</ul>
<div class="search-box">
<input class="search-txt" type="text" placeholder="Search...">
<a class='search-btn' href="#">
<i class="fas fa-search"></i>
</a>
</div>
<div class="text-end">
Sign-up
Login
Logout
</div>
</div>
</div>
</header>
{% block body %}
{% endblock %}
</div>
<footer class="footer">
<ul class="nav justify-content-center border-bottom pb-3 mb-3">
<li class="nav-item">Home</li>
<li class="nav-item">Features</li>
<li class="nav-item">Pricing</li>
<li class="nav-item">FAQs</li>
<li class="nav-item">About</li>
</ul>
</footer>
</body>
</html>
And this is my connect to css_files in main.py
css_file = 'static/css/main.css'
css_file_authorization = 'static/css/login_form.css'
css_file_reset_password_request_page = 'static/css/request_passsword.css'
But here is an example of a page that is generated after switching from email:
And here is the one that should have been generated, and is generated in the case of the second handler function
Maybe someone knows how to solve it
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 have a for loop that displays images (media_gallery1-4) obtained from users. Each post should display four images and cycle in a bootstrap carousel. There are about 10 posts on my page. When I click the next or previous button on any of the 10 posts it only changes the image of the first post and the other 9 remain the same. How do I change my code so that the next/previous arrows change cycle through the images for that specific posts. Let me know if more context is needed.
{% for post in posts %}
<div class="container">
<div class="row">
<div class = "form-group col-md-6 mb-0">
<div id="carouselExampleControls" class="carousel slide">
<ol class="carousel-indicators">
<li data-target="#carouselExampleIndicators" data-slide-to="0"class="active">
</li>
<li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="3"></li>
</ol>
<div class="carousel-inner">
<div class="carousel-item active" id="slide1">
{% if post.media_gallery %}
<img class="img" src="{{post.media_gallery.url}}">
{% else %}
<div class="defualt_image">
<img src= "{% static 'main/images/boston_apartments.jpg' %}">
</div>
{% endif %}
</div>
<div class="carousel-item active" id="slide2">
{% if post.media_gallery2 %}
<img class="img" src="{{post.media_gallery2.url}}">
{% else %}
<div class="defualt_image">
<img src= "{% static 'main/images/boston_apartments.jpg' %}">
</div>
{% endif %}
</div>
<div class="carousel-item active" id="slide3">
{% if post.media_gallery %}
<img class="img" src="{{post.media_gallery3.url}}">
{% else %}
<div class="defualt_image">
<img src= "{% static 'main/images/boston_apartments.jpg' %}">
</div>
{% endif %}
</div>
<div class="carousel-item active" id="slide4">
{% if post.media_gallery %}
<img class="img" src="{{post.media_gallery4.url}}">
{% else %}
<div class="defualt_image">
<img src= "{% static 'main/images/boston_apartments.jpg' %}">
</div>
{% endif %}
</div>
<a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-
slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleControls" role="button" data-
slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
</div>
</div>
</div>
Hey Did you try this code :
<!DOCTYPE html>
<html>
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
{% for post in posts %}
<div class="container">
<div class="row">
<div class = "form-group col-md-6 mb-0">
<div id="carouselExampleControls" class="carousel slide">
<ol class="carousel-indicators">
<li data-target="#carouselExampleIndicators" data-slide-to="0"class="active"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="3"></li>
</ol>
<!-- Wrapper for slides -->
<div class="carousel-inner">
<div class="carousel-item active" id="slide1">
{% if post.media_gallery %}
<img class="img" src="{{post.media_gallery.url}}">
{% else %}
<div class="defualt_image">
<img src= "{% static 'main/images/boston_apartments.jpg' %}">
</div>
{% endif %}
</div>
<div class="carousel-item" id="slide2">
{% if post.media_gallery2 %}
<img class="img" src="{{post.media_gallery2.url}}">
{% else %}
<div class="defualt_image">
<img src= "{% static 'main/images/boston_apartments.jpg' %}">
</div>
{% endif %}
</div>
<div class="carousel-item" id="slide3">
{% if post.media_gallery %}
<img class="img" src="{{post.media_gallery3.url}}">
{% else %}
<div class="defualt_image">
<img src= "{% static 'main/images/boston_apartments.jpg' %}">
</div>
{% endif %}
</div>
<div class="carousel-item" id="slide4">
{% if post.media_gallery %}
<img class="img" src="{{post.media_gallery4.url}}">
{% else %}
<div class="defualt_image">
<img src= "{% static 'main/images/boston_apartments.jpg' %}">
</div>
{% endif %}
</div>
<a class="right carousel-control" href="#carouselExampleIndicators" data-slide="next">
<span class="glyphicon glyphicon-chevron-right"></span>
<span class="sr-only">Next</span>
</a>
<a class="left carousel-control" href="#carouselExampleIndicators" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left"></span>
<span class="sr-only">Previous</span>
</a>
</div>
</div>
</div>
</div>
</body>
I've came across an issue where message is displayed twice even though its called only once. Sometimes only one message is displayed however, most of the time 2 messages are.
My view:
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
messages.success(request, f'Account created has been creted! You can log-in now.')
return redirect('login')
else:
if request.user.is_authenticated:
messages.error(request, 'You are loged-in and in order to registrate you must be loged-out.')
return redirect('blog-home')
else:
form = UserRegisterForm()
return render(request, 'users/register.html', {'form': form,'title':'Register Page'})
And here is my template:
Base.html
{% load static %}
<!DOCTYPE html>
<html>
<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/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="{% static 'blog/main.css' %}">
{% if title %}
<title> Django blog - {{ title }}</title>
{% else %}
<title> Django blog</title>
{% endif %}
</head>
<body>
<header class="site-header">
<nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top">
<div class="container">
<a class="navbar-brand mr-4" href="{% url 'blog-home' %}">Django Blog</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarToggle">
<div class="navbar-nav mr-auto">
<a class="nav-item nav-link" href="{% url 'blog-home' %}">Home</a>
<a class="nav-item nav-link" href="{% url 'blog-about' %}">About</a>
</div>
<!-- Navbar Right Side -->
<div class="navbar-nav">
{% if user.is_authenticated %}
<a class="nav-item nav-link" href="{% url 'profile' %}">{{ user.username }}</a>
<a class="nav-item nav-link" href="{% url 'logout' %}">Logout</a>
{% else %}
<a class="nav-item nav-link" href="{% url 'login' %}">Login</a>
<a class="nav-item nav-link" href="{% url 'register' %}">Register</a>
{% endif %}
</div>
</div>
</div>
</nav>
</header>
<main role="main" class="container">
<div class="row">
<div class="col-md-8">
{% if messages %}
{% for message in messages %}
{% if message.tags == 'error' %}
<div class="alert alert-danger">
{{ message }}
</div>
{% else %}
<div class="alert alert-{{ message.tags }}">
{{ message }}
</div>
{% endif %}
{% endfor %}
{% endif %}
{% block content %}{% endblock %}
</div>
<div class="col-md-4">
<div class="content-section">
<h3>Our Sidebar</h3>
<p class='text-muted'>You can put any information here you'd like.
<ul class="list-group">
<li class="list-group-item list-group-item-light">Latest Posts</li>
<li class="list-group-item list-group-item-light">Announcements</li>
<li class="list-group-item list-group-item-light">Calendars</li>
<li class="list-group-item list-group-item-light">etc</li>
</ul>
</p>
</div>
</div>
</div>
</main>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>
You can see that in the {% if messages %} block, message is called only once.
And here is the main html:
{% extends "blog/base.html" %}
{% block content%}
{% for post in posts %}
<article class="media content-section">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="#">{{ post.author.first_name }}</a>
<small class="text-muted">{{ post.date_posted|date:"d F, Y"}}</small>
</div>
<h2><a class="article-title" href="#">{{ post.title }}</a></h2>
<p class="article-content">{{ post.content }}</p>
</div>
</article>
{% endfor %}
{% endblock content%}
Any ideas what could be causing this?
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