JSON POST and GET 404 (Not Found) - javascript

I am trying to create an API in Django but am receiving the following errors message in the JavaScript console.
GET http://127.0.0.1:8000/edit/undefined 404 (Not Found)
POST http://127.0.0.1:8000/edit/undefined 404 (Not Found)
Does anyone know how to fix this problem?
API url: path("edit/<int:post_id>", views.edit, name="edit")
views.py
def edit(request, post_id):
try:
post = Post.objects.get(user=request.user, pk=post_id)
except Post.DoesNotExist:
return JsonResponse({"error": "Post does not exist."}, status=404)
if request.method == "GET":
return JsonResponse(post.serialize())
else:
return JsonResponse({"error": "Need a GET request."}, status=404)
JavaScript
document.addEventListener('DOMContentLoaded', function(){
const editButtons = document.querySelectorAll('.edit_button');
for (const button of editButtons) {
button.addEventListener('click', () => edit_email());
}
});
function edit_email(id){
console.log("edit button is clicked")
document.querySelector('#post_itself').style.display = 'none';
document.querySelector('#date_and_time').style.display = 'none';
document.querySelector('#likes').style.display = 'none';
const textarea = document.createElement('textarea');
//get post
fetch(`/edit/${id}`)
.then(response => response.json())
.then(post => {
textarea.innerHTML = `${post.post}`
document.querySelector('#p_user').append(textarea);
})
//save the post
fetch(`/edit/${id}`,{
method: 'POST',
post: JSON.stringify({
post: textarea.value
})
})
}
HTML
{% for post in page_obj.object_list %}
<div class = "individual_posts">
<h5 id="p_user" class = "post_user">{{ post.user }}</h5>
<h6 id = "post_itself">{{ post.post }}</h6>
<h6 id="date_and_time" class = "post_elements">{{ post.date_and_time }}</h6>
<h6 id="likes" class = "post_elements">{{ post.likes }}👍</h6>
{% if post.user == request.user %}
<button id="editButton" class="edit_button">Edit</button>
{% endif %}
</div>
{% endfor %}
I think something might be wrong in the way I am passing in the id to the API, but I am not sure. Could the for loop in the HTML be causing the problem?
models.py
class User(AbstractUser):
followers = models.ManyToManyField("self", related_name="users_followers", symmetrical=False)
following = models.ManyToManyField("self", related_name ="who_user_is_following", symmetrical=False)
def serialize(self):
return{
"followers": self.followers,
"following": self.following
}
class Post(models.Model):
post = models.TextField()
user = models.ForeignKey(User, on_delete=models.CASCADE, default="")
likes = models.IntegerField(default=0)
date_and_time = models.DateTimeField(auto_now_add=True)
def serialize(self):
return{
"id": self.id,
"post": self.post,
"user": self.user,
"likes": self.likes,
"date_and_time": self.date_and_time
}

you call edit_email without id here:
button.addEventListener('click', () => edit_email());
of cause, after call you get /edit/undefined on this line:
fetch(`/edit/${id}`)
you don't send anything like id, I can imagine it should be something like this:
button.addEventListener('click', (event) => edit_email(event.target.value));
You will also need to pass the value property to the button as post.id assuming that the post object will have an id key in your for loop.
If you are getting a reference error you need to check if page_obj.object_list has an id key for all the posts.

Related

How to call an async function from template?

