Delete from django database with many form in same template - javascript

I am new to django and I'm trying to build a to do list
so what I click on "✓" button it turn the item to green from red using javascript
and now Iam trying to make the button "X" delete objects from the django database
so I stuck here
this is my code I am waiting for your help
my views
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import *
from .forms import *
# Create your views here.
def index(request):
tasks = Task.objects.all()
form = TaskForm()
if request.method == "POST" :
form = TaskForm(request.POST)
if form.is_valid():
form.save()
return redirect("/")
context = {
'tasks' : tasks , 'form' : form
}
return render(request,"tasks/list.html", context)
def deletetask(request, pk):
if request.method == "POST" and "delete" in request.POST:
print(request.POST)
print("good work")
item = request.POST.get(id=pk)
Task.objects.delete(id=item)
return render(request,"tasks/list.html")
my forms.py
from django import forms
from django.forms import ModelForm
from .models import *
class TaskForm(forms.ModelForm):
class Meta:
model = Task
fields = '__all__'
my models.py
from django.db import models
# Create your models here.
class Task(models.Model):
title = models.CharField(max_length=200)
complete = models.BooleanField(default=False)
creted = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
my template
<h3>Hello world from templates</h3>
<form action="/" method="POST"> {% csrf_token %}
{{form.title}}
<input type="submit" name="Ajout medoc">
</form>
{% for task in tasks %}
<div >
<form action="/" method="POST">
<p style="color: red" id="{{task.id}}">
<input type="button" name="cmd" value="✓" onclick="document.getElementById( '{{ task.id }}').style.color = 'green'">
<input type="button" name="delete" value="X" id="{{task.id}}">
{{ task }}
</p>
</form>
</div>
{% endfor %}

What i would do instead is this:
def deletetask(request, pk):
instance = Task.objects.delete(id=pk)
instance.delete()
return redirect('index')
and then in your template:
{% for task in tasks %}
<div >
<p style="color: red" id="{{task.id}}">
<input type="button" name="cmd" value="✓" onclick="document.getElementById( '{{ task.id }}').style.color = 'green'">
<a href="{% url 'delete_item' task.id %}">
<button>X</button>
</a>
{{ task }}
</p>
</div>
{% endfor %}
In your urls.py:
urlpatterns = [
path("delete_item/", views.delete_item, name="delete_item"),
]
The code in the template is calling a function from a "a" html tag instead of using a form.

Related

I want to add custom countdown timer in my project where admin/teacher set time for exam,that time becomes input for timer

