How to avoid page reloading in my django front end? - javascript

every time I press submit button page gets reloaded.I have included preventdefault on submit.But it is not working.
Please help me.
This is part of html code .
Every time on submit I got redirected to another page.
I don't want page to reload. How to fix this.
<form id='form' method="POST">
{% csrf_token %}
{{form.as_p}}
<input type='hidden' id='myusername' value='{{user}}'>
<input type="submit" class='btn btn-primary'>
</form>
{% block script %}
<script src='https://cdnjs.cloudflare.com/ajax/libs/reconnecting-websocket/1.0.0/reconnecting-websocket.js'></script>
<script>
var loc=window.location
var wsStart='ws://'
var formData=$("#form")
var me=$("#myusername").val()
var Holder=$("#items")
var msgInput=$("#id_message")
if(loc.protocol=='https:'){
wsStart='wss://'
}
var endpoint=wsStart + loc.host + loc.pathname+'/'
var socket=new ReconnectingWebSocket(endpoint)
socket.onmessage=function(e){
console.log('message',e)
var Data=JSON.parse(e.data)
chatHolder.append('<li>'+Data.message+' via '+Data.username+'</li>')
}
socket.onopen=function(e){
console.log('open',e)
formData.submit(function(event){
event.preventDefault()
var msgText=msgInput.val()
var finalData={
'message':msgText
}
socket.send(JSON.stringify(finalData))
formData[0].reset()
})
}
socket.onerror=function(e){
console.log('error',e)
}
socket.onclose=function(e){
console.log('close',e)
}
</script>
{% endblock %}

store the content from your form in a context dict then pass it to the new page maybe?

Related

Adding Plus minus button in form with POST and scrf_tocken

With Django I generate a list of items, with the number of them.
To be more convenient, I would like to add a plus and a minus button.
I found a simple solution, but when I try to put this in my form with the POST method, if click the page refresh or POST ?
I don't want to refresh the page every time, I have a validate button and all the value will be treat in one time.
<form class"form-inline" action="{% url 'stock:stock' %}"method="post" >{% csrf_token %}
{% for stock in stocks %}
<div>
<button id="minusButton">-</button>
<input type="number" name="stock" id="stock" value="{{stock.stock}}" >
<button id="plusButton">+</button>
</div>
{% endfor %}
</form>
<script>
textInput = document.querySelector('#numberInput');
plusButton = document.querySelector('#plusButton');
minusButton = document.querySelector('#minusButton');
plusButton.onclick = () => textInput.value = parseInt(textInput.value) + 1;
minusButton.onclick = () => textInput.value = parseInt(textInput.value) - 1;
</script>
If anyone know how to manage?

Django forms - How to change form data with HTML DOM?