When the user clicks a specific button, I want to call an synchronous function inside the already used view function, but passing a parameter from JavaScript. How can I do it?
Template:
<input class="form-check-input" type="checkbox" value="{{ subject.id }}" id="flexCheckDefault{{ subject.name }}" onclick="checkRequisite(this.defaultValue)">
Javascript:
function checkRequisite(id){
}
View:
if request.user.is_authenticated and request.user.groups.filter(name='student'):
subjects = subject.objects.all()
async def checkResquisite(id):
requisite = Requisite.objects.filter(subject_requisite_id=id)
context = {'subjects': subjects, 'requisite': requisite}
template = loader.get_template('student/subject/select.html')
return HttpResponse(template.render(context, request))
elif request.user.is_authenticated and request.user.groups.filter(name='teacher'):
return render(request, 'admin/home/index.html', {})
else:
return redirect('login')
I think there are a few misconcepts here. Async functions are called from the frontend to the backend (with ajax, fetch...), not the other way around:
async function checkRequisite(id){
response = await fetch(...);
}
Also, normally you would have two different views, I believe just as a good practice to have your code more organized and descriptive of what your views do exactly.
def load_template(request):
...
return render(...)
def ajax_view(request):
...
return JsonResponse(...)
But, to answer your question, the code below does the following:
On the template, with every click on checkboxes search which of them are selected take their value (subject.id), push into a list and send that list of IDs to backend using a post request with the fetch API.
There (on the backend), check the type the request method and filter requisite based on that list of IDs.
student/subject/select.html
{% extends 'base.html' %}
{% block content %}
{% for subject in subjects %}
<label>{{ subject.name }}</label>
<input class="form-check-input" type="checkbox" value="{{ subject.id }}" id="checkbox" onclick="checkRequisite()">
<br>
{% endfor %}
<hr>
<div id="demo"></div>
{% endblock %}
{% block script %}
<script>
async function checkRequisite() {
var id_list = [];
var inputs = document.getElementsByTagName("input");
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].type == "checkbox") {
if (inputs[i].checked) {
id_list.push(inputs[i].getAttribute('value'))
}
}
}
var payload = {
subject_ids: id_list,
};
var data = new FormData();
data.append( 'data' , JSON.stringify( payload ) );
data.append('csrfmiddlewaretoken', '{{ csrf_token }}');
await fetch("{% url 'core:load-template' %}", {
method: 'post',
body: data
}).then((response) => {
return response.json();
}).then((data) => {
let element = document.getElementById("demo").innerHTML = '';
for (let key in data['requisites']){
let element = document.getElementById("demo").innerHTML += `<p>Requisite: ${data['requisites'][key]['name']} | Subject: ${data['requisites'][key]['subject']}<p><br>`;
}
});
}
</script>
{% endblock %}
views.py
def load_template(request):
if request.user.is_authenticated and request.user.groups.filter(name='student'):
queryset = Subject.objects.all()
requisite = None
if request.method == 'POST':
data = json.loads(request.POST.get('data'))
requisites = Requisite.objects.filter(subject__id__in=data['subject_ids'])
response = {}
for requisite in requisites:
response[requisite.id] = { 'name': requisite.name, 'subject': requisite.subject.name }
return JsonResponse({ 'requisites': response })
return render(request, 'student/subject/select.html', {'subjects': queryset })
elif request.user.is_authenticated and request.user.groups.filter(name='teacher'):
return render(request, 'admin/home/index.html', {})
else:
return redirect('login')
urls.py
from django.urls import path
from core import views
app_name = 'core'
urlpatterns = [
path('load/template/', views.load_template, name='load-template'),
]

How to allow JSON access to the text within a textarea in HTML>

I am trying to create a button that allows users to save edits to a post, which they write in a textarea, through JSON. I am trying to save the data through a PUT request, but I get the following error:
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
javascript function:
function save_edit(id){
console.log("save button is clicked");
const edit_area = document.querySelector(`#edit_area_${id}`);
//save the post
fetch(`/edit/${id}`,{
method: 'PUT',
post: JSON.stringify({
post: edit_area.value
})
})
fetch(`/edit/${id}`)
.then(response => response.json())
.then(post => {
const post_itself =
document.querySelector(`#post_itself_${id}`);
post_itself.value = `${post.post}`;
post_itself.style.display = 'block';
})
}
django.views:
def edit(request, post_id):
try:
post = Post.objects.get(pk=post_id)
except Post.DoesNotExist:
return JsonResponse({"error": "Post not found."}, status=404)
if request.method == "POST":
edited_post = request.POST.get('post')
try:
post.post = edited_post
post.save()
except:
return JsonResponse({"error": "Editing the post did not work."}, status=404)
elif request.method == "GET":
return JsonResponse(post.serialize())
elif request.method == "PUT":
data = json.loads(request.body)
edited_post = data["edit_area"]
post.post = data["edited_post"]
post.save()
else:
return JsonResponse({"error": "Need a GET request."}, status=404)
html
{% for post in page_obj.object_list %}
<div class = "individual_posts">
<h5 id="p_user" class = "post_user">{{ post.user }}</h5>
<h6 id = "post_itself_{{ post.id }}" class="post_itself">{{ post.post }}</h6>
{% if post.user == request.user %}
<button id="{{ post.id }}" class="edit_button" value="{{ post.id }}">Edit</button>
{% endif %}
<textarea class="textarea" id="edit_area_{{ post.id }}" cols="220" rows="5"></textarea>
<button class="edit_save" id="save_{{ post.id }}">Save</button>
</div>
{% endfor %}
models.py serialization
def serialize(self):
return{
"id": self.pk,
"post": str(self.post),
"user": self.user.pk,
}
The GET request works correctly, but I am receiving the previously stated error from the PUT request. I think that it is because of the way I am getting the value through edited_post = data["edit_area"]. How do I correctly get access to the text within the textarea to pass to JSON?
In your save_edit PUT function you are using
post: JSON.stringify({
post: edit_area.value
})
But in your view you are looking for
data = json.loads(request.body)
edited_post = data["edit_area"]
post.post = data["edited_post"]
The JSON you are sending looks like
{"post": "Here's my edits"}
So you probably want something like:
data = json.loads(request.body)
post.post = data["post"]
Also - fetch uses "body" not "post" so you might want to amend your put function to
body: JSON.stringify({
post: edit_area.value
})

