Django: Javascript error with alert box displaying values - javascript

I am creating a web application that will serve as a grocery store. The way I set it up is so the customer can come onto the website, click on the items that they would like to purchase, and then click a submit button to purchase those items. The problem I am running into is that my Javascript is not printing the correct values. In both spots, it says undefined. I will put a picture below for reference.
views.py
def inventory(request):
products = request.POST.getlist('products')
for product in products:
a = Post.objects.get(title=product)
a.quantity = a.quantity -1
a.save()
print(products)
return redirect('blog-home')
home.html
{% extends "blog/base.html" %}
{% load static %}
{% block content %}
<form action="{% url 'js' %}" method="POST" id="menuForm">
{% for post in posts %}
{% if post.quantity > 0 %}
<article class="media content-section">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2">{{ post.category }}</a>
</div>
<h2><a class="article-title" >{{ post.title }}</a></h2>
<p class="article-content"> Price: ${{ post.Price }}</p>
<p class="article-content"> Sale: ${{ post.Sale }}</p>
<input type="checkbox" id="product_{{ post.id }}" value="{{ post.title }}" form="menuForm" name="products" > Inventory count: {{ post.quantity }}
</input>
</div>
</article>
{% else %}
{% endif %}
{% endfor %}
<button id="btn" type="submit" form="menuForm">Confirm Purchase</button>
</form>
<script src="{% static "JS/javascript.js" %}" type="text/javascript"></script>
{% endblock content %}
javascript.js
function getSelectedCheckboxValues(name) {
const checkboxes = document.querySelectorAll(`input[name="${name}"]:checked`);
let values = [];
checkboxes.forEach((checkbox) => {
values.push(checkbox.value);
});
return values, tPrice;
var price = 0;
var tPrice =0;
if (values=='Milk'){
var MPrice = 3.99
tPrice = price+MPrice;
}
if (values == 'Cheese'){
var CPrice = 4.50
tPrice = price + CPrice;
}
if (values == 'Yogurt'){
var YPrice = 1.99
tPrice = price + YPrice;
}
}
const btn = document.querySelector('#btn');
btn.addEventListener('click', (event) => {
alert('You ordered: ' + getSelectedCheckboxValues('products')+
'\nTotal Price: $'+ getSelectedCheckboxValues('tPrice'));
});

First of all you are passing the parameter to the function getSelectedCheckboxValues as a string when you call them in the alert which is completely wrong.
Also you are directly comparing values list with strings which is not possible. You need to loop over the list and then compare the different elements with the different products. I will also recommend to create an object instead of the list and keep the product name as key and its price as value.

Related

