Django pagination problem - pages not getting paginated - html

I'm using Django-filters to filter results. The filter is working correctly, but now the pagination is not working. It's being rendered, but now all the products are being displayed in one page. I was using paginate_by = 6 as it is a class based view. Even after filtering results, for example there are 8 products matching the filter, everything is being displayed in one single page. Why is it not working? Can anyone please help me out? Thanks in advance!
My filters.py:
import django_filters
from .models import Item
class ItemFilter(django_filters.FilterSet):
class Meta:
model = Item
fields = {
'category': ['exact'],
'price': ['lte']
}
My views.py:
from .filters import ItemFilter
class homeview(ListView):
model = Item
template_name = 'products/home.html'
paginate_by = 6
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['filter'] = ItemFilter(self.request.GET, queryset=self.get_queryset())
return context
My index.html:
<div class="card mb-4">
<div class="card-body">
<div class="container">
<form method="GET">
{{ filter.form|crispy }}
<button type="submit" class="btn btn-primary mt-4">Filter</button>
</form>
</div>
</div>
</div>
<h1>List Of Items</h1>
<div class="row mb-4">
{% for item in filter.qs %}
<div class="col-lg-4">
<img class="thumbnail" src="{{ item.image_url }}">
<div class="box-element product">
<h6><strong>{{ item.title }}</strong></h6>
<h6 class="text-success">Category - {{ item.get_category_display }}</h6>
<hr>
</div>
</div>
{% endfor %}
</div>
<ul class="pagination justify-content-center">
{% if is_paginated %}
{% if page_obj.has_previous %}
<a class="btn btn-outline-dark mb-4" href="?page=1">First</a>
<a class="btn btn-outline-dark mb-4" href="?page={{ page_obj.previous_page_number }}">Previous</a>
{% endif %}
{% for num in page_obj.paginator.page_range %}
{% if page_obj.number == num %}
<a class="btn btn-dark mb-4" href="?page={{ num }}">{{ num }}</a>
{% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
<a class="btn btn-outline-dark mb-4" href="?page={{ num }}">{{ num }}</a>
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
<a class="btn btn-outline-dark mb-4" href="?page={{ page_obj.next_page_number }}">Next</a>
<a class="btn btn-outline-dark mb-4" href="?page={{ page_obj.paginator.num_pages }}">Last</a>
{% endif %}
{% endif %}
</ul>

First of all You're not using page object created by django's ListView methods. Technically you pass a new queryset instead. Therefore you're listing all the results instead of paginated results.
super().context already has a page object which is not used here. since you use ItemFilter
Here's how I'd handle the situation. without django_filters though
forms.py
class FilterForm(forms.Form):
category = forms.CharField()
price = forms.IntegerField()
views.py
from .forms.py import FilterForm
class HomeView(ListView):
model = Item
template_name = 'products/home.html'
paginate_by = 6
def get_filter_args(self):
request = self.request
filter_args = {}
filter_args['category'] = request.GET.get('category')
filter_args['price__lte'] = request.GET.get('price')
# To remove filter arg if the value is null. to avoid errors
filter_args = {key: value for key, value in filter_args.items() if value}
return filter_args
def get_queryset(self):
filter_args = self.get_filter_args()
queryset = super().get_queryset().filter(**filter_args)
return queryset
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['form'] = FilterForm()
return context
In order to prevent the applied filters from losing on pagination, use a helper to build url for pagination add this file in a templatetags folder inside the app folder (same path where views.py, models.py etc...)
temptag.py
register = template.Library()
#register.simple_tag
def paginate_url(field_name, value, urlencode=None):
get_query = f'{field_name}={value}'
if urlencode:
qs = urlencode.split('&')
_filtered = filter(lambda p: p.split('=')[0] != field_name, qs)
querystring = '&'.join(_filtered)
get_query = f'{get_query}&{querystring}'
return get_query
you can import the template helper inside html file
html file
{% load temptag %}
<div class="card mb-4">
<div class="card-body">
<div class="container">
<form method="GET">
{{ form|crispy }}
<button type="submit" class="btn btn-primary mt-4">Filter</button>
</form>
</div>
</div>
</div>
<h1>List Of Items</h1>
<div class="row mb-4">
{% for item in object_list %}
<div class="col-lg-4">
<img class="thumbnail" src="{{ item.image_url }}">
<div class="box-element product">
<h6><strong>{{ item.title }}</strong></h6>
<h6 class="text-success">Category - {{ item.get_category_display }}</h6>
<hr>
</div>
</div>
{% endfor %}
</div>
<ul class="pagination justify-content-center">
{% if is_paginated %}
{% if page_obj.has_previous %}
<a class="btn btn-outline-dark mb-4" href="?{% paginate_url 'page' 1 request.GET.urlencode %}">First</a>
<a class="btn btn-outline-dark mb-4" href="?{% paginate_url 'page' page_obj.previous_page_number request.GET.urlencode %}">Previous</a>
{% endif %}
{% for num in page_obj.paginator.page_range %}
{% if page_obj.number == num %}
<a class="btn btn-dark mb-4" href="?{% paginate_url 'page' num request.GET.urlencode %}">{{ num }}</a>
{% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
<a class="btn btn-outline-dark mb-4" href="?{% paginate_url 'page' num request.GET.urlencode %}"</a>
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
<a class="btn btn-outline-dark mb-4" href="?{% paginate_url 'page' page_obj.next_page_number request.GET.urlencode %}">Next</a>
<a class="btn btn-outline-dark mb-4" href="?{% paginate_url 'page' page_obj.paginator.num_pages request.GET.urlencode %}">Last</a>
{% endif %}
{% endif %}
</ul>

Write your get_context_data() like that
def get_context_data(self, **kwargs):
items = Item.objects.all()
context = super().get_context_data(**kwargs)
context['filter'] = ItemFilter(self.request.GET, queryset=items)
return context

I had a similar problem when using django-filter. However, my solution was using List.js, as I had a table that I not only want paginated, but I wanted the table headers to be sortable.
You can probably use List.js here, even though you don't have a list or table of data (you can also check out some example codepens by the creator of List.js).
index.html:
<h1>List Of Items</h1>
<div id="paginate-items"> <!-- Need a container with a unique ID for List.js -->
<div class="row mb-4 list"> <!-- Must include the class "list" for the div containing the data to be paginated -->
{% for item in filter.qs %}
<div class="col-lg-4">
<img class="thumbnail" src="{{ item.image_url }}">
<div class="box-element product">
<h6><strong>{{ item.title }}</strong></h6>
<h6 class="text-success">Category - {{ item.get_category_display }}</h6>
<hr>
</div>
</div>
{% endfor %}
</div>
<ul class="pagination"></ul>
</div>
...
<!-- You'll need to include jQuery and List.js just before the close of the '<body>' tag: -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/list.js/1.5.0/list.min.js"></script>
Then, in a separate .js file:
var myData= new List('paginate-items', {
page: 3, // refers to how many items per page
pagination: true
});
And some simple styling in a separate .css file:
.pagination li {
display:inline-block;
padding:5px;
}

Related

sending data from a "form action" to a views function in django

How are you community, I'm a little confused between my newbies and lack of knowledge, I'm working on a small project in Django and I'm also trying to send data from a form action in the html to another view function but I'm not understanding it well How does this work and on top of that I have to send several data not just one and it confuses me even more, I have the following HTML:
{% extends "base.html" %}
{% block content %}
<main class="container">
<div class="row">
<div class="col-md-10 offset-md-1 mt-5">
<form action="/interface/" method="POST" class="card card-body">
<h1>Interface</h1>
<h4>{{ error }}</h4>
<select name="dv">
<option selected disabled="True">Select Device</option>
{% for device in devicess %}
<option>{{ device.id }} - {{ device.name }}</option>
{% endfor %}
</select>
<br>
{% csrf_token %}
<br>
<button type="submit" class="btn btn-primary">Send</button>
</form>
<br>
{% for interface in interfaces %}
<section class="card card-body">
<h2>{{interface.Interface}}</h2>
{% if interface.Description == "" %}
<p class="text-secondary">none description</p>
{% else %}
<P class="text-secondary">{{interface.Description}}</P>
{% endif %}
<form action= "{% url 'send_description' %}"method="POST">
{% csrf_token %}
<input type="text" name="command" class="form-control" placeholder="Change description">
<br>
<button type="submit" class="btn btn-primary align-content-lg-center">Send change</button>
</form>
<br>
{% if interface.Status == "up" %}
<p class="text-secondary">Interface State: 🟒 Free</p>
{% else %}
<p class="text-secondary">Interface State: πŸ”΄ Used</p>
{% endif %}
</section>
<br>
{% endfor %}
</div>
</div>
</main>
{% endblock %}
and aesthetically to better understand the first POST executed like this:
So far everything is perfect, if I press the "Send change" button it redirects me perfectly, the problem is that I need to send various data such as device.id, interface to that function that I am executing in the action= "{% url 'send_description' %} .Interface and also the content of the input that is inside the same form. Could you give me a hand or a guide on where to find the best way?
regards!
Let me start by saying that this would work way better with JS and AJAX. But, to answer your question, data is passed via Django http request object, in your case, since you have several different forms, it is possible to pass this data by adding a hidden field inside each form with the desired value:
<input type="hidden" name="interface" value="{{ interface.id }}">
And fetch this value form the request object in the view:
interface = request.POST.get('interface')
A full example:
models.py
class Device(models.Model):
name = models.CharField(max_length=100)
class Interface(models.Model):
name = models.CharField(max_length=100)
description = models.CharField(max_length=100, default='interface description field')
status = models.BooleanField(default=False)
device = models.ForeignKey(Device, on_delete=models.CASCADE, related_name='interfaces')
views.py
from django.core.exceptions import ObjectDoesNotExist
def list_interfaces(request):
devices = Device.objects.all()
interfaces = None
try:
selected_device = Device.objects.get(id=request.POST.get('dv'))
interfaces = selected_device.interfaces.all()
except ObjectDoesNotExist:
selected_device = Device.objects.all().first()
if selected_device:
interfaces = selected_device.interfaces.all()
else:
selected_device = None
context = {
'devices': devices,
'selected_device': selected_device,
'interfaces': interfaces
}
return render(request, 'list_device_interfaces.html', context)
def send_description(request):
command = request.POST.get('command')
device = request.POST.get('seleted_device')
interface = request.POST.get('interface')
print(f'command: {command}')
print(f'device_id: {device}')
print(f'device_id: {interface}')
return redirect('core:list-device-interfaces')
urls.py
from core import views
from django.urls import path
app_name = 'core'
urlpatterns = [
path("list/device/interfaces/" , views.list_interfaces, name="list-device-interfaces"),
path("send/description/" , views.send_description, name="send-description"),
]
list_device_interfaces.html
{% extends "base.html" %}
{% block content %}
<main class="container">
<div class="row">
<div class="col-md-10 offset-md-1 mt-5">
<form action="{% url 'core:list-device-interfaces' %}" method="POST" class="card card-body">
{% csrf_token %}
<h1>Device</h1>
<h4>{{ error }}</h4>
<select name="dv">
<option selected disabled="True">Select Device</option>
{% for device in devices %}
<option value="{{ device.id }}" {% if device.id == selected_device.id %} selected {% endif %}>{{ device.id }} - {{ device.name }}</option>
{% endfor %}
</select>
<br>
<br>
<button type="submit" class="btn btn-primary">Send</button>
</form>
<br>
<hr>
<h2>Interfaces</h2>
{% for interface in interfaces %}
<section class="card card-body">
<h2>{{interface.name}}</h2>
{% if interface.description == "" %}
<p class="text-secondary">none description</p>
{% else %}
<P class="text-secondary">{{interface.description}}</P>
{% endif %}
<form action= "{% url 'core:send-description' %}"method="POST">
{% csrf_token %}
<input type="text" name="command" class="form-control" placeholder="Change description">
<input type="hidden" name="seleted_device" value="{{ selected_device.id }}">
<input type="hidden" name="interface" value="{{ interface.id }}">
<br>
<button type="submit" class="btn btn-primary align-content-lg-center">Send change</button>
</form>
<br>
{% if interface.status %}
<p class="text-secondary">Interface State: 🟒 Free</p>
{% else %}
<p class="text-secondary">Interface State: πŸ”΄ Used</p>
{% endif %}
</section>
<br>
{% endfor %}
</div>
</div>
</main>
{% endblock %}

I am getting an error when trying to click on Like button This page isn’t working HTTP ERROR 405

I am new to Django and trying to implemet Like and Dislike option in Blog application.
I have issue where once any logged in user click Like button the browser gives HTTP ERROR 405
Once user click Like button it redirect to PostDetailView (post_detail)
I have also added POST in form method as below in post_detail.html page
view.py
class PostDetailView(DetailView):
model = Post
template_name = 'blog/post_detail.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
data = get_object_or_404(Post, id=self.kwargs['pk'])
total_likes = data.total_likes()
liked = False
if data.likes.filter(id=self.request.user.id).exists():
liked = True
else:
pass
context["total_likes"] = total_likes
context["liked"] = liked
return context
def LikeView(request,pk):
if request.method == 'POST':
post = get_object_or_404(Post, id=request.POST.get('post_id'))
liked = False
if post.likes.filter(id=request.user.id).exists():
post.likes.remove(request.user)
else:
post.likes.add(request.user)
liked = True
post.likes.add(request.user)
return HttpResponseRedirect(reverse('post_detail', args=[str(pk)]))
post_detail.html
{% extends 'blog/base.html' %}
{% block content %}
{% csrf_token %}
<article class="media content-section">
<img class="rounded-circle article-img" src="{{ object.author.profile.image.url }}">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="{% url 'user_post' object.author.username %}">{{ object.author }}</a>
<small class="text-muted">{{ object.date_posted }}</small>
</div>
<h2 class="article-title">{{ object.title }}</h2>
<p class="article-content">{{ object.content|urlize }}</p>
{% if object.author == user %}
<div>
<a class="btn sm btn btn-secondary mb-1" href="{% url 'post_update' object.id %}">Update</a>
<a class="btn sm btn btn-danger mb-1" href="{% url 'post_delete' object.id %}">Delete</a>
</div>
{% endif %}
<br/><br/>
<form action="{% url 'like_post' object.id %}"
method="POST">
{% csrf_token %}
{% if liked %}
<button class="btn btn-danger btn-sm" type="submit", name "post_id", value={{post.id}}>Unlike
</button>
{% else %}
<button class="btn btn-primary btn-sm" type="submit", name "post_id", value={{post.id}}>Like
</button>
{% endif %}
- {{ total_likes }}
</form>
</div>
</article>
{% endblock %}
urls.py
urlpatterns = [
path('', PostListView.as_view(), name='home'),
path('user/<str:username>', UserPostListView.as_view(), name='user_post'),
path('post/<int:pk>/', PostDetailView.as_view(), name='post_detail'),
path('post/<int:pk>/update', PostUpdateView.as_view(), name='post_update'),
path('post/<int:pk>/delete', PostDeleteView.as_view(), name='post_delete'),
path('post/new/', PostCreateView.as_view(), name='post_create'),
path('about/', views.about, name='about'),
path('contact/', views.contactView, name='contact'),
path('success/', views.successView, name='success'),
path('post/<int:pk>/', views.LikeView, name='like_post'),
]
In your urls.py
"like_post" and "post_detail"
have the same pattern.I think your code chooses "post_detail" instead of "like_post" when you post to this url.
urlpatterns = [
path('post/<int:pk>/like', views.LikeView, name='like_post'),
]
can solve you problem

i get an error. django.urls.exceptions.NoReverseMatch

l am started to learn Django few days ago, and I get this error:
django.urls.exceptions.NoReverseMatch: Reverse for 'create_order' with no arguments not found. 1 pattern(s) tried: ['create_order/(?P[^/]+)/$']*
urls.py
path('create_order/<str:pk>/', views.createOrder, name='create_order'),
views.py
def createOrder(request, pk):
customer = Customer.objects.get(id=pk)
form = OrderForm(initial={'customer': customer})
if request.method == 'POST':
# print('Printing:', request.POST)
form = OrderForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
context = {
'form': form
}
return render(request, 'accounts/order_form.html', context)
order_form.html
{% extends 'accounts/main.html' %}
{% load static %}
{% block content %}
<br>
<div class="row">
<div class="col-12 col-md-6">
<div class="card card-body">
<form action="" method="post">
{% csrf_token %}
{{form}}
<input class="btn btn-sm btn-danger" type="submit" value="Conform">
</form>
</div>
</div>
</div>
{% endblock %}
customer.html
<div class="row">
<div class="col-md">
<div class="card card-body">
<h5>Customer:</h5>
<hr>
<a class="btn btn-outline-info btn-sm btn-block" href="">Update Customer</a>
<a class="btn btn-outline-info btn-sm btn-block" href="{% url 'create_order' customer.id %}">Place Order</a>
</div>
</div>
As the error said, it tried with empty argument, means there was no customer value available in context. So you need to send the customer value through context, like this:
context = {
'customer' : customer,
'form': form
}
I was also following this tutorial from youtube(dennis ivy) and got the same error,
don't know what is the problem but just replace the file urls.py from github with the same context and it's not showing that error,.
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name="home"),
path('products/', views.products, name='products'),
path('customer/<str:pk_test>/', views.customer, name="customer"),
path('create_order/<str:pk>/', views.createOrder, name="create_order"),
path('update_order/<str:pk>/', views.updateOrder, name="update_order"),
path('delete_order/<str:pk>/', views.deleteOrder, name="delete_order"),
]
views.py
from django.forms import inlineformset_factory
def createOrder(request, pk):
OrderFormSet = inlineformset_factory(Customer, Order, fields=('product', 'status'), extra=10 )
customer = Customer.objects.get(id=pk)
formset = OrderFormSet(queryset=Order.objects.none(),instance=customer)
#form = OrderForm(initial={'customer':customer})
if request.method == 'POST':
#print('Printing POST:', request.POST)
#form = OrderForm(request.POST)
formset = OrderFormSet(request.POST, instance=customer)
if formset.is_valid():
formset.save()
return redirect('/')
context = {'form':formset}
return render(request, 'accounts/order_form.html', context)
order_form.html
{% extends 'accounts/main.html' %}
{% load static %}
{% block content %}
<div class="row">
<div class="col-md-6">
<div class="card card-body">
<form action="" method="POST">
{% csrf_token %}
{{ form.management_form }}
{% for field in form %}
{{field}}
<hr>
{% endfor %}
<input type="submit" name="Submit">
</form>
</div>
</div>
</div>
{% endblock %}
again I don't know why it was showing this error and where was the problem but just relapced it with the same code from github and it worked..if someone know how it worked , that will be really helpful in near future. thanks to all regards Haris Ahmad