i tried creating timer in python but its not being as i wanted so i guess javascript is only going
to help and im not very good in javascript do please help me to create a timer and page should close when timer runs out of time
'THIS IS : models.py'
from django.db import models
from student.models import Student
class Course(models.Model):
course_name = models.CharField(max_length=50)
question_number = models.PositiveIntegerField()
total_marks = models.PositiveIntegerField()
time_to_solve = models.IntegerField()
required_marks_to_pass = models.IntegerField()
def __str__(self):
return self.course_name
class Question(models.Model):
course=models.ForeignKey(Course,on_delete=models.CASCADE)
marks=models.PositiveIntegerField()
question=models.CharField(max_length=600)
option1=models.CharField(max_length=200)
option2=models.CharField(max_length=200)
option3=models.CharField(max_length=200)
option4=models.CharField(max_length=200)
cat=(('Option1','Option1'),('Option2','Option2'),('Option3','Option3'),('Option4','Option4'))
answer=models.CharField(max_length=200,choices=cat)
class Result(models.Model):
student = models.ForeignKey(Student,on_delete=models.CASCADE)
exam = models.ForeignKey(Course,on_delete=models.CASCADE)
marks = models.PositiveIntegerField()
date = models.DateTimeField(auto_now=True)
'THIS IS HTML TEMPLATE WHERE COUNTDOWN TIMER SHOULD APPEAR '
{% extends 'student/studentbase.html' %}
{% block content %}
{%load static%}
{% block scripts %}
<script src="{% static 'quiz.js' %}" defer></script>
{% endblock scripts %}
<head>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
{% comment %} <script src="//code.jquery.com/jquery-1.11.1.min.js"></script> {% endcomment %}
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</head>
<div class="jumbotron my-4">
<form class="form" autocomplete="off" onsubmit="return saveAns()" action="/student/calculate-marks" method="POST">
{% csrf_token %}
<h2 style="text-align: left;">Course: {{course.course_name}}</h2>
<h2 style="text-align: right;">Countdown: </h2>
{% comment %} <h2 id="timer-box" style="text-align: right;">Time: {{5:00}} min</h2> {% endcomment %}
<h1 style="text-align: right;"><span id = "time">00:00</span></h1>
{% for q in questions%}
<h3 class="text-danger">{{ forloop.counter }}. {{q.question}}</h3><h4 style="text-align: right;">[{{q.marks}} Marks]</h4>
<input type="hidden" name="csrfmiddlewaretoken" value="C24rUotmdHawVQJL3KrqiWxvti8UffOFYUc8TRbZtLt36AVLdP3jbkzUVe3beRAa">
<div class="form-check mx-4">
<input class="form-check-input" type="radio" name="{{ forloop.counter }}" id="{{q.option1}}" value="Option1">
<label class="form-check-label" for="option1">
{{q.option1}}
</label>
</div>
<div class="form-check mx-4">
<input class="form-check-input" type="radio" name="{{ forloop.counter }}" id="{{q.option2}}" value="Option2">
<label class="form-check-label" for="option2">
{{q.option2}}
</label>
</div>
<div class="form-check mx-4">
<input class="form-check-input" type="radio" name="{{ forloop.counter }}" id="{{q.option3}}" value="Option3">
<label class="form-check-label" for="option3">
{{q.option3}}
</label>
</div>
<div class="form-check mx-4">
<input class="form-check-input" type="radio" name="{{ forloop.counter }}" id="{{q.option4}}" value="Option4">
<label class="form-check-label" for="option4">
{{q.option4}}
</label>
</div>
{% endfor %}
<input class="btn btn-success btn-lg" style="border-radius: 0%;" type="submit" value="Submit Answers">
</form>
</div>
<script>
function saveAns(){
var ele = document.getElementsByTagName('input');
for(i = 0; i < ele.length; i++) {
if(ele[i].type="radio") {
if(ele[i].checked){
setCookie(ele[i].name,ele[i].value,3)
}
}
}
}
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
</script>
<br><br><br><br><br><br>
{% endblock content %}
'THIS IS VIEWS.PY'
from django.shortcuts import render,redirect,reverse
from . import forms,models
from django.db.models import Sum
from django.contrib.auth.models import Group
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required,user_passes_test
from django.conf import settings
from datetime import date, timedelta
from django.db.models import Q
from django.core.mail import send_mail
from teacher import models as TMODEL
from student import models as SMODEL
from teacher import forms as TFORM
from student import forms as SFORM
from django.contrib.auth.models import User
def home_view(request):
if request.user.is_authenticated:
return HttpResponseRedirect('afterlogin')
return render(request,'exam/index.html')
def is_teacher(user):
return user.groups.filter(name='TEACHER').exists()
def is_student(user):
return user.groups.filter(name='STUDENT').exists()
def afterlogin_view(request):
if is_student(request.user):
return redirect('student/student-dashboard')
elif is_teacher(request.user):
accountapproval=TMODEL.Teacher.objects.all().filter(user_id=request.user.id,status=True)
if accountapproval:
return redirect('teacher/teacher-dashboard')
else:
return render(request,'teacher/teacher_wait_for_approval.html')
else:
return redirect('admin-dashboard')
def adminclick_view(request):
if request.user.is_authenticated:
return HttpResponseRedirect('afterlogin')
return HttpResponseRedirect('adminlogin')
#login_required(login_url='adminlogin')
def admin_dashboard_view(request):
dict={
'total_student':SMODEL.Student.objects.all().count(),
'total_teacher':TMODEL.Teacher.objects.all().filter(status=True).count(),
'total_course':models.Course.objects.all().count(),
'total_question':models.Question.objects.all().count(),
}
return render(request,'exam/admin_dashboard.html',context=dict)
#login_required(login_url='adminlogin')
def admin_teacher_view(request):
dict={
'total_teacher':TMODEL.Teacher.objects.all().filter(status=True).count(),
'pending_teacher':TMODEL.Teacher.objects.all().filter(status=False).count(),
'salary':TMODEL.Teacher.objects.all().filter(status=True).aggregate(Sum('salary'))['salary__sum'],
}
return render(request,'exam/admin_teacher.html',context=dict)
#login_required(login_url='adminlogin')
def admin_view_teacher_view(request):
teachers= TMODEL.Teacher.objects.all().filter(status=True)
return render(request,'exam/admin_view_teacher.html',{'teachers':teachers})
#login_required(login_url='adminlogin')
def update_teacher_view(request,pk):
teacher=TMODEL.Teacher.objects.get(id=pk)
user=TMODEL.User.objects.get(id=teacher.user_id)
userForm=TFORM.TeacherUserForm(instance=user)
teacherForm=TFORM.TeacherForm(request.FILES,instance=teacher)
mydict={'userForm':userForm,'teacherForm':teacherForm}
if request.method=='POST':
userForm=TFORM.TeacherUserForm(request.POST,instance=user)
teacherForm=TFORM.TeacherForm(request.POST,request.FILES,instance=teacher)
if userForm.is_valid() and teacherForm.is_valid():
user=userForm.save()
user.set_password(user.password)
user.save()
teacherForm.save()
return redirect('admin-view-teacher')
return render(request,'exam/update_teacher.html',context=mydict)
#login_required(login_url='adminlogin')
def delete_teacher_view(request,pk):
teacher=TMODEL.Teacher.objects.get(id=pk)
user=User.objects.get(id=teacher.user_id)
user.delete()
teacher.delete()
return HttpResponseRedirect('/admin-view-teacher')
#login_required(login_url='adminlogin')
def admin_view_pending_teacher_view(request):
teachers= TMODEL.Teacher.objects.all().filter(status=False)
return render(request,'exam/admin_view_pending_teacher.html',{'teachers':teachers})
#login_required(login_url='adminlogin')
def approve_teacher_view(request,pk):
teacherSalary=forms.TeacherSalaryForm()
if request.method=='POST':
teacherSalary=forms.TeacherSalaryForm(request.POST)
if teacherSalary.is_valid():
teacher=TMODEL.Teacher.objects.get(id=pk)
teacher.salary=teacherSalary.cleaned_data['salary']
teacher.status=True
teacher.save()
else:
print("form is invalid")
return HttpResponseRedirect('/admin-view-pending-teacher')
return render(request,'exam/salary_form.html',{'teacherSalary':teacherSalary})
#login_required(login_url='adminlogin')
def reject_teacher_view(request,pk):
teacher=TMODEL.Teacher.objects.get(id=pk)
user=User.objects.get(id=teacher.user_id)
user.delete()
teacher.delete()
return HttpResponseRedirect('/admin-view-pending-teacher')
#login_required(login_url='adminlogin')
def admin_view_teacher_salary_view(request):
teachers= TMODEL.Teacher.objects.all().filter(status=True)
return render(request,'exam/admin_view_teacher_salary.html',{'teachers':teachers})
#login_required(login_url='adminlogin')
def admin_student_view(request):
dict={
'total_student':SMODEL.Student.objects.all().count(),
}
return render(request,'exam/admin_student.html',context=dict)
#login_required(login_url='adminlogin')
def admin_view_student_view(request):
students= SMODEL.Student.objects.all()
return render(request,'exam/admin_view_student.html',{'students':students})
#login_required(login_url='adminlogin')
def update_student_view(request,pk):
student=SMODEL.Student.objects.get(id=pk)
user=SMODEL.User.objects.get(id=student.user_id)
userForm=SFORM.StudentUserForm(instance=user)
studentForm=SFORM.StudentForm(request.FILES,instance=student)
mydict={'userForm':userForm,'studentForm':studentForm}
if request.method=='POST':
userForm=SFORM.StudentUserForm(request.POST,instance=user)
studentForm=SFORM.StudentForm(request.POST,request.FILES,instance=student)
if userForm.is_valid() and studentForm.is_valid():
user=userForm.save()
user.set_password(user.password)
user.save()
studentForm.save()
return redirect('admin-view-student')
return render(request,'exam/update_student.html',context=mydict)
#login_required(login_url='adminlogin')
def delete_student_view(request,pk):
student=SMODEL.Student.objects.get(id=pk)
user=User.objects.get(id=student.user_id)
user.delete()
student.delete()
return HttpResponseRedirect('/admin-view-student')
#login_required(login_url='adminlogin')
def admin_course_view(request):
return render(request,'exam/admin_course.html')
#login_required(login_url='adminlogin')
def admin_add_course_view(request):
courseForm=forms.CourseForm()
if request.method=='POST':
courseForm=forms.CourseForm(request.POST)
if courseForm.is_valid():
courseForm.save()
else:
print("form is invalid")
return HttpResponseRedirect('/admin-view-course')
return render(request,'exam/admin_add_course.html',{'courseForm':courseForm})
#login_required(login_url='adminlogin')
def admin_view_course_view(request):
courses = models.Course.objects.all()
return render(request,'exam/admin_view_course.html',{'courses':courses})
#login_required(login_url='adminlogin')
def delete_course_view(request,pk):
course=models.Course.objects.get(id=pk)
course.delete()
return HttpResponseRedirect('/admin-view-course')
#login_required(login_url='adminlogin')
def admin_question_view(request):
return render(request,'exam/admin_question.html')
#login_required(login_url='adminlogin')
def admin_add_question_view(request):
questionForm=forms.QuestionForm()
if request.method=='POST':
questionForm=forms.QuestionForm(request.POST)
if questionForm.is_valid():
question=questionForm.save(commit=False)
course=models.Course.objects.get(id=request.POST.get('courseID'))
question.course=course
question.save()
else:
print("form is invalid")
return HttpResponseRedirect('/admin-view-question')
return render(request,'exam/admin_add_question.html',{'questionForm':questionForm})
#login_required(login_url='adminlogin')
def admin_view_question_view(request):
courses= models.Course.objects.all()
return render(request,'exam/admin_view_question.html',{'courses':courses})
#login_required(login_url='adminlogin')
def view_question_view(request,pk):
questions=models.Question.objects.all().filter(course_id=pk)
return render(request,'exam/view_question.html',{'questions':questions})
#login_required(login_url='adminlogin')
def delete_question_view(request,pk):
question=models.Question.objects.get(id=pk)
question.delete()
return HttpResponseRedirect('/admin-view-question')
#login_required(login_url='adminlogin')
def admin_view_student_marks_view(request):
students= SMODEL.Student.objects.all()
return render(request,'exam/admin_view_student_marks.html',{'students':students})
#login_required(login_url='adminlogin')
def admin_view_marks_view(request,pk):
courses = models.Course.objects.all()
response = render(request,'exam/admin_view_marks.html',{'courses':courses})
response.set_cookie('student_id',str(pk))
return response
#login_required(login_url='adminlogin')
def admin_check_marks_view(request,pk):
course = models.Course.objects.get(id=pk)
student_id = request.COOKIES.get('student_id')
student= SMODEL.Student.objects.get(id=student_id)
results= models.Result.objects.all().filter(exam=course).filter(student=student)
return render(request,'exam/admin_check_marks.html',{'results':results})
def aboutus_view(request):
return render(request,'exam/aboutus.html')
def contactus_view(request):
sub = forms.ContactusForm()
if request.method == 'POST':
sub = forms.ContactusForm(request.POST)
if sub.is_valid():
email = sub.cleaned_data['Email']
name=sub.cleaned_data['Name']
message = sub.cleaned_data['Message']
send_mail(str(name)+' || '+str(email),message,settings.EMAIL_HOST_USER, settings.EMAIL_RECEIVING_USER, fail_silently = False)
return render(request, 'exam/contactussuccess.html')
return render(request, 'exam/contactus.html', {'form':sub})