When using Fetch the page reloads (when it shouldn't) and only shows the Json data instead of the page that should be displayed

I am trying to make a basic twitter style application for a class project. When the like button is clicked the text in the button should then change to say unlike and the like count should increase by one without reloading the page. The database information is updated. The page itself reloads to a white background and the only thing on the page is my json data "{"likeButton": "Unlike", "total_likes": 0}", instead of the page itself. Any help would be appreciated.
Edit: here is a screenshot of the result I am getting
webpage screenshot
views.py
#login_required
def likes(request, post_id):
try:
current_user = request.user
post = Post.objects.get(id = post_id)
likeCount = Post.objects.get(id = post.id)
total_likes = likeCount.like_count
likeButton = request.POST.get('buttonForLikes')
if likeButton == 'Like':
total_likes = total_likes + 1
post.like_count = total_likes
post.save()
post.like.add(current_user)
post.save()
else:
total_likes = total_likes - 1
post.like_count = total_likes
post.like.remove(current_user)
post.save()
return JsonResponse ({'likeButton': likeButton, 'total_likes': total_likes,}, status=200,)
except KeyError:
return HttpResponseBadRequest("Like Error")
urls.py
from django.urls import path
from . import views
app_name = "network"
urlpatterns = [
path("", views.index, name="index"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
path("new-post", views.new_post, name="new-post"),
path("profile/<str:username>", views.profile, name="profile"),
path("follows/<str:username>", views.follows, name="follows"),
path("following", views.following, name="following"),
path("edit", views.edit, name="edit"),
path("likes/<int:post_id>", views.likes, name='likes')
]
HTML
{% extends "network/layout.html" %}
{% load static %}
{% block body %}
{% if user.is_authenticated %}
<div class="borderDiv">
<div class="newPostCard">
<form id = "new_post_form" name="newPost" action = "{% url 'network:new-post' %}" method ="POST">
{% csrf_token %}
<label id="test"><h2>New Post</h2></label><br>
<textarea id="newPostBox" name="newPost"></textarea></textarea><br><br>
<input type ="submit" id = "new_post_submit" class = "btn btn-primary">
</form>
</div>
</div>
{% endif %}
<div class="newPostCard">
{% for item in all_post %}
<div class="borderDiv">
<div class="newPostCard">
<h2>{{ item.user }}</h2>
<p id="user_post">{{ item.post }}</p>
</div>
<form id = "like_form" method ="POST" action = "{% url 'network:likes' item.id %}" >
{% if request.user in item.like.all %}
<div> <button claas="likes" id = 'likeButton' data-id= '{{ item.id }}' value="Unlike" name="buttonForLikes">
Unike</button>: <span id="numOfLikes">{{ item.like_count }}</span>
{% csrf_token %}
</div>
{% else %}
<div> <button class="likes" id = 'likeButton' data-id= '{{ item.id }}' value="Like" name="buttonForLikes">
Like</button>: <span id="numOfLikes">{{ item.like_count }}</span>
{% csrf_token %}
</div>
{% endif %}
</form>
<div>
{% if user.is_authenticated and request.user == item.user %}
<button class ="btn btn-primary" id="edit">Edit</button>
{% endif %}
<textarea id="editText" name="editBox" style="display: none;"></textarea>
<button class="btn btn-primary" id="editSaveButton" style="display: none;">Save</button>
</div>
<p><i>{{ item.timestamp }}</i></p>
</div>
</div>
{% endfor %}
<div id="page_num">
<span class="page_numbers">
{% if all_post.has_previous %}
« first
previous
{% endif %}
<span class="current_page">
Page {{ all_post.number }} of {{ all_post.paginator.num_pages }}.
</span>
{% if all_post.has_next %}
next
last »
{% endif %}
</span>
</div>
</div>
<script src="{% static 'network/edit.js' %}"></script>
<script src="{% static 'network/likes.js' %}"></script>
{% endblock %}
javascript
let likes = document.getElementById('likeButton');
likes.addEventListener("click", (e) =>{
e.preventDefault();
e.stopPropagation();
let likeCount = document.getElementById('numOfLikes');
fetch(`/likes/${likes.dataset.id}`, {
credentials: "include",
method: "PUT",
headers: {
"Accept": "application/json",
'Content-Type': 'application/json',
},
})
.then(response => response.text())
.then(result => {
if (result.likeButton === 'Like'){
likes.innerHTML = "Unlike";
likeCount.innerHTML = result.total_likes;
}
else{
likes.innerHTML = 'Like';
likeCount.innerHTML = result.total_likes;
}
})
return false;
});

How to handle error 404 when total items is lower than" per_page" flask pagination?

I am developing a web application with Flask Python.
In my application, there is a report page that displays a table of results with Flask pagination.
At the bottom of my table, I added a "select options" field called "number_result_per_page" to let the user choose the "per_page" parameters (number of items per page).
I made a javascript that reloads the page with the "per_page" parameters updated according to this user's choice.
PROBLEM :
My problem is if the user is almost on the last page, and he decides to display "100" results per page, and there are less than 100 results to display, I get a 404 error.
I am sure I am not the only one who faced this kind of issue. Is there any solution to avoid this scenario?
Or can I catch this particular error 404 to display an "error" popup and reload the previous page which was correct?
Here is sample of my code:
# Route
#app.route('/task_user_report/<int:task_user_id>/view', methods=['GET', 'POST'])
#login_required
def task_user_report(task_user_id):
args = request.args
per_page_task_report = args.get("per_page_task_report", 1, type=int)
actions = db_mysql.session.query(Action).filter_by(id_task_user=task_user_id) \
.filter(Action.id_contact==Contact.id) \
.paginate(page=page_task_report, per_page=per_page_task_report)
render_template(render_html,title='Task Report',legend='Task Report',actions=actions, \
per_page_task_report=per_page_task_report)
# Template
<div class="row justify-content-center" style="width: 95%;">
<div class="col-7 my-auto text-right">
<div class="text-center mt-4" style="display: inline-block;">
<nav aria-label="Pagination">
<ul class="pagination justify-content-center">
{% for page_num in actions.iter_pages(left_edge=1,right_edge=1,left_current=1, right_current=2) %}
{% if page_num %}
{% if actions.page == page_num %}
<li class="page-item active"><a class="page-link" href="{{ url_for('task_user_report',task_user_id=task_user_id,page_task_report=page_num,per_page_task_report=per_page_task_report) }}">{{ page_num }}</a>
{% else %}
<li class="page-item"><a class="page-link" href="{{ url_for('task_user_report',task_user_id=task_user_id,page_task_report=page_num,per_page_task_report=per_page_task_report) }}">{{ page_num }}</a>
{% endif %}
{% else %}
<li> ... </li>
{% endif %}
{% endfor %}
</ul>
</nav>
</div>
</div>
</div>
<div class="col-5 my-auto text-right">
<select style="width:180px!important;display: inline-block;" id="number_result_per_page" class="form-control form-control-sm w-25 text-right" onchange="change_per_page()">
<option value="10"
{% if per_page_task_report== 10 %}
selected
{% endif %}
>10 results per page</option>
<option value="25"
{% if per_page_task_report== 25 %}
selected
{% endif %}
>25 results per page</option>
<option value="50"
{% if per_page_task_report== 50 %}
selected
{% endif %}
>50 results per page</option>
<option value="100"
{% if per_page_task_report== 100 %}
selected
{% endif %}
>100 results per page</option>
</select></div>
</div>
# Javascript
<script>
function change_per_page() {
var url = window.location.href;
// we get value of per page option
var per_page_option = document.getElementById("number_result_per_page");
var per_page_option_value = per_page_option.value;
// We check if parameter exist in url
var is_per_page = url.includes("per_page_task_report");
if (is_per_page == true){
var queryParams = new URLSearchParams(window.location.search);
// new value of "page_task_report" is set to "per_page_option_value"
queryParams.set('per_page_task_report', String(per_page_option_value));
// change the search property of the main url
history.pushState(null, null, "?"+queryParams.toString());
var new_url = window.location.href;
}
else{
// There are 2 cases :
// [1] url doesn't have any parameters (ex:http://127.0.0.1:5000/task_user_report/2/view)
// [2] url has a parameter (ex:http://127.0.0.1:5000/task_user_report/2/view?page_task_report=2)
var is_page_task_report = url.includes("page_task_report");
if (is_page_task_report == true){
var new_url = url + '&per_page_task_report=' + per_page_option_value;
}
else{
var new_url = url + '?per_page_task_report=' + per_page_option_value;
}
}
window.location.replace(new_url);
}
</script>
In your paginate() call, set error_out=False like this, paginate(..., error_out=False)
The default is True. This behavior is not always desired though. If you are using Flask as an API backend, this can sometimes cause errors. It's up to you how you want to handle it by either providing an empty result set or by defaulting the page back to one when no results are returned.

How to handle JavaScript event inside a inlineformset_factory with formset_media_js

I have an inlineformset_factory implemented with formset_media_js, these two by itself are working ok. What I need to implement is to be able to handle the enable and disable state of some checkboxes and input fields that are inside the inlineformset_factory.
I have a javascript that works on the first group of formset created on page load, but when a new formset is added by the user the javascript is not working.
How can I handle the new formsets input fields added by the user with javascript?
If "is chapter" is checked then "is subchapter" and "quantity" are disabled, by default the inlineformset_fatory creates 1 formset on page load, on this formset the javascript works. But when the user adds another formset with button "Add another Budget Item" the javascript is no longer working. If for example, I configure the inlineformser_factory to create 3 formset on page load the javascript works on those 3 formset but not on the formsets added by the user.
forms.py : at this forms.py i have the inlineformset_factory that is created every time the user adds a formset.
from django import forms
from django.forms import inlineformset_factory
from djangoformsetjs.utils import formset_media_js
from accounts.models import ProjectManager
from projects.models import Project, BudgetModel, BudgetModelItems
class CreateBudgetItem(forms.ModelForm):
class Media(object):
js = formset_media_js
class Meta:
model = BudgetModelItems
fields = ('budget_model',)
widgets = {
'budget_item_description': forms.Textarea(attrs={'rows': 2, 'cols': 50}),
'budget_item_item': forms.NumberInput(attrs={'size': 6}),
'budget_item_quantity': forms.NumberInput(attrs={'size': 6}),
}
BudgetItemFormset = inlineformset_factory(BudgetModel, BudgetModelItems,
form=CreateBudgetItem,
fields=('budget_model', 'budget_item_item',
'budget_item_description', 'budget_item_unit',
'budget_item_quantity', 'budget_item_is_chapter',
'budget_item_is_subchapter'),
extra=1,
can_delete=True,
can_order=True
)
views.py
from django.shortcuts import render, redirect
from django.forms import formset_factory
from accounts.models import ProjectManager
from projects.forms.create_project import CreateProjectForm
from projects.forms.create_budgetmodel import BudgetFormset, ProjectForBudgetModel
from projects.forms.create_budgetitem import CreateBudgetItem, BudgetItemFormset
from projects.models import BudgetModel, Project
def create_budget_item(request):
user = request.user.projectmanager
projects = Project.objects.filter(project_manager_id=user)
models = BudgetModel.objects.none()
project_form = ProjectForBudgetModel(user)
budget_item_form = CreateBudgetItem()
formset = BudgetItemFormset()
for project in projects:
models |= BudgetModel.objects.filter(project_id=project.pk)
budget_item_form.fields['budget_model'].queryset = models
if request.method == 'POST':
project_form = ProjectForBudgetModel(user, request.POST)
budget_item_form = CreateBudgetItem(request.POST)
if project_form.is_valid() and budget_item_form.is_valid():
# project_id = project_form.cleaned_data['project']
budget_model_id = budget_item_form.cleaned_data['budget_model']
formset = BudgetItemFormset(request.POST, instance=budget_model_id)
if formset.is_valid():
formset.save()
context = {'project_form': project_form,
'bi_form': budget_item_form,
'formset': formset,
'models': models}
return render(request, 'projects/create_budget_items.html', context)
budget_item_form.html: this form is called (included) at create_budget_items.html
<div data-formset-form>
<div class="card">
<div class="card-body">
<div class="row">
<div class="col">
<table class="table">
<thead class="thead-light">
<tr>
<th scope="col">Item</th>
<th scope="col">Description</th>
<th scope="col">Unit</th>
<th scope="col">Quantity</th>
<th scope="col">Is Chapter</th>
<th scope="col">Is SubChapter</th>
</tr>
</thead>
<tbody>
<tr>
<th>{{ form.budget_item_item }}</th>
<td>{{ form.budget_item_description }}</td>
<td>{{ form.budget_item_unit }}</td>
<td>{{ form.budget_item_quantity }}</td>
<td>{{ form.budget_item_is_chapter }}</td>
<td>{{ form.budget_item_is_subchapter }}</td>
</tr>
</tbody>
</table>
</div>
<div class="col-md-auto">
{% if form.ORDER %}
<div class="row mt-1">
<div class="d-none">{{ form.ORDER }}</div>
<button class="btn btn-info btn-block" type="button" data-formset-move-up-button>
{% trans 'Move up' %}
</button>
</div>
<div class="row mt-1">
<button class="btn btn-info btn-block" type="button" data-formset-move-down-button>
{% trans 'Move down' %}
</button>
</div>
{% endif %}
</div>
<div class="col col-lg-2 mt-1">
{% if form.DELETE %}
<div class="d-none">{{ form.DELETE }}</div>
<button type="button" class="btn btn-danger btn-block h-100" data-formset-delete-button>
{% trans 'Delete' %}
</button>
{% endif %}
</div>
</div>
</div>
</div>
</div>
create_budget_items.html: On this template I have the javascript where I control the enable and disable states of checkboxes and input fields. I thought that by calling the script inside the for loop where the formset is being iterated I was going to be able to control the input fields of the formsets added by the user. Is only working on the formsets created on page load.
{% block dashboard_head %}
{{ formset.media }}
<script type="text/javascript">
function trackDisabled(trigger_id, ...targets) {
const checkbox = document.getElementById(trigger_id);
checkbox.addEventListener('change', e => {
console.log(e.target.checked);
{#console.log(trigger_id);#}
{#console.log(...targets);#}
if (e.target.checked === true) {
targets.forEach(x => {
const element = document.getElementById(x);
element.disabled = true;
element.checked = false;
element.value = ''
})
} else {
targets.forEach(x => document.getElementById(x).disabled = false)
}
})
}
</script>
{% endblock dashboard_head %}
{% block dashboard_content %}
<h1>Create Budget Items</h1>
<form method="post">
{% csrf_token %}
{{ project_form.project }}
<select name="budget_model" id="id_budget_model" class="form-control">
{% with value=bi_form.budget_model.value %}
{% for model in models %}
<option value="{{ model.pk }}" class="{{ model.project.pk }}"
{% if model.pk|slugify == value|slugify %}selected="selected"{% endif %}>
{{ model.budget_name }}
</option>
{% endfor %}
{% endwith %}
</select>
{% load formset_tags %}
<div id="formset" data-formset-prefix="{{ formset.prefix }}">
{{ formset.management_form }}
<div data-formset-body>
{% for form in formset %}
{% include "projects/budget_item_form.html" with form=form only %}
<script>
trackDisabled(
'{{ form.budget_item_is_chapter.auto_id }}',
'{{ form.budget_item_is_subchapter.auto_id }}',
'{{ form.budget_item_quantity.auto_id }}'
);
console.log('{{ form.budget_item_is_chapter.auto_id }}');
</script>
{{ form.errors }}
{% endfor %}
</div>
<script type="form-template" data-formset-empty-form>
{% escapescript %}
{% include "projects/budget_item_form.html" with form=formset.empty_form only %}
{% endescapescript %}
</script>
<div class="row mt-3 mr-1 ml-1">
<!-- This button will add a new form when clicked -->
<div class="col text-center">
<input class="w-75 btn btn-info" type="button"
value="{% trans 'Add another Budget Item' %}" data-formset-add>
</div>
<div class="col text-center">
<button class="w-75 btn btn-success" type="submit">
{% trans 'Create Models' %}
</button>
</div>
</div>
</div>
</form>
{% endblock dashboard_content %}
This is the javascript that finally worked out, was written by a friend.. Thank you FunkyBob!
<script>
function isChapter() {
const root = document.getElementById('formset');
const prefix = root.dataset.formsetPrefix;
console.log({root, prefix});
// listen for all input changes
root.addEventListener('change', ev => {
// check if it matches out name pattern
console.log(ev.target.name);
console.log(ev.target.checked, !ev.target.checked);
console.log(`${prefix}-(\\d+)-budget_item_is_chapter`);
let m = ev.target.name.match(RegExp(`${prefix}-(\\d+)-budget_item_is_chapter`));
// if it's not {prefix}-*-budget_item_is_chapter ignore
if (!m) return;
console.log(m);
let idx = m[1]; // the matched regex group
// Find the related fields, and set them as enabled/disabled
root.querySelector(`[name="${prefix}-${idx}-budget_item_is_subchapter"]`).disabled = ev.target.checked;
root.querySelector(`[name="${prefix}-${idx}-budget_item_is_subchapter"]`).checked = false;
root.querySelector(`[name="${prefix}-${idx}-budget_item_unit"]`).disabled = ev.target.checked;
root.querySelector(`[name="${prefix}-${idx}-budget_item_unit"]`).value = ev.target.checked;
root.querySelector(`[name="${prefix}-${idx}-budget_item_quantity"]`).disabled = ev.target.checked;
root.querySelector(`[name="${prefix}-${idx}-budget_item_quantity"]`).value = ev.target.checked;
console.log("Done!")
});
}
isChapter();
</script>

Checkbox filter array values not joining in url

I am trying to create a set of filters using checkboxes. When a box is checked, the value is added to the url and the page content filters accordingly.
As it stands, the filters and script is working, but instead of multiple values being joined in the url and content being displayed, the url is being overridden and only using one value from the checkbox array. For example, if WordPress and XL selected, only WordPress will show in the url. I have had a version of this script working but for select options with no issue, but checkboxes are proving an issue and i'm not sure what i've missed..
Can anyone point me in the right direction? : )
Shopify.queryParams = {};
if (location.search.length) {
for (var aKeyValue, i = 0, aCouples = location.search.substr(1).split('&'); i < aCouples.length; i++) {
aKeyValue = aCouples[i].split('=');
if (aKeyValue.length > 1) {
Shopify.queryParams[decodeURIComponent(aKeyValue[0])] = decodeURIComponent(aKeyValue[1]);
}
}
}
jQuery('.coll-picker').change(function() {
if (jQuery(this).val()) {
location.href = '/collections/' + jQuery(this).val();
}
else {
location.href = '/collections/all';
}
});
/* Specify the input */
var collFilters = jQuery('.coll-filter');
collFilters.change(function() {
delete Shopify.queryParams.page;
/* declare an array */
var newTags = [];
// console.log(newTags);
/* This works - if (this) is checked, push value from array : only working for one value though */
collFilters.each(function() {
//if (jQuery(this).val()) { // this works for select options
if (jQuery(this).is(':checked')) {
newTags.push(jQuery(this).val());
// var id = $(this).attr("id"); alert("Checked: " + id);
}
});
{% if collection.handle %}
var newURL = '/collections/{{ collection.handle }}';
if (newTags.length) {
newURL += '/' + newTags.join('+');
}
var search = jQuery.param(Shopify.queryParams);
if (search.length) {
newURL += '?' + search;
}
location.href = newURL;
{% else %}
if (newTags.length) {
Shopify.queryParams.constraint = newTags.join('+');
}
else {
delete Shopify.queryParams.constraint;
}
location.search = jQuery.param(Shopify.queryParams);
{% endif %}
});
<form class="lmwd-filter" method="post">
<ul class="clearfix filter-category">
<li>
<p>Category</p>
{% assign tags = 'Ecommerce, Woocommerce, WordPress, Magento 2' | split: ',' %}
{% for t in tags %}
{% assign tag = t | strip %}
<label for="{{ tag }}">
<input type="checkbox" id="{{ tag | handle }}" class="chk coll-filter" name="{{ tag | handle }}" value="{{ tag | handle }}" />
{{ tag }}
</label>
{% endfor %}
</li>
<li><br /></li>
<li>
<p>Size</p>
{% assign tags = 'XS, S, M, L, XL' | split: ',' %}
{% for t in tags %}
{% assign tag = t | strip %}
<label for="{{ tag }}">
<input type="checkbox" id="{{ tag | handle }}" class="chk coll-filter" name="{{ tag | handle }}" value="{{ tag | handle }}" />
{{ tag }}
</label>
{% endfor %}
</li>
</ul>
</form>

value gets submitted through form, then even after the value got submitted and gets displayed, in a form the value got submitted is shown

Sorry for the long title, but this is what happens:
I submit word "hello", then hello gets displayed. Then in a form, it still says "hello". I'm not sure why this is happening. Is this django problem or some javascript code is needed for this...?Here's my full code I think is causing this problem.
in my views.py
def post(request, slug):
user = get_object_or_404(User,username__iexact=request.user)
try:
profile = MyProfile.objects.get(user_id=request.user.id)
# if it's a OneToOne field, you can do:
# profile = request.user.myprofile
except MyProfile.DoesNotExist:
profile = None
post = get_object_or_404(Post, slug=slug)
post.views += 1 # increment the number of views
post.save() # and save it
path = request.get_full_path()
comments = Comment.objects.filter(path=path)
#comments = post.comment_set.all()
comment_form = CommentForm(request.POST or None)
if comment_form.is_valid():
parent_id = request.POST.get('parent_id')
parent_comment = None
if parent_id is not None:
try:
parent_comment = Comment.objects.get(id=parent_id)
except:
parent_comment = None
comment_text = comment_form.cleaned_data['comment']
new_comment = Comment.objects.create_comment(
user=MyProfile.objects.get(user=request.user),
path=request.get_full_path(),
text=comment_text,
post = post,
parent = parent_comment)
for c in comments:
c.get_children()
context_dict = {
'post' :post,
'profile' :profile,
'comments' : comments,
'comment_form':comment_form
}
return render(request, 'main/post.html', context_dict)
and in my post.html I have
<table class='table'>
{% for comment in comments %}
<tr><td>{{ comment.get_comment }}
<br/><small>via {{ comment.user }} | {{ comment.timestamp|timesince }} ago </small>
{% if not comment.is_child %}
<ul>
{% for child in comment.get_children %}
<li>{{ child.get_comment }}
<small>via {{ child.user }}</small>
</li>
{% endfor %}
</ul>
<a href='#' class='reply_btn'>Reply</a>
<div class='reply_comment'>
<form method="POST" action=''>{% csrf_token %}
<input type='hidden' name='parent_id' value='{{ comment.id }}' />
{{ comment_form.as_p }}
<input type='submit' class='btn btn-default' value='Add reply'/>
</form>
</div>
{% endif %}
</td></tr>
{% endfor %}
</table>
</div>
<div class = "col-sm-3">
</div>
{% include 'footer.html' %}
<script>
{% block jquery %}
$('.reply_btn').click(function(e){
e.preventDefault();
$(this).next(".reply_comment").fadeToggle();
// $(".reply_comment").fadeToggle();
})
{% endblock %}
</script>
{% endblock %}
Can someone please direct me where I should look.....thank you
Before you check if a form is valid or not you assign the form to include the POST data so it will still include this when you return back to the form (in case it needs to show errors). The easiest fix would be to reassign the form after your valid logic is done.
comment_form = CommentForm(request.POST or None)
if comment_form.is_valid():
.. Valid logic ..
comment_form = CommentForm()

Categories