I have been working on a like system using django and ajax, this like system is very similar to instagram's one. After finishing with the code I started to get a Post matching query does not exist error which has been a pain. I dont see the wrong in my code but I think the problem is on the views.py file because the traceback is triggering a line there. How can i fix this error?
models.py
class Post(models.Model):
text = models.CharField(max_length=200)
user = models.ForeignKey(User, on_delete=models.CASCADE, default='username')
liked = models.ManyToManyField(User, default=None, blank=True, related_name='liked')
def __str__(self):
return str(self.id)
views.py (upload view uploades the form, home displays the uploaded form, like_post is the view in charged of liking and unliking posts and home_serialized os the one that contains the json so that the page doesnt reload when the like button is clicked)
def upload(request):
print("toro")
if request.method == 'POST':
print("caballo")
form = PostForm(request.POST)
if form.is_valid():
instance = form.save(commit=False)
instance.user = request.user
instance.save()
return redirect('home')
print('succesfully uploded')
else:
form = PostForm()
print('didnt upload')
return render(request, 'home.html', {'form': form})
def home(request):
contents = Post.objects.all()
args = {
'contents': contents,
}
return render(request, 'home.html', args)
def like_post(request):
user = request.user
if request.method == 'POST':
pk = request.POST.get('post_pk')
post_obj = Post.objects.get(pk=pk)
if user in post_obj.liked.all():
post_obj.liked.remove(user)
else:
post_obj.liked.add(user)
return HttpResponse()
def home_serialized(request):
data = list(Post.objects.values())
return JsonResponse(data, safe=False)
urls.py
urlpatterns = [
path('', views.home, name='home'),
path('upload', views.upload, name='upload'),
path('like/', views.like_post, name='like-post'),
path('serialized/', views.home_serialized, name='serialized-view'),
]
home.html
<form method='post' action="{% url 'upload' %}">
{% csrf_token %}
<input type="text" name="text" placeholder="Add a comment..." required="" id="id_text">
<button class="submit-button" type="submit">Save</button>
</form>
{% for content in contents %}
{% if content %}
<ul class="list-group">
<li class="list-group-item">{{ content.text }}</li>
<form action="{% url 'like-post' %}" class='like-form' method="POST" id={{content.id}}>
{% csrf_token %}
<input type='hidden' name="post_ok" value="{{ content.ok }}">
<button class='like-btn{{ content.id }}'>
{% if request.user in content.liked.all %}
Unlike
{% else %}
Like
{% endif %}
</button>
</form>
<strong>{{ content.liked.all.count }}</strong>
</ul>
{% endif %}
{% endfor %}
<script type='text/javascript'>
$(document).ready(function(){
$('.like-form').submit(function(e){
e.preventDefault()
console.log('works')
const post_id = $(this).attr('id')
console.log(this)
console.log(post_id)
const likeText = $(`.like-btn${post_id}`).text()
console.log(likeText)
const trim = $.trim(likeText)
console.log(trim)
const url = $('.like-form').attr('action')
console.log(url)
$.ajax({
type: 'POST',
url: url,
data : {
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(),
'post_pk': post_id,
},
success: function(error){
console.log('success')
$.ajax({
type: 'GET',
url: 'http://127.0.0.1:8000/serialized/',
success: function(response){
console.log(response)
$.each(response, function(index, element){
console.log(index)
console.log(element.content)
if (post_id == element.id) {
if(trim == 'Like') {
console.log('unlike')
$(`.like-btn${post_id}`).html('Unlike')
} else if (trim == 'Unlike') {
console.log('like')
$(`.like-btn${post_id}`).html('Like')
} else {
console.log('ups')
}
}
})
},
error: function(error){
console.log('error')
}
})
},
error: function(error){
console.log('error', error)
}
})
})
});
</script>
traceback
Traceback (most recent call last):
File "C:\Users\MaríaPaola\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\MaríaPaola\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\MaríaPaola\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\MaríaPaola\projects\nwpc\like\views.py", line 65, in like_post
post_obj = Post.objects.get(pk=pk).exists()
File "C:\Users\MaríaPaola\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\MaríaPaola\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py", line 415, in get
raise self.model.DoesNotExist(
like.models.Post.DoesNotExist: Post matching query does not exist.
I'm not sure what it says in the traceback. If you could provide that, maybe it'll make more sense. But I assume it's because of the like post_obj = Post.objects.get(pk=pk) in
def like_post(request) function.
Post with the given primary key does not exist. What you can do is to check if the pk exists.
if Post.objects.filter(pk=pk).exists():
# it exist
or you can do a try except method
try:
post_obj = Post.objects.get(pk=pk)
if user in post_obj.liked.all():
post_obj.liked.remove(user)
else:
post_obj.liked.add(user)
except:
# what happens if post does not exist
Related
detail.html
{% if request.user.is_authenticated %}
<form class="like-forms d-inline" data-book-id="{{ book.pk }}" data-review-id="{{ review.pk }}">
{% csrf_token %}
<h4>
{% if request.user in review.like_users.all %}
<button type="submit" id="btn-like-{{ review.pk }}" class="btn-none bi bi-emoji-heart-eyes"></button>
{% else %}
<button type="submit" id="btn-like-{{ review.pk }}" class="btn-none bi bi-emoji-angry"></button>
{% endif %}
</h4>
</form>
{% endif %}
<!-js-->
<script>
const likeForms = document.querySelectorAll('.like-forms')
const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value
likeForms.forEach((form) => {
form.addEventListener('submit', function (event) {
event.preventDefault()
const reviewId = event.target.dataset.reviewId
const bookId = event.target.dataset.bookId
axios({
method: 'post',
url: `/detail/${bookId}/like/${reviewId}/`,
headers: {'X-CSRFToken': csrfToken},
})
.then(response => {
const isLiked = response.data.isLiked
const likeBtn = document.querySelector(`#btn-like-${reviewId}`)
console.log(isLiked)
if (isLiked === true) {
likeBtn.classList.add('bi-emoji-heart-eyes')
likeBtn.classList.remove('bi-emoji-angry')
} else {
likeBtn.classList.add('bi-emoji-angry')
likeBtn.classList.remove('bi-emoji-heart-eyes')
}
})
.catch(error => {
console.log(error)
})
})
})
</script>
urls.py
path("detail/<int:book_pk>", views.detail, name="detail"),
path("detail/<int:book_pk>/like/<int:review_pk>", views.like, name="like"),
.....
views.py
def detail(request, book_pk):
reviews = Review.objects.order_by("-pk")
book = Book.objects.get(pk=book_pk)
context = {
"reviews": reviews,
"book": book,
}
return render(request, "review/detail.html", context)
def like(request, book_pk, review_pk):
review = Review.objects.get(pk=review_pk)
book = Book.objects.get(pk=book_pk)
if review.like_users.filter(pk=request.user.pk).exists():
review.like_users.remove(request.user)
is_liked = False
else:
review.like_users.add(request.user)
is_liked = True
data = {
"isLiked": is_liked,
}
return JsonResponse(data)
I got a 404 not found error while writing code for a "like" async function.
data-book-id="{{ book.pk }}" data-review-id="{{ review.pk }} in the form
I seem to get pk values for books and book reviews, but I don't know what causes the 404 error.
Console error message : POST http://localhost:8000/detail/1/like/2/ 404 (Not Found)
I am running this on localhost (http://localhost:8000/)
Thanks for reading..!
I am trying to pass the values of form data through ajax .And getting method not allowed error. I am trying to add comment in a blog post.
This is my form which is inside blog_detail page
<form id="commentform" class="commentform" method="post">
{% csrf_token %}
{%with allcomments.count as total_comments%}
<p>
{{total_comments}} comment{{total_comments|pluralize}}
</p>
{%endwith%}
<select name="blog" class="d-none" id="id_blog">
<option value="{{blog.id}}" selected="{{blog.id}}"></option>
</select>
<label class="small font-weight-bold">{{comment_form.parent.label}}</label>
{{comment_form.parent}}
<div class="d-flex">
<img class="avatar_comment align-self-center" src="{% for data in avatar%}{{data.avatar.url}}{%endfor%}" alt="">
{{comment_form.content}}
</div>
<div class="d-flex flex-row-reverse">
<button value="commentform" id="newcomment" type="submit" class="newcomment btn btn-primary">Submit</button>
</div>
</form>
And when I click the button it should call the ajax
$(document).on('click','#newcomment',function(e){
e.preventDefault();
var button =$(this).attr("value");
var placement = "commentform"
if (button=="newcommentform"){
var placement = "newcommentform"
}
$.ajax({
type: 'POST',
url: '{% url "website:addcomment" %}',
data: $("#" + button).serialize(),
cache: false,
sucess: function(json){
console.log(json)
$('<div id="" class="my-2 p-2" style="border: 1px solid grey"> \
<div class="d-flex justify-content-between">By ' + json['user'] + '<div></div>Posted: Just now!</div> \
<div>' + json['result'] + '</div> \
<hr> \
</div>').insertBefore('#' + placement);
},
error: function(xhr,errmsg,err){
}
});
})
This is my urls.py
path('blog/<int:blog_id>', BlogDetails.as_view(), name="blog_detail"),
path('addcomment/',addcomment, name="addcomment"),
and my views.py is:
class BlogDetails(View):
def get(self, request, blog_id):
query = request.GET.get('query')
if query:
return redirect(reverse('website:search') + '?query=' + query)
blog = Blog.objects.get(id=blog_id)
total_comment = Comment.objects.filter(blog=blog).count()
allcomments = blog.comments.filter(status=True)
blog_list = Blog.objects.all()
comment_form = NewCommentForm()
data = {
'blog': blog,
'blog_list': blog_list,
'total_comment': total_comment,
'comment_form': comment_form,
'allcomments': allcomments
}
return render(request, "blog_detail.html", data)
def addcomment(request):
if request.method == 'post':
comment_form = NewCommentForm(request.POST)
print(comment_form)
if comment_form.is_valid():
user_comment = comment_form.save(commit=False)
user_comment.user = request.user
user_comment.save()
result = comment_form.cleaned_data.get('content')
user = request.user.username
return JsonResponse({'result': result, 'user': user})
Please help me with this it is not calling addcomment view
If how I've interpreted your code is correct, it would probably work if changed your BlogDetails class to this:
class BlogDetails(View):
def get(self, request, blog_id):
query = request.GET.get('query')
if query:
return redirect(reverse('website:search') + '?query=' + query)
blog = Blog.objects.get(id=blog_id)
total_comment = Comment.objects.filter(blog=blog).count()
allcomments = blog.comments.filter(status=True)
blog_list = Blog.objects.all()
comment_form = NewCommentForm()
data = {
'blog': blog,
'blog_list': blog_list,
'total_comment': total_comment,
'comment_form': comment_form,
'allcomments': allcomments
}
return render(request, "blog_detail.html", data)
def post(self, request, *args, **kwargs):
return self.addcomment(request)
def addcomment(self, request):
comment_form = NewCommentForm(request.POST)
print(comment_form)
if comment_form.is_valid():
user_comment = comment_form.save(commit=False)
user_comment.user = request.user
user_comment.save()
result = comment_form.cleaned_data.get('content')
user = request.user.username
return JsonResponse({'result': result, 'user': user})
Because you are trying to POST to a view that doesn't have a post method defined.
Then you would need to remove addcomment from the URL you are calling and just post to whatever URL you are currently at.
I am new to Django and Javascript - I am making a project that has posts on a site, and I want to create a 'like' button on each post. So far here is my code - I am not getting any errors at all. No console errors in the browser either. But nothing happens. When you click the heart image, if it is liked, it should be a red image. When it is not liked, it is the white heart image. Currently when I click the image, it just stays white. It is always defaulting to that white image. The code doesn't work. Any help is appreciated.
views.py for the like button:
#csrf_exempt
def like(request):
if request.method == "POST":
post_id = request.POST.get('id')
is_liked = request.POST.get('is_liked')
try:
post = Post.objects.get(id=post_id)
if is_liked == 'no':
post.like.add(request.user)
is_liked = 'yes'
elif is_liked == 'yes':
post.like.remove(request.user)
is_liked = 'no'
post.save()
return JsonResponse({'like_count': post.like.count(), 'is_liked': is_liked,
"status": 201})
except:
return JsonResponse({'error': "Post not found", "status": 404})
return JsonResponse({}, status=400)
views.py for the page to show all the posts:
def index(request):
list_of_posts = Post.objects.all().order_by('id').reverse()
paginator = Paginator(list_of_posts, 10)
page_number = request.GET.get('page', 1)
page_obj = paginator.get_page(page_number)
return render(request, "network/index.html", {
"list_of_posts": list_of_posts,
"page_obj": page_obj
})
Javascript file:
like = document.querySelectorAll(".liked");
edit = document.querySelectorAll(".edit");
text_area = document.querySelectorAll(".textarea");
like.forEach((element) => {
like_handeler(element);
});
function like_handeler(element) {
element.addEventListener("click", () => {
id = element.getAttribute("data-id");
is_liked = element.getAttribute("data-is_liked");
icon = document.querySelector(`#post-like-${id}`);
count = document.querySelector(`#post-count-${id}`);
form = new FormData();
form.append("id", id);
form.append("is_liked", is_liked);
fetch("/like/", {
method: "POST",
body: form,
})
.then((res) => res.json())
.then((res) => {
if (res.status == 201) {
if (res.is_liked === "yes") {
icon.src = "https://img.icons8.com/plasticine/100/000000/like.png";
element.setAttribute("data-is_liked", "yes");
} else {
icon.src =
"https://img.icons8.com/carbon-copy/100/000000/like--v2.png";
element.setAttribute("data-is_liked", "no");
}
count.textContent = res.like_count;
}
})
.catch(function (res) {
alert("Network Error. Please Check your connection.");
});
});
}
html file for each post: index.html:
{% extends "network/layout.html" %}
{% load static %}
{% block body %}
<h3> Welcome. Here is your news feed: </h3>
{% for i in page_obj %}
<div class='card mb-3' style="max-width: 530px;" id="card-posts">
<div class="row no-gutters">
<div class="col-md-8">
<div class="card-body">
<h5 class="card-title"><a href="{% url 'profile' username=i.username
%}">{{i.username}}</a></h5>
<p class="card-text">{{i.text}}</p>
<div class="like mt-3">
<img
data-id="{{i.id}}"
id="post-like-{{i.id}}"
class="liked"
{% if not request.user in i.like.all %}
data-is_liked="no"
src="https://img.icons8.com/carbon-copy/100/000000/like--v2.png"
{%else%}
data-is_liked="yes"
src="https://img.icons8.com/plasticine/100/000000/like.png"
{%endif%}
/>
<span id="post-count-{{post.id}}">{{i.like.count}}</span>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
{% block script %}
<script src="{% static 'network/network.js'%}"></script>
{% endblock %}
When I click the 'like' heart button on the page this is what I get. Each instance of 2, happens when I click it once. So this image is from clicking the heart button 3 times:
I'm working on an assignment to use the fetch API to do some of the normal things we would have Python do in our views with JavaScript such as adding records or querying the database. One issue I'm running across is passing the normal properties we would see in Django, say a user or username, where it just shows up as a literal user id when I pull it from the sql database with the fetch API. With the views, html and JavaScript I have written now, how would I go about pulling the username with fetch in JavaScript that I can normally grab with a variable or view with a print statement in the Django console, instead of just viewing the user id from the database. I feel like I'm missing a step and I'm just not seeing it.
urls
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"),
# API Routes
path("addpost", views.post, name="post"),
path("<str:navbar_item>", views.viewposts, name="viewposts"),
]
models.py
class User(AbstractUser):
pass
class Profile(models.Model):
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
bio = models.TextField(null=True, blank=True)
# pics
website = models.CharField(max_length=225, null=True, blank=True)
follower = models.ManyToManyField(
User, blank=True, related_name="followed_user") # user following this profile
# profile user that follows this profile
following = models.ManyToManyField(
User, blank=True, related_name="following_user")
def __str__(self):
return f"{self.user}'s' profile id is {self.id}"
def following_users(self):
for username in self.following:
return username
def get_absolute_url(self):
return reverse("network:profile-detail", args=[str(self.id)])
class Post(models.Model):
created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name="post_user")
body = models.TextField(max_length=1000)
timestamp = models.DateTimeField(auto_now_add=True)
likes = models.ManyToManyField(User, blank=True, related_name="post_likes")
def __str__(self):
return f"{self.created_by} posted {self.body}"
def get_absolute_url(self):
return reverse("network:post-detail", args=[str(self.id)])
def total_likes(self):
return self.likes.count()
class Meta:
ordering = ["-timestamp"]
views.py
def index(request):
if request.user.is_authenticated:
return render(request, "network/index.html", {})
else:
return HttpResponseRedirect(reverse("network:login"))
#login_required
def post(request):
# Composing a new post must be done via POST
if request.method != "POST":
return JsonResponse({"error": "You must POST your request."}, status=404)
try:
data = json.loads(request.body)
body = data.get("body", "")
user = request.user
print(user)
post = Post(created_by=user, body=body)
# post = Post(created_by=Profile.objects.get(user=user), body=body)
post.save()
except AttributeError:
return JsonResponse({"error": "AttributeError thrown."}, status=500)
return JsonResponse({"message": "Post created."}, status=201)
#login_required
def viewposts(request, navbar_item):
if navbar_item == "viewposts":
posts = Post.objects.all()
posts = posts.order_by("-timestamp")
json_post = serialize("json", posts)
print(posts)
return HttpResponse(json_post, content_type="application/json")
else:
return JsonResponse({"error": "Invalid page."}, status=400)
index.html
{% extends "network/layout.html" %}
{% load static %}
{% block body %}
<div class="container p-5">
{% if error %}
{{ error }}
{% endif %}
<h1 class="display-4">All Posts</h1>
<div class="form-group border rounded p-4">
<h2 class="diplay-3">New Post</h2>
<form id="addpost" class="form-group pt-5">
{% csrf_token %}
<div class="form-group">
<textarea class="form-control" id="body" placeholder="Add post here..."></textarea>
</div>
<input type="submit" class="btn btn-primary"/>
</form>
</div>
<div id="all-posts" class="all-posts">
</div>
</div>
{% endblock %}
{% block script %}
<script src="{% static 'network/main.js' %}"></script>
{% endblock %}
JavaScript
// Post on index page # API Routes /addpost
const addPost = () => {
const addPostUrl = '/addpost';
const csrftoken = getCookie('csrftoken');
const body = document.querySelector('#body').value;
// body needs to be passed into an object before using the stringify method
const bodyObject = { body };
fetch(addPostUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': csrftoken,
},
body: JSON.stringify(bodyObject)
})
.then(response => response.json())
.then(result => {
console.log(result);
})
.catch(error => {
console.log(error);
});
return false;
};
// Load posts in index page # API Routes /navbar_item
function loadPosts(navItem, event) {
preventPageLoad(event);
const postUrl = `/${navItem}`;
// Send a GET request to the URL to retrieve all posts
fetch(postUrl)
.then(response => response.json())
.then(data => {
data.forEach(post => {
const { fields } = post;
const allPostsContainer = document.querySelector("#all-posts");
const element = document.createElement('div');
const postId = `#post-${fields.id}`;
element.style.textDecoration = 'none';
element.classList.add('HoverClass1');
element.setAttribute('id', `post-${fields.id}`);
element.classList.add('d-flex', 'flex-column' ,'justify-content-between', 'p-4', 'm-3', 'lead', 'border', 'rounded');
element.style.color = '#000000';
element.innerHTML =
// This is returning an id
`<div class="bd-highlight font-weight-bolder mr-5">${fields.created_by}</div>
<div class="bd-highlight">${fields.timestamp}</div>
<div class="flex-fill bd-highlight">${fields.body}</div>`;
console.log(fields);
allPostsContainer.append(element);
const linePost = document.querySelector(postId);
linePost.addEventListener('click', (event) => {
console.log(event);
});
});
})
.catch(error => {
console.log(error);
});
return false;
}
Images showing my admin console in Django versus the browser console and what fetch is pulling in JavaScript. You'll see in the admin console we can view the username, but in the browser console all I'm getting is the user id with fetch.
I figured out how to do this. I added a serialize method to the Post model to convert these properties to JSON.
def serialize(self):
return {
'id': self.id,
'created_by': self.created_by.username,
'body': self.body,
'timestamp': self.timestamp.strftime('%b %-d %Y, %-I:%M %p'),
'likes': self.total_likes()
}
Then in views.py, in my viewposts function, instead of my the HttpResponse, I used JsonResponse and passed the model's serialize method as an argument.
#login_required
def viewposts(request, navbar_item):
if navbar_item == "viewposts":
posts = Post.objects.all()
posts = posts.order_by("-timestamp")
return JsonResponse([post.serialize() for post in posts], safe=False)
else:
return JsonResponse({"error": "Invalid page."}, status=400)
This allowed me to not have to deconstruct anything in my JavaScript file. So I could pull any attributes from my query using dot notation directly off of the data model in fetch.
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 5 years ago.
I have a formset to update my models and I display forms from my formset based on the search query. I have an ajax keyup function to send post requests so I can generate search_results.html that I then pass to in search.html.
Now, if I generate the forms dynamically the submit button does not work. If I ditch the search and pass the content of search_results.html to search.html directly it does work.
I have two views, SearchReportView which supposed to be the main one, and SearchReports to handle generating the report. I guess I might just merge them at this point - it doesn't solve my problem though.
Also I had this working before when I used multiple forms but I had to switch to a formset.
body of search.html
<div class="container">
<div class="navbar">
<div class="navbarItem">
<img src="{% static 'back.png' %}" width="20px" height="12px" \>Back
</div>
</div>
<div>
<h3>Search:</h3>
{% csrf_token %}
<input type="text" id="search" name="search" />
<span class="button-checkbox">
<button id="mybutton" type="button" class="btn" data-color="primary">Recent</button>
<input type="checkbox" class="hidden" name="reports_checkbox" checked />
</span>
</div>
<div class="normalText" id="search-results"></div>
</div>
search_results.html
{% if reports_and_formset %}
<form action="/TP/auto/report/search/" method="post" enctype="multipart/form-data"> {% csrf_token %}
{{ formset.management_form }}
{% for x, form in reports_and_formset %}
<button type="submit" class="button" >Submit</button>
{{ form.checking_user }}
{{ form.comment }}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% endfor %}
</form>
{% else %}
<tr> <td> <center>
No results found.
</center></td></tr>
{% endif %}
views.py
class SearchReportView(FormView):
def post(self, request, *args, **kwargs):
# form = ReportCommentForm(initial={'comment': ''})
# context = {'form': form}
if 'form-TOTAL_FORMS' in request.POST:
single_day_enb_reports = SingleDayEnbReport.objects.all()
report_form_set = modelformset_factory(SingleDayEnbReport, form=ReportCommentForm,
max_num=single_day_enb_reports.count())
formset = report_form_set(request.POST, queryset=single_day_enb_reports)
formset.save()
return HttpResponseRedirect('/TP/auto/report/search/report_search/')
# #requires_csrf_token
def get(self, request, *args, **kwargs):
return render(request, 'app/search.html')
class SearchReports(View):
def get(self, request, *args, **kwargs):
single_day_enb_reports = SingleDayEnbReport.objects.all()
report_form_set = modelformset_factory(SingleDayEnbReport, form=ReportCommentForm, max_num=single_day_enb_reports.count())
formset = report_form_set(queryset=single_day_enb_reports)
single_day_enb_reports_and_formset = zip(single_day_enb_reports, formset)
# context = {'single_day_enb_reports': single_day_enb_reports, 'formset': formset}
context = {'reports_and_formset': single_day_enb_reports_and_formset, 'formset': formset}
return render(request, 'app/search_results.html', context, context_instance=RequestContext(request))
#classmethod
def calculate_dates(self): #not important
def post(self, request, *args, **kwargs):
if 'form-TOTAL_FORMS' in request.POST:
single_day_enb_reports = SingleDayEnbReport.objects.all()
report_form_set = modelformset_factory(SingleDayEnbReport, form=ReportCommentForm,
max_num=single_day_enb_reports.count())
formset = report_form_set(request.POST, queryset=single_day_enb_reports)
# if formset.is_valid():
formset.save()
return HttpResponseRedirect('/TP/auto/report/search/report_search/')
if 'button_state' in request.POST:
search_text = request.POST['search_text']
button_state = request.POST['button_state']
if button_state == 'false':
button_state = False
else:
button_state = True
if button_state:
now, fit_date = self.calculate_dates()
single_day_enb_reports = SingleDayEnbReport.objects.all().filter(
Q(last_modification_date__range=[fit_date, now]) & (
Q(alarms__contains=search_text)|
Q(enb__contains=search_text)|
Q(creation_date__date__contains=search_text) |
Q(last_modification_date__date__contains=search_text)|
Q(comment__contains=search_text)|
Q(checking_user__name__contains=search_text)))
else:
single_day_enb_reports = SingleDayEnbReport.objects.all().filter(
Q(alarms__contains=search_text)|
Q(enb__contains=search_text)|
Q(creation_date__date__contains=search_text) |
Q(last_modification_date__date__contains=search_text)|
Q(comment__contains=search_text)|
Q(checking_user__name__contains=search_text))
report_form_set = modelformset_factory(SingleDayEnbReport, form=ReportCommentForm,
max_num=single_day_enb_reports.count())
formset = report_form_set(queryset=single_day_enb_reports)
single_day_enb_reports_and_formset = zip(single_day_enb_reports, formset)
context = {'reports_and_formset': single_day_enb_reports_and_formset, 'formset': formset}
return render_to_response('app/search_results.html', context, context_instance=RequestContext(request))
ajax.js
$('#search').keyup(function(){
delay(function(){
if($('input[name=reports_checkbox]:checked').val()) button_state = true
else button_state = false
$.ajax({
type: "POST",
url: "/TP/auto/report/search/report_search/",
data: {
'button_state' : button_state,
'search_text' : $('#search').val(),
'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()
},
success: searchSuccess,
dataType: 'html'
});
}, 500 );
});
});
function searchSuccess(data, textStatus, jqXHR){
//generated data is put into search-results <div>field in search.html
$('#search-results').html(data);
}
Please change your this line
$('#search').keyup(function(){
with
$(document).on('keyup','#search', function(){