I am trying to change a Django form's data by using:
document.getElementById("id_role").innerHTML = "developer"
The CustomUser model has a "role" field that is referenced in the function. By testing the output (with the displayField() function, it appears that document.getElementById("id_role").innerHTML actually references all of the available fields ("choices" given in the models.py).
The goal is for the second function, changeField(), to change the selected data on the form (my goal isn't to change the database's stored data at this point, just the selected form's input).
My question: How do I use document.getElementById().innerHTML to access the specific value that is shown in the form, instead of all of the options for the field?
models.py
TECH_OPTIONS = ( ('developer','DEVELOPER'), ('manager','MANAGER'), ('testing','TESTING'), )
class CustomUser(AbstractUser):
career = models.CharField(max_length=30)
role = models.CharField(choices=TECH_OPTIONS,blank = True, max_length=30)
def __str__(self):
return self.username
html page
{% extends "base.html" %}
{% load bootstrap3 %}
{% block content %}
<h1 id="testTag">{{user.username}}'s Info</h1>
<input onclick="displayField(); changeField();" type="submit" name="" value="TESTING">
<form method="post">
{% csrf_token %}
{% bootstrap_form form %}
<input type="submit" value="Save" />
</form>
<script type="text/javascript">
function displayField(){
var myFormFields = document.getElementById("id_role").innerHTML
document.getElementById("testTag").innerHTML = myFormFields;
}
function changeField(){
document.getElementById("id_role").innerHTML = "developer"
}
</script>
{% endblock %}
You need to use value rather than innerHTML to change/read the value of a field:
document.getElementById("id_role").value = "developer"

Ajax working on Localhost but not on Live Server

I'm working on a website on which users can comment something below the posts, running on Python & Django.
As soon as a user comments something, then I'm updating comments without refreshing the web-page. Here's the code,
In views.py
postType1 = sorted(Posts.objects.filter( . . . ), key=lambda x: random.random())
postType2= Posts.objects.filter( . . . )
In template,
// BLOCK - 1
{% for post in postType1 %}
<p>{{ post }}</p>
<div class="comm_update" action="{% url 'comment:create' post.id %}">
<form class="comm_form" action="{% url 'comment:create' post.id %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<textarea id="id_comment"></textarea><br /><br />
<button type="submit">Submit</button>
</form>
</div>
{% endfor %}
<hr />
// BLOCK - 2
{% for post in postType2 %}
<p>{{ post }}</p>
<div class="comm_update" action="{% url 'comment:create' post.id %}">
<form class="comm_form" action="{% url 'comment:create' post.id %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<textarea name="comment_text" id="id_comment"></textarea><br />
<button type="submit">Submit</button>
</form>
</div>
{% endfor %}
Auto updating comments without refreshing webpage,
$(document).on("submit", ".comm_form", function(t) {
t.preventDefault();
var o = $(this),
e = $.post(o.attr("action"), o.serialize()),
n = o.attr("action");
e.done(function(t) {
var e = $(t).find(".comm_update[action='" + n + "']");
o.closest(".comm_update").html(e), o[0].reset()
})
});
On localhost everything is working fine.
*But on live server the first block BLOCK - 1 is not updating the comments, instead when user presses submit entire comment section disappears.
How can we fix this issue?
Thank You!

Javascript Confirm continues regardless of user answer

I have an html template that I use with my Django website code. In the template are a couple of forms. Two of the forms are datefields and I have a confirm popup that is activated on submission if the user fills them in. I wanted the popup to exit the form submission and return to the page if the user clicks 'cancel', and to continue submitting the form if the user clicks 'ok'.
The confirm popup shows up correctly but the form submission continues no matter what the user clicks. How do I change it so that the form submission exits if the user clicks 'cancel'?
Javascript looks like this:
<script type="text/javascript">
var checkFields = ["SPAN_START","SPAN_END"];
function checkForm( theForm ) {
for (i in checkFields ) {
var fieldName = checkFields[ i ];
var theField = theForm[ fieldName ];
if ( theField.value ) {
var retVal = confirm("Are you sure you want to specify a date?");
if (retVal == true){
theField.submit()
return true;
} else {
return false;
}
}
}
}
</script>
The html where it is used looks like this:
<form action="/InterfaceApp/Nominal_Request/" method="post" class="form" onsubmit="checkForm( this )">
{% csrf_token %}
<div class="panel-body text-center">
{% bootstrap_form form_span_start %}
{% bootstrap_form form_span_end %}
{% buttons %}
<button type="submit" class="btn btn-primary center-block" value="Submit" name="Range">
{% bootstrap_icon "fire" %} Generate Range of Requests
</button>
{% endbuttons %}
</div>
</form>
Can anyone tell me how to cancel the submission of the form if the user clicks 'cancel'??
Much appreciated.
You have to return the value of the function to the inline event handler
onsubmit="return checkForm( this )"
preferably you wouldn't use inline event handlers at all, but addEventListener instead.

How to write JQuery function to display text in special location of Django template

I'm trying to create my first ajax function in Django.
I want to change my code using JQuery, the idea is pretty simple:
User type a subject name and this name is displayed in subject-list below the form,
The problem is I don't really know what to type in JQuery function.
JQuery:
function create_subject() {
$("input").focus(function(){
var subject = $(this).val();
$(".btn-create").click(function(){
/* What I need to write in here */
});
});
}
In HTML "subjects" refer to database.
HTML
<div id="subjects-list">
{% if user.username %}
<ul>
{% if subjects %}
<form method="post" action=".">{% csrf_token %}
{% for subject in subjects %}
-------- TYPED TEXT SHOULD BE HERE --------> <li>{{ subject.name }}</li>
{% endfor %}
</form>
{% else %}
<p>No Subjects for this user</p>
{% endif %}
</ul>
{% else %}
You are in else
{% endif %}
</div>
That's how HTML looks in "View Page Source"
<div id="create-subject">
<form method="post" action="."> <div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='cfbd1893742c3ab9936bacaae9653051' /></div>
<p><label for="id_name">Subject Name:</label> <input id="id_name" type="text" name="name" size="9" /></p>
<input type="button" name="subject-create-b" value="Create Subject" class="btn-create"/>
</form>
</div>
<div id="subjects-list">
<ul>
<form method="post" action="."><div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='cfbd1893742c3ab9936bacaae9653051' /></div>
<li>Math 140<span id="subject-link"></span></li>
</form>
</ul>
</div>
</div>
And that's my form
forms.py
class SubjectCreationForm(forms.Form):
name = forms.CharField(label="Subject Name", widget=forms.TextInput(attrs={'size':9}))
class Meta:
exclude = ('created_by', 'created_time', 'num_of_followers', 'vote')
def clean_name(self):
name = self.cleaned_data['name']
if len(name)>1:
return name
else:
raise forms.ValidationError("Subject name should be longer")
In order to do what (I think) you want to do which is some basic AJAX using Django as your backend, you'll need the following:
A view which returns the data you want to load
There are a number of ways you can represent the data, but to keep it simple, I'll use HTML.
Javascript to load that view (using JQuery if you like)
Your code might look like this for the first part:
urls.py:
...
(r'^get-subjects/$', 'yourapp.views.get_subjects'),
...
views.py:
...
def get_subjects(request):
subjects = # code to fetch your subjects.
return render_to_response('subjects_template.html', {'subjects': subjects})
...
subjects_template.html:
{% for subject in subjects %}
<li>{{ subject.name }}</li>
{% endfor %}
For the second part, it might look like this:
main_template.html:
...
<ul id="subjects-list"></ul>
<script>
function loadSubjects() {
$.ajax({
url: "/get-subjects",
success: function (data) {
$("#subjects-list").html(data);
}
});
}
</script>
...
[1] render_to_response()
[2] jQuery.ajax()
This will get you most the way there. When you want to reload the list, you call the loadSubjects() function.
As far as creating the subjects go, that is a different thing. What you'll want to look into is how to do an HTML form submission without leaving the page. There are plenty of tools and libraries to do that stuff with a nice api. If you want to stick with JQuery, you might consider this plugin for a nicer api.
function create_subject() {
$("input").focus(function(){
var subject = $(this).val();
$(".btn-create").click(function(){
$('#subjects-list').append(subject);
});
});
}
that said, you probably don't want to assign the click handler every time the input is focused. i'd move that out of the focus handler.

Categories