Reputation: 13
I am working in Djnago and I want to update the information without reloading the page. At first, I have used Ajax for post method so that the page should not reload after submitting the form, and it is working properly. Then I used Ajax for get method, and it is working too but to see the new information on the page, I have to refresh the page.
The view.py
file:
def bfs_view(request):
form = BFSForm(request.POST or None)
if form.is_valid():
form.save()
form = BFSForm()
try:
image_url_info = None
num_states_explored = None
final_solution = None
text_file = open("BFS\outputs\maze.txt", "w")
field_name = 'description'
input_value = BFS.objects.latest('id')
field_object = BFS._meta.get_field(field_name)
field_value = field_object.value_from_object(input_value)
field_string_value = str(field_value).split("\n")
text_file.writelines(field_string_value)
text_file.close()
m = Maze("BFS\outputs\maze.txt")
print("Maze:")
m.print()
print("Solving...")
m.solve()
print("States Explored:", m.num_explored)
print("Solution:")
m.print()
image_url_info = "/../../../static/search/bfs/maze.png"
num_states_explored = m.num_explored
# final_solution = ''.join(m.end_result)
final_solution = str(''.join(m.end_result))
print(''.join(m.end_result))
# BFS.objects.latest('id').delete()
except:
print("BFS ERROR: Error in the try session of BFS in view.py")
context = {
'form': form, 'image_url': image_url_info, 'states_explored': num_states_explored,
'solution': final_solution}
return render(request, "BFS/bfs.html", context)
def post_bfs_view(request):
if request.method == "POST" and request.is_ajax():
bfs_view(request)
return JsonResponse({"success":True}, status=200)
return JsonResponse({"success":False}, status=400)
def get_bfs_view(request):
if request.method == "GET" and request.is_ajax():
try:
image_url_info = None
num_states_explored = None
final_solution = None
text_file = open("BFS\outputs\maze.txt", "w")
field_name = 'description'
input_value = BFS.objects.latest('id')
field_object = BFS._meta.get_field(field_name)
field_value = field_object.value_from_object(input_value)
field_string_value = str(field_value).split("\n")
text_file.writelines(field_string_value)
text_file.close()
m = Maze("BFS\outputs\maze.txt")
m.print()
m.solve()
print("States Explored:", m.num_explored)
print("Solution:")
# final_solution = ''.join(m.end_result)
final_solution = str(''.join(m.end_result))
print(''.join(m.end_result))
# bfs_view(request)
# BFS.objects.latest('id').delete()
bfs_view(request)
except:
print("BFS ERROR: Error in the try session of BFS in view.py")
return HttpResponse(final_solution)
The main bfs.html
file:
<form id = "contactForm" method='POST' >{% csrf_token %}
{{ form.as_p }}
<input type='submit' value='Search' class="submit-btn poppins"/>
</form>
<div onload="myFunction()">
<h1>"The value is: " <pre><span id="myText"></span></pre></h1>
</div>
The Ajax for post
operation:
<script type="text/javascript">
$(document).ready(function(){
$("#contactForm").submit(function(e){
// prevent from normal form behaviour
e.preventDefault();
// serialize the form data
var serializedData = $(this).serialize();
$.ajax({
type : 'POST',
url : "{% url 'BFS:contact_submit' %}",
data : serializedData,
success : function(response){
//reset the form after successful submit
$("#contactForm")[0].reset();
},
error : function(response){
console.log(response)
}
});
});
});
</script>
The Ajax for get
operation:
<script>
$.ajax({
url: "{% url 'BFS:get_user_info' %}",
type: 'get', // This is the default though, you don't actually need to always mention it
success: function(data) {
var number = data;
document.getElementById("myText").innerHTML = number;
},
failure: function(data) {
alert('Got an error dude');
}
});
</script>
The urls.py
file:
app_name = 'BFS'
urlpatterns = [
path('bfs/', bfs_view),
# path('ajax/get_user_info', get_bfs_view, name='get_user_info'),
path('ajax/contact', post_bfs_view, name ='contact_submit'),
path('ajax/get_user_info', get_bfs_view, name = 'get_user_info'),
]
The models.py
file:
from django.db import models
from django.urls import reverse
# Create your models here.
class BFS(models.Model):
description = models.TextField(blank=True, null=True)
def __str__(self):
return self.description
The forms.py
file:
from django import forms
from .models import BFS
class BFSForm(forms.ModelForm):
description = forms.CharField(
required=False,
label=False,
widget=forms.Textarea(
attrs={
'id': 'TA1',
'rows': '10vh',
'cols': '8vw',
'placeholder': 'Enter Your Map Here',
'class': 'textfield-style',
'style': 'max-width: 100%; max-height: 100%;outline: none; border: none; background-color: white; width: 100%; padding: 12px 20px; margin: 8px 0; box-sizing: border-box; font-size: 20px; spellcheck="false";',
}
)
)
class Meta:
model = BFS
fields = [
'description'
]
def __init__(self, *args, **kwargs):
super(BFSForm, self).__init__(*args, **kwargs)
for field in self.fields:
self.fields[field].widget.attrs.update({
'class': 'form-control'})
Upvotes: 1
Views: 1169
Reputation: 439
This might be the time to introduce a frontend framework to your pipeline as it will make life easier to refresh pages upon DOM state changes. I had challenges myself trying to implement similar functionality with Django alone some years back until i introduced React Js.
Here is something that could help you without learning another software altogether:
Update DOM without reloading the page in Django
However, you will notice that the marked answer there still uses Javascript i.e jQuery. So there is no denying the fact that you will need to implement javascript to achieve what you want.
Which is why i mentioned React Js.
Good luck!
Upvotes: 0
Reputation: 1370
I'd suggest you wrapping what you have used to get the update in a function then do the function call after you hit the success
method after submitting the form...
In your js
for example:
$(document).ready(function(){
$("#contactForm").submit(function(e){
// prevent from normal form behaviour
e.preventDefault();
// serialize the form data
var serializedData = $(this).serialize();
$.ajax({
type : 'POST',
url : "{% url 'BFS:contact_submit' %}",
data : serializedData,
success : function(response){
//reset the form after successful submit
$("#contactForm")[0].reset();
// This will then call for the get request to update the id "myText"
live_update();
},
error : function(response){
console.log(response)
}
});
});
function live_update(){
$.ajax({
url: "{% url 'BFS:get_user_info' %}",
type: 'get', // This is the default though, you don't actually need to always mention it
success: function(data) {
var number = data;
document.getElementById("myText").innerHTML = number;
},
error: function() {
alert('Got an error dude');
}
});
}
});
Also, for the success method within the live_update
function... You could also use,
success: function(data) {
$("#myText").hide();
$("#myText").html(data);
$("#myText").fadeIn(1000);
},
That should give it a nice little fade in effect as it updates. :)
Upvotes: 1