How to access foreign key in a django template? (ListView)

In my project, the Profile model has Foreign Key relation with Education instance. Here are my models:
class Profile(models.Model):
user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, null=True, blank=True)
full_name = models.CharField(max_length=30, null=True, blank=True)
education = models.ForeignKey(Education, on_delete=models.SET_NULL, null=True, blank=True, related_name="education")
class Education(models.Model):
degree = models.CharField(max_length=100, null=True, blank=True)
school = models.CharField(max_length=100, null=True, blank=True)
edu_start_date = models.DateField(null=True, blank=True)
edu_end_date = models.DateField(null=True, blank=True)
def __str__(self):
return str(self.degree)
Now, using the Django ListView, I am not being able to display the data of foreign key. My views:
class EducationView(CreateView):
form_class = EducationForm
pk_url_kwarg = 'pk'
template_name = "profile_settings.html"
class EducationList(ListView):
model = Profile
queryset = Profile.objects.all()
context_object_name = 'object'
pk_url_kwarg = 'pk'
template_name = "profile_settings.html"
Template
{% for obj in profile.education.all %}
<div class="col-lg-12">
<h2>{{ obj.degree }}</h2>
<br>
<div>
{{ obj.school }}
</div>
</div>
<br>
{% endfor %}
Education form saves data to the database but I couldn't fetch it using the template code.
Note: I'm using single template for CreateView and ListView.
In ListView you specified context_object_name as 'object'. So inside the template, the context is referred to an object.
So the code look like
{% for each_profile in object %}
{% for obj in each_profile.education.all %}
<div class="col-lg-12">
<h2>{{ obj.degree }}</h2>
<br>
<div>
{{ obj.school }}
</div>
</div>
<br>
{% endfor %}
{% endfor %}
You need to do it like this:
{% for obj in object %} <!-- as your context_object_name is `object` -->
<div class="col-lg-12">
<h2>{{ obj.education.degree }}</h2> <!-- accessed foreign key -->
<br>
<div>
{{ obj.education.school }} <!-- accessed foreign key -->
</div>
</div>
<br>
{% endfor %}
Update
If you are using this template in create view then update the View like this:
class EducationView(CreateView):
form_class = EducationForm
pk_url_kwarg = 'pk'
template_name = "profile_settings.html"
def get_context_data(self, **kwargs):
context = super(EducationView, self).get_context_data(**kwargs)
context['profiles'] = Profile.objects.all() # I don't want to mix up `object` here. so using profiles
return context
Now in ListView and template, we are going to update context object as well:
# view
class EducationList(ListView):
model = Profile
queryset = Profile.objects.all()
context_object_name = 'profiles'
template_name = "profile_settings.html"
# template
{% for obj in profiles %}
<div class="col-lg-12">
<h2>{{ obj.degree }}</h2>
<br>
<div>
{{ obj.school }}
</div>
</div>
<br>
{% endfor %}