How to stop Getting 405 error Method not allowed?

I am trying to make my django project to work but somehow I always come to get this error
Method Not Allowed (POST): /
I have tried using decorators like #csrf_exempt like in the django documentation as to not encounter csrf errors and yet I came to this error.Please tell me what's the problem with my code...
urls.py
from test.views import HomePageView,predict
urlpatterns = [
path('', HomePageView.as_view(), name="homepage"),
path('predict', predict, name="predict"),]
views.py
class HomePageView(Notif, TemplateView):
template_name = "homepage.html"
def predict(self, request, *args, **kwargs):
if request == 'POST':
text = self.request.get_json().get('message')
# check if text is valid
response = get_response(text)
message = {'answer': response}
return JsonResponse(message)
#method_decorator(csrf_exempt)
def dispatch(self, *args, **kwargs):
return super(HomePageView, self).dispatch(*args, **kwargs)
app.js
onSendButton(chatbox) {
var textField = chatbox.querySelector('input');
let text1 = textField.value
if (text1 === "") {
return;
}
let msg1 = { name: "User", message: text1 }
this.messages.push(msg1);
fetch( $SCRIPT_ROOT+'/predict',{
method: 'POST',
body: JSON.stringify({ message: text1 }),
mode: 'same-origin',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'X-CSRFToken':csrftoken,
},
})
.then(r => r.json())
.then(r => {
let msg2 = { name: "Sam", message: r.answer };
this.messages.push(msg2);
this.updateChatText(chatbox)
textField.value = ''
}).catch((error) => {
console.error('Error:', error);
this.updateChatText(chatbox)
textField.value = ''
});
}
homepage.html
<div class="container">
{% csrf_token %}
<div class="chatbox">
<div class="chatbox__support">
<div class="chatbox__header">
<div class="chatbox__image--header">
<img src="https://img.icons8.com/color/48/000000/circled-user-female-skin-type-5--v1.png" alt="image">
</div>
<div class="chatbox__content--header">
<h4 class="chatbox__heading--header">Chat support</h4>
<p class="chatbox__description--header">Hi. My name is Sam. How can I help you?</p>
</div>
</div>
<div class="chatbox__messages">
<div></div>
</div>
<div class="chatbox__footer">
<input type="text" placeholder="Write a message...">
<button class="chatbox__send--footer send__button">Send</button>
</div>
</div>
<div class="chatbox__button">
<button class="btn-light"><img src="./images/chatbox-icon.svg" width="45px" height="45px"/></button>
</div>
</div>
</div>
<script type="text/javascript">
$SCRIPT_ROOT='{{ request.path }}'
</script>
Method Not Allowed (POST): / - means your function is not accepting post methos it accpets only get or other safe methods.
you're not changing any state of your database so you don't have to use post request you can use get intead of post
class HomePageView(Notif, TemplateView):
template_name = "homepage.html"
#staticmethod
def predict(self, request, *args, **kwargs):
if request == "POST":
text = self.request.get_json().get("message")
# check if text is valid
response = get_response(text)
message = {"answer": response}
return JsonResponse(message)
#method_decorator(csrf_exempt)
def dispatch(self, *args, **kwargs):
return super(HomePageView, self).dispatch(*args, **kwargs)
and change your urls like this
urlpatterns = [
path('predict', HomePageView.predict, name="predict"),
]
and in your javascript change method post to get
fetch($SCRIPT_ROOT + '/predict', {
method: 'GET',
body: JSON.stringify({
message: text1
}),
mode: 'same-origin',
})

How to do Live search Using Fetch Ajax Method In Django Python?