Delete posts on profile django

I have been working on a project and one of the functions that it has it to delete posts, when in the imagelist view, I am able to delete those posts but when I am in the profile view which shows the user's posts when I try to delete it, a 404 error page not found shows up. I dont know where the error is but I think it is on the profile view.
views.py
def profile(request, pk=None):
if pk:
post_owner = get_object_or_404(User, pk=pk)
user_posts=Post.objects.filter(user_id=pk)
else:
post_owner = request.user
user_posts=Post.objects.filter(user_id=pk)
return render(request, 'profile.html', {'post_owner': post_owner, 'user_posts': user_posts,})
profile.html
<div class="content-section">
<div class="media">
<img class="rounded-circle account-img" src="{{ user.profile.image.url }}">
<div class="media-body">
<h2 class="account-heading">{{ post_owner.username }}</h2>
<p class="text-secondary">{{ post_owner.email }}</p>
</div>
</div>
<div>
{% for Post in user_posts %}
<li class="list-group-item">{{ Post.text }}
{{ Post.user }}
{% if Post.posti %}
<img src="{{ Post.posti.url }}" alt="image here" style="max-width: 300px; max-height: 300px">
{% endif %}
{% if Post.user == user %}
<div class="float-right">
<form action="delete_image/{{ Post.id }}/" action="post">
<button type="submit" class="btn btn-outline-danger btn-sm">Delete</button>
</form>
</div>
{% endif %}
</li>
{% endfor %}
</div>
</div>
urls.py
urlpatterns = [
path('profile/<int:pk>/', views.profile, name='profile_pk'),
path('imagepost', views.uimage, name='image'),
path('imagelist', views.imagelist, name='imagelist'),
path('delete_image/<int:image_id>/', views.delete_image, name='delete_image'),
]
All I did for fixing this problem was create add an if statement to my imagelist.html
{% if image.user == user %}
{{ image.user }}
{% else %}
{{ image.user }}
{% endif %}

