I have one app name register_login and this app manages login and register opeartions. I have a form on localhost:8000/login page and i want that the button redirects to my func in register_login app but i cant do it. I'm new at Django Framework. How can i handle this?
MAIN URLS.PY
from django.conf.urls import include,url
from django.contrib import admin
from register_login.views import login, register, test
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^homepage/', include('homepage.urls')),
url(r'^login/$', login),
url(r'^register/$', register),
url(r'^success/$', test),
]
LOGIN PAGE .HTML
<form id=registerLogin style="margin-top: 30px; margin-left: 350px;">
<header>Login</header>
<label >Username <span>*</span></label>
<input id="username"/>
<label >Password <span>*</span></label>
<input id="password"/>
<button id="login">Login</button>
<h1 style="margin-left: 20px;">Are you not registered?</h1>
<button id="register">Register</button>
</form>
At the end of this html there is my .js file. I didnt forget.
JAVASCRIPT
if (!jQuery) { throw new Error("This page requires jQuery") }
function readInput() {
e.preventDefault();
var userName = document.getElementById('username').value;
var password = document.getElementById('password').value;
debugger
$.ajax({
type: "POST",
url: "/success/",
data: {'username':username,'password':password, csrfmiddlewaretoken: '{{ csrf_token }}'},
dataType: 'json',
success : function(json) {
$('#post-text').val(''); // remove the value from the input
console.log(json); // log the returned json to the console
console.log("success"); // another sanity check
},
});
}
(function ($) {
$("#login").click(function(){
readInput();
});
})(jQuery);
And finally my function. Its in register_login app as i said before
REGISTER_LOGIN VIEW
def test(request):
embed()
if request.method == 'POST':
embed()
return HttpResponse("hell world")
I tried to change url like "/register_login/success/","/register_login/success","/register_login/success/$","/success/","success/" or "/success/$". Nothing works
I need to go that function but it doesnt :(
Since you are logging in via ajax, you can not redirect in your test view. What you can do is add a redirect in your ajax success function. Something like this:
// similar behavior as an HTTP redirect
window.location.replace("/some-url/");
or
// similar behavior as clicking on a link
window.location.href = "/some-url/";
Also, you need to fix your javascript code, add preventDefault in the click handler and remove it in the readInput. You also need to remove the quotes in the data object and make sure you used the correct variables. Something like this:
$(function() {
function readInput() {
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
$.ajax({
type: "POST",
url: "/success/",
data: {
username: username,
password: password,
csrfmiddlewaretoken: '{{ csrf_token }}'
},
dataType: 'json',
success : function(json) {
window.location.replace("/some-url/");
}
});
}
$("#login").click(function(e){
e.preventDefault();
readInput();
});
});
Related
;0mage to process it on server and get a response without refreshing the page. I look up for some tutorials how to use AJAX and jQuery to do this but I don't have much knowledge at this matter. I'm completly stuck and have no idea what shall I do next. So far my code looks like this:
models.py
class Snip(models.Model):
#some fields
snip = models.FileField(upload_to="snips/")
latex = models.TextField(default = '')
forms.py
from .models import Snip
from django import forms
class SnipForm(forms.ModelForm):
class Meta:
model = Snip
fields = ['snip']
HTML:
<form id="snipForm" method="POST" enctype="multipart/form-data">
<input type="hidden" name="csrfmiddlewaretoken" value="...">
<div class="row align-items-center">
<div class="col-12">
<label for="id_snip">Snip:</label>
<input type="file" name="snip" required="" id="id_snip" class="btn-success p-2 rounded">
<input type="submit" name="upload" id="upload" class="btn btn-secondary">
</div>
</div>
</form>
JavaScript/AJAX
var upload_btn = document.getElementById("upload")
upload_btn.addEventListener('click', function () {
var form_data = new FormData();
var ins = document.getElementById('id_snip').files.length; //
if(ins == 0) return console.log("No snip!!!")
form_data.append("file[]", snip.files[0]);
csrf_token = $('input[name="csrfmiddlewaretoken"]').val();
form_data.append("csrfmiddlewaretoken", csrf_token);
headers = {'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'};
console.log(form_data);
console.log(headers);
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('HTTP_X_REQUESTED_WITH', 'XMLHttpRequest');
}
});
$.ajax({
type: 'POST',
url: 'https://localhost:8000/docs/', // point to server-side URL
dataType: "json",
ContentType: "application/json",
cache: false,
processData: false,
headers: headers,
data: form_data,
success: function (response) { // display success response
console.log("SUCCESSSSSSSSS")
},
error: function (response) {
console.log("NOPEEEEEE")
}
});
});
views.py
from django.shortcuts import render
from django.contrib.auth.models import User
from .models import Snip
from .forms import SnipForm
from django.http import JsonResponse
from django.core import serializers
def generate(request):
is_ajax = request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
if is_ajax and request.method == "POST":
file = request.FILES['snip']
processed_image = "Some text from OCR"
return JsonResponse({'text':'Yay, I got text from OCR'})
if request.method == 'GET':
Users = User.objects.all()
form = SnipForm()
user_list = []
for user in Users:
if user.get_full_name():
user_list.append(user.get_full_name())
return render(request, "new.html", {'Users': user_list, 'form': form})
To sum up:
The image is loaded to id_snip input tag. After clicking on id="upload" button it should be sent to django server and then to outer OCR API to receive some text back. Then it's supposed to be displayed on the front end without refreshing the page. However after clicking submit I get error:
The view docs.views.generate didn't return an HttpResponse object. It returned None instead.
My first thought was to check the is_ajax value. It occured to be false. So my question is:
How can I check if the request "is AJAX"? I know in previous versions of django it was is_ajax() method but since some like 3.1 version is not recommended
Is there any simple way to do it? My goal is to put received response (text) somewhere else on the page.
#UPDATE:
So I changed a bit of JavaScript/AJAX code above due to this post
I added
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('HTTP_X_REQUESTED_WITH', 'XMLHttpRequest');
}
});
However on Django error page I can't see any META info such as HTTP_X_REQUESTED_WITH.
What more it seems that no data is appended to the form_data:
Output of:
console.log(form_data)
console.log(headers)
is:
FormData {}
{HTTP_X_REQUESTED_WITH: 'XMLHttpRequest'}
For now I get exactly the same error message, which is The view docs.views.generate didn't return an HttpResponse object. It returned None instead.
What might be wrong with this code? It seems fine for me
Based on my understanding, ajax could be used to prevent the page from reloading/refreshing/redirecting after submitting a request to the server. However, my code will redirect to display the JSON response. I used e.preventDefault() and it didn't work. Is there anything that I am doing wrong?
My Django code looks like this:
views.py:
def projects(request):
if request.method == 'POST':
task_id = request.POST.get('task_id')
myUser = User.objects.get(pk=request.user.id)
myTask = Task.objects.get(pk = task_id)
myTask.claimed.add(myUser) #add the user to the task
return JsonResponse({'status': 'ok'})
projects = Project.objects.all()
tasks = Task.objects.all()
open_tasks = tasks.filter(status='Created')
proj_dict = {}
context = {
'projects' : projects,
'tasks' : tasks,
'open_tasks' : open_tasks,
}
return render(request, 'projects/projects.html', context)
My HTML:
<form action="{% url 'projects:' %}" method="POST" class='join-form' id='{{task.id}}'>
{% csrf_token %}
<input type="hidden" name="task_id" value={{task.id}}>
<button type="submit" class=" claim-font claim-button">
Join
</button>
</form>
Tha ajax call:
<script>
$(document).ready(function () {
$('#join-form').on('submit', function (e) {
e.preventDefault();
e.stopPropagation();
const url = $(this).attr('action');
console.log("here we are");
const task_id = $(this).attr('id');
$.ajax({
type: 'POST',
dataType: "json",
headers: { 'X-CSRFToken': csrftoken },
url: url,
data: {
csrfmiddlewaretoken: '{{ csrf_token }}',
task_id: task_id,
},
success: function (response) {
alert(data);
console.log("here we are");
},
error: function (response) {
console.log('error', response);
alert("shit")
}
})
return false;
});
});
</script>
Seems like ajax will make sure that my browser doesn't redirect/reload/refresh after the submit button is clicked, and only the server-side changes. However, my browser turns out to be displaying: {"status": "ok"}
Any insights are greatly appreciated!
I noticed that you have class attribute for your form. Change your JQuery selector from $('#join-form') to $('.join-form') for class attributes
<script>
$(document).ready(function () {
$('.join-form').submit(function(e) {
e.preventDefault();
// write your code here
});
});
</script>
You need to change button type from "submit" to "button"
I have a prescription form and submitted the form using AJAX.
Now I want to automatically redirect to another route from AJAX after the form successfully submitted.
I have tried with several options like
window.location.href = "{ url('/show-all-prescription') }"
and
{{ route('/show-all-prescription')}}
AJAX CODE
jQuery.ajax({
url:"{{ url('/submit_prescription') }}",
type: 'GET',
data: {name: name, age: age, mobile_no: mobile_no},
success:function(msg){
if(msg>0)
{
// window.location.href = "{ url('/show-all-prescription') }";
{{ route('/show-all-prescription')}}
}
}
});
And got the error
Route [/show-all-prescription] not defined
route.php
Route::get('/show-all-prescription', 'prescriptionController#show_all_prescription');
But not getting the result. Someone Help Please?
In route file
Route::get('/show-all-prescription', 'prescriptionController#show_all_prescription')->name('show-all-prescription');
Then in blade file ajax request,
window.location.href = "{{ route('show-all-prescription')}}";
My template.html:
...
<button class="btn btn-success" onclick="save_post(event, 'publish')">Publish</button>
...
My javascript.js:
function save_post(event, action) {
event.preventDefault();#new line
var tag_string=document.getElementById('id_tags').value;
if (action=='publish' || action=='draft') {
var url_post='/blog/post/new/'
} else {
var url_post='/blog/post_edit/'
};
$.ajax({type: 'POST',
url: url_post,
data: {
tagstring: tag_string,
action: action
},
success: function (lista) {
//code
}
});
};
My views.py:
#staff_member_required
def post_new(request):
context_dict=[]
if request.method == "POST":
if request.is_ajax():
#code
...
else:
form = PostForm()
return render(request, 'blog/post_edit.html', context_dict)
My url.py:
app_name = 'blog'
urlpatterns = [
...
path('post/new/', views.post_new, name='post_new'),
path('post/<int:pk>/edit/', views.post_edit, name='post_edit'),
...
My views is called by the url (browser), then the button call a javascript function and it call (with ajax) again the same view, this time with request.method = "POST" and this works, but request.is_ajax() gives False.
For call post_edit (probabily) I need the id of the post. Where can I get it?
Should I pass it to save_post() from the template?
Edit: ignore these lines below
Also should I use preventDefault() somewhere?
Thank you
Edit: now I use preventDefault() but it gives this error:
Not Found: /blog/post_new/
[26/Jan/2018 19:07:20] "POST /blog/post_new/ HTTP/1.1" 404 10871
and ajax dosn't call the view. Edit: I solved this problem, but I continue tomorrow :)
Your Ajax code some problems and view is correct
I have attached my Code attached Image and code
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'myajaxview', // the url where we want to POST
data :{
'csrfmiddlewaretoken': '{{csrf_token}}',
'text': text,
'search': search,
'email': email,
'url': url,
'telephone': telephone,
'password': password,
'number': number,
},
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
I´m building a social network with Grails and got stucked
on giving users inner their editprofile
page the chance to paste an youtube-Url into a textfield and by clicking a button a JS regexxes the id out of the URL pasted, an ajax post is fired updating a div with a preview image of the youtube video
the html looks like :
<g:textField name="videoinput" class="videoinput reLef" value="" />
<span class="daten_videouploadbtn reLef" ></span>
<g:render template="/forms/storedVideos" />
the JS looks like :
$('.daten_videouploadbtn').click(function() {
var string = document.editProfileForm.videoinput.value;
var neu = string.replace(/http[s]?:\/\/(?:[^\.]+\.)*(?:youtube\.com\/(?:v\/|watch\?(?:.*?\&)?v=|embed\/)|youtu.be\/)([\w\-\_]+)/i, '$1');
var id = RegExp.$1;
jQuery.ajax({
type:'POST',
data:RegExp.$1,
url:'${createLink(action: 'addVideo')}',
success:function(data,textStatus){jQuery('#storedvideos').html(data);},
error:function(XMLHttpRequest,textStatus,errorThrown){}
});
});
the controller looks like :
def addVideo() {
def videoitems = !!%%-- HOW TO PARSE YOUTUBE-ID HERE -%%!!
render(template:"/forms/storedVideos", model: [newVideo:videoitems])
}
and stored videos looks :
<div id="storedvideos"><span><img src="http://img.youtube.com/vi/${newVideo}/default.jpg" width="225px" height="130px"/></span></div>
i just dont get it how to catch the data of the Ajax Post and update the div with the preview image with the id inside,
can someone give a hint ? it is killing me
You should post the data like this:
jQuery.ajax({
type: 'POST',
data: { value: RegExp.$1 },
...
After that you can access the posted data inside your grails controller with params.value.
I got this working on Grails 2.0.4:
Javascript/Ajax
var data =
{requestId: 12456,
node: "node1",
host: "mynode.com"};
$.ajax({
url: '/myurl',
data: JSON.stringify(data),
type: 'post',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function() ...
},
error: function() ...
}
});
In Grails....
def service(){
def jsonObj = request.JSON
}
I like this approach because request.JSON parses the data and returns a ready to use object.