I am getting Post.match is not a function error when i do this :( Please help, i am a newbie in JavaScript part. (I am getting back an object so have to turn it into an array but still get this error after using the Objects.values Method)
My Views.py File:
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from .models import Post
def Data(request):
items = Post.objects.all()
data = []
for qs in items:
I = {"title":qs.title,
"content": qs.content,
"image": qs.image.url,
}
data.append(I)
return JsonResponse({"data":data})
My HTML File:
{% extends 'blog/base.html' %}
{% load static %}
{% block content %}
<div class = 'w-100 text-center'>
<h1>Search Results</h1>
<form id = "search-form" autocomplete="off">
{% csrf_token %}
<input name = 'game' type="text" id = "search-input" placeholder= "Post Search..">
</form>
<div id = "results-box" class = "results-card">
</div>
</div>
{% endblock content %}
{% block js %}
<script defer src="{% static 'blog/S1.js' %}"> </script>
{% endblock js %}
My Java Script File:
console.log('Heelowwww')
const url = window.location.href
const searchForm = document.getElementById("search-form")
const searchInput = document.getElementById("search-input")
const resultsBox = document.getElementById("results-box")
const csrf = document.getElementsByName("csrfmiddlewaretoken")[0].value
options = {method: "GET",
headers: {
Accept: "application/json"
},
data:{
'csrfmiddlewaretoken': csrf,
}
}
const SearchPosts = async SearchIt => {
const res = await fetch("http://localhost:8000/data/",options)
const Posts = await res.json()
S = Object.values(Posts["data"])
let matches = S.filter(post =>{
const regex = new RegExp(`^${SearchIt}`, 'gi')
return post.match(regex)
})
console.log(matches)
}
searchInput.addEventListener('input', () => SearchPosts(searchInput.value))
My data Json Page:
Json Data Page
Here post.match(regex) your trying to call the match method on a js object. It seems you should be calling it on on of the string properties of it. Something like: post.title.match(regex).

How to attach a callback on a recursively generated <select> dropdown?

I'm trying to implement chained dependent dropdown combobox selection, so you start with one combobox for main category and once you select main category, another <select> appears to select a subcategory, and so on until the innermost (most specific) category is selected. The code I have currently only works for one subcategory (direct children), how can I make it work for other levels too? So, I need to attach an onChange callback to a newly created <select> somehow.
This is jQuery code in my Django template:
{% extends 'pages/base.html' %}
{% block content %}
<h1>Create a product</h1>
<form method='POST' id='productForm' data-products-url="{% url 'products:ajax_load_categories' %}">
{{ form.as_p }}
</form>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$("select").change(function () {
var url = $("#productForm").attr("data-products-url");
var categoryId = $(this).val();
$.ajax({
url: url,
data: {
'category': categoryId
},
success: function (data) {
$("#productForm").append(data);
}
});
});
</script>
{% endblock %}
Here is my view:
def load_categories(request):
category_id = request.GET.get('category')
subcategories = Category.objects.get(id=category_id).get_children()
return render(request, 'products/category_dropdown_list_options.html', {'subcategories': subcategories})
products/category_dropdown_list_options.html
<select id="select_{{ subcategories.first.get_level }}">
<option value="">---------</option>
{% for subcategory in subcategories %}
<option value="{{ subcategory.pk }}">{{ subcategory.name }}</option>
{% endfor %}
</select>
Here is my urls.py:
app_name = 'products'
urlpatterns = [
path('create/', product_create_view, name='product-create'),
path('ajax/load-categories/', load_categories, name='ajax_load_categories')
]
Here is my Category model as per request:
from mptt.models import MPTTModel, TreeForeignKey
class Category(MPTTModel):
parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children')
name = models.CharField(max_length=255)
slug = models.SlugField()
class Meta:
unique_together = (('parent', 'slug',))
verbose_name_plural = 'categories'
class MPTTMeta:
order_insertion_by = ['name']
def __str__(self):
return self.name
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super().save(*args, **kwargs)
def get_slug_list(self):
ancestors = self.get_ancestors(include_self=True)
slugs = [ancestor.slug for ancestor in ancestors]
new_slugs = []
for idx, ancestor in enumerate(slugs, 1):
new_slugs.append('/'.join(slugs[:idx]))
return new_slugs
def get_recursive_product_count(self):
return Product.objects.filter(category__in=self.get_descendants(include_self=True)).count()
You'll need to turn your jQuery ajax script into a function, then call it recursively, like this:
<script>
var $r_ = function() {
var url = $("#productForm").attr("data-products-url");
var categoryId = $(this).val();
$.ajax({
url: url,
data: {
'category': categoryId
},
success: function (data) {
if (data != 'leaf_node') {
$("#productForm").append(data);
}
$('select').change($r_);
}
});
} //end of $r_
$('select').change($r_);
</script>
Update
If you take a look at the get_children method of the MPTT model, you'll see that it checks whether or not the instance has any children, and returns None if it doesn't.
Add a None check in your view, then add a different response when you've reached a leaf node:
from django.http import HttpResponse
def load_categories(request):
category_id = request.GET.get('category')
subcategories = Category.objects.get(id=category_id).get_children()
if subcategories:
return render(request, 'products/category_dropdown_list_options.html', {'subcategories': subcategories})
return HttpResponse('leaf_node')
Then add a check for leaf nodes in your ajax call (see above).

Categories