multiple html form from a single form model in django

i need your assistance
im building a school president vote tallying system
the vote results are saved in the polls table as
candidate id | pollingstationid | result |
when capturing the results the html page will render the form for each candidate. for example if there are 3 candidates the html form will have 3 forms:
candidate 1:
result _______
candidate id 1001
pollingstationid 301
candidate 2:
result _______
candidate id 1002
pollingstationid 301
candidate 3:
result _______
candidate id 1003
pollingstationid 301
[submit button]
the problem:
when i click submit, its only saving the last form(i.e candidate 3)
how do i get all three entries into the database each as a new row.
views.py
class candidatesview(AjaxFormMixin, View):
form_class = pollsForm
model = Polls
template_name = 'app/candidates.html'
def get(self, request):
form = self.form_class()
candidatesls = Candidates.objects.all()
context = {'title':'polls','form' : form, 'candidates': candidatesls }
#print(context)
return render(request, self.template_name, context )
def post(self, request):
form = pollsForm(request.POST)
candidatesls = Candidates.objects.all()
if form.is_valid():
print(form.cleaned_data['Result'])
print(form.cleaned_data['Candidateid'])
print(form.cleaned_data['PollingstationID'])
form.save()
messages.success(request,('Form submitted successfuly'))
else:
messages.warning(request,('nah!'))
print(messages)
context = {'title':'polls','form' : form, 'candidates': candidatesls, 'message':messages}
return render(request, self.template_name, context)
forms.py
class pollsForm(forms.ModelForm):
class Meta:
model = Polls
fields = ['Result', 'Candidateid','PollingstationID']
html (candidates.html)
{% extends "app/base.html" %}
{% load widget_tweaks %}
{% block content %}
<div class="bg-white">
<div class="row">
<div class="col-lg-4 col-md-4 col-sm-8">
{% if messages %}
{% for message in messages %}
<div class="alert alert-warning alert-dismissible show" role="alert">
{{ message }}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="false">Γ—</span>
</button>
</div>
{% endfor %}
{% endif%}
<div id="alertbox">
</div>
<div class="form-group">
<form class="my-ajax-form" method="POST" action="{% url 'polls' %}">
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{#{% for field in form.visible_fields %}#}
<table class="table">
{% for candidates in candidates %}
<tr>
<td>
{% render_field form.Result class="form-control" placeholder=candidates.CandidateName id=forloop.counter %}
<input type="number" class="form-control" id={{ forloop.counter }} value={{ candidates.CandidateID }}>
{% render_field form.PollingstationID type="hidden" class="form-control" id="C1_Pollingstation" %}
{% for error in field.errors %}
<span class="help-block">{{ error }}</span>
{% endfor %}
</td>
<td>
<div class="circle" style="background:{{ candidates.CandidateColor }}">2</div>
</td>
</tr>
{% endfor %}
</table>
<div class="pull-right">
<input type='submit' class='btn btn-next btn-fill btn-success btn-wd' name='Post' value='Post' />
</div>
</form>
</div>
</div>
</div>
</div>
<br />
{% endblock content %}
{% block javascript %}
<script>
$(document).ready(function(){
var $myForm = $(".my-ajax-form")
var $myMessage = $("#alertbox")
$myForm.submit(function(event){
event.preventDefault()
var $formData = $(this).serialize()
var $endpoint = $myForm.attr("data-url") || window.location.href
console.log($formData)
console.log($endpoint)
$.ajax({
method: "POST",
url: $endpoint,
data: $formData,
success: handleFormSuccess,
error: handleFormError,
})
function handleFormSuccess(data, textStatus, jqXHR){
console.log(data)
console.log(textStatus)
console.log(jqXHR)
$myForm[0].reset();
$myMessage.replaceWith('<div class="alert alert-success show" role="alert" id="alertbox"> post succcess</div> ');
}
function handleFormError(jqXHR, textStatus, errorThrown){
console.log(jqXHR)
console.log(textStatus)
console.log(errorThrown)
$myMessage.replaceWith('<div class="alert alert-warning show" role="alert" id="alertbox"> post failure</div> ');
}
})
})
</script>
{% endblock %}