How can I put json's data to form?

I wanna put json's data to form.I wrote in index.html
{% load staticfiles %}
<html lang="ja">
<head>
<meta charset="utf-8">
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<script src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<main>
<form class="form-horizontal" action="/accounts/regist_save/" method="POST">
 

 
<label for="id_email">Email</label>

 {{ regist_form.email }} 
 
{% include 'registration/sex.html' %}
<button type="submit" class="regist">REGIST</button>
<input name="next" type="hidden"/>
{% csrf_token %}
</form>
</main>
</body>
</html>
in forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.forms import AuthenticationForm
from .models import User
from .models import NewUser
class RegisterForm(UserCreationForm):
class Meta:
model = User
fields = ('email',)
def __init__(self, *args, **kwargs):
super(RegisterForm, self).__init__(*args, **kwargs)
self.fields['email'].widget.attrs['class'] = 'form-control'
class ProfileForm(forms.ModelForm):
class Meta:
model = NewUser
fields = (
"sex"
)
in models.py
#coding:utf-8
from django.db import models
from django.contrib.auth.models import User
class NewUser(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
sex = models.CharField(max_length=100,null=True, blank=True, default=None)
in sex.html
<form class="form-horizontal" method="post" action="#">
<div class="form-group-lg">
<label for="sex">SEX</label>
<select class="form-control sex" name="sex">
<option value="">--</option>
<option value="male">MAN</option>
<option value="female">FEMALE</option>
</select>
</div>
 
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function showSex() {
var num = document.forms[0].sex.selectedIndex;
var sex = document.forms[0].sex.options[num].value;
console.log(sex);
}
document.addEventListener("DOMContentLoaded", showSex);
for (var i = 0, e = document.querySelectorAll(".form-horizontal select"); i < e.length; i++) {
e[i].addEventListener("change", showSex);
}
</script>
Now REGIST button cannot be sent,so I cannot regist these data.Why does such thing happen?I wanna put var sex data to regist in form.How should I fix this?
how can i sent js data to python?is it impossible?I think I should convert javascript data to python one,but I cannot understand how to do it.

AJAX update list of object

Can someone help me and say whats wrong I did?
In my django project I have product_detail page which has comment part. I am tring to update comments list after successfully adding new comment with AJAX. Unfortunatly it updates all page. I am little bit comfused and need advice. I need to update only list of comments not all page.
product_detail.html:
<div class="card">
<div class="card-block">
<table id="comment-table">
<thead>
<tr>
<th>Author</th>
<th>Date</th>
<th>Comment Text</th>
</tr>
</thead>
<tbody>
{% include 'project/comment_list.html' %}
</tbody>
</table>
</div>
<div class="card-footer">
<form method="post" class="comment-form" id="comment-form" action="{% url 'project:comment_add' project_code=project.code product_code=product.code %}">
{% csrf_token %}
{% for field in form %}
<div class="form-group{% if field.errors %} has-error{% endif %}">
{% render_field field class="form-control" %}
{% for error in field.errors %}
<p class="help-block">{{ error }}</p>
{% endfor %}
</div>
{% endfor %}
<button type="submit" class="btn btn-primary">Send</button>
</form>
</div>
</div>
views.py:
def comment_add(request, project_code, product_code):
data = dict()
project = get_object_or_404(Project, pk=project_code, status='open')
product = get_object_or_404(Product, pk=product_code)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.author = request.user
comment.save()
product.comments.add(comment)
data['form_is_valid'] = True
data['html_comment'] = render_to_string('project/comment_list.html', {'product': product})
form = CommentForm()
else:
data['form_is_valid'] = False
else:
form = CommentForm()
context = {'project': project, 'product': product, 'form': form}
return render(request, 'project/product_detail.html', context)
js:
$(function () {
var saveForm = function () {
var form = $(this);
$.ajax({
url: form.attr("action"),
data: form.serialize(),
type: form.attr("method"),
dataType: 'json',
success: function (data) {
if (data.form_is_valid) {
$("#comment-table tbody").html(data.html_comment);
}
else {
$("#comment-form").html(data.html_comment_form);
}
}
});
return false;
};
$("#comment-form").on("submit", ".comment-form", saveForm);
});
The problem is type="submit" native refresh new page. You have to stop form submitting. Try something like this:
$("#comment-form").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
// here your ajax code
});

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