I'm trying to post the form data using
'XMLHttprequest' to the django views and i'm getting 'A server error occurred. Please
contact the administrator.' in the browser console, and
i'm getting following error
raise MultiPartParserError('Invalid boundary in multipart: %s' % boundary.decode())
AttributeError: 'NoneType' object has no attribute 'decode' in my terminal.
The following is my code snippet.
<html><head><tile></title>
<body>
<form>
{% csrf_token %}
<input type="text" id="in" name="">
<input type="button" id='' value="submit" onclick="myfunction()">
</form>
<script type="text/javascript">
function myfunction() {
var emailId = document.getElementById('in').value;
var csrfToken = getCookie("csrftoken");
var myform = new FormData();
myform.append("email", emailId);
var xhttp = new XMLHttpRequest();
xhttp.open("POST", '{% url "log" %}', true);
xhttp.setRequestHeader('X-CSRFToken', csrfToken );
xhttp.setRequestHeader("Content-Type", "multipart/form-data;charset=utf-8");
xhttp.send(myform);
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText)
}
};
}
</script>
<body>
</html>
This is my urls.py file
from django.contrib import admin
from django.urls import path
from zifapp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('login/', views.login),
path('log', views.xmlhttprequest, name='log'),
]
and this is my views.py file
from django.http import JsonResponse
def xmlhttprequest(request):
print(request.POST.get('email', False))
return JsonResponse({'status':True}, safe=False)
Related
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',
})
I have madefunction that resends otp when the 'resend Otp' lick is clicked. This is django project. The following are the codes that I wrote.
html (this page extends base.html)
<a class="resend-otp" href="#" onclick="ReSendOTP('{{user.username}}', 'resendOTPmess')" ><i id="resendOTPmess">Resend</i>OTP?</a>
<script type="text/javascript" src="{% static 'jquery-3.6.0.min.js' %}"></script>
<script type="text/javascript" src="{% static 'regd_ajax.js' %}"></script>
js file
function ReSendOTP(username, mess_id){
mess = document.getElementById(mess_id);
mess.innerText = "Sending...";
$.ajax({
type: 'GET',
url: '/user/resendOTP',
data: {usr:username},
success: function(data){
mess.innerText = data;
}
})
}
views.py
def resend_otp(request):
if request.method == 'GET':
get_user = request.GET['usr']
if User.objects.filter(username = get_user).exists() and not User.objects.get(username = get_user).is_active:
user = User.objects.get(username=get_user)
user_otp = random.randint(100000, 999999)
UserOtp.objects.create(user = user, otp = user_otp)
mess = f"Hello, {user.first_name}, \nYour OTP is {user_otp}\n Thanks!"
send_mail(
"Welcome to Solve Litigation - Verify your Email", #subject
mess, #message
settings.EMAIL_HOST_USER, # sender
[user.email], #reciever
fail_silently= False
)
return HttpResponse("Resend")
return HttpResponse("Can't Send OTP")
urls.py
from .views import resend_otp
path('resendOTP', resend_otp)
So here I am requesting a resend otp for the "username: rick.bhardwaj27#gmail.com" but I am getting the follwing error in the console
jquery-3.6.0.min.js:2 GET http://127.0.0.1:8000/user/resendOTP?usr=rick.bhardwaj27%40gmail.com 404 (Not Found)
Recently I learned ajax but now i am trying to implement in my fjango project but it is not working.
signup.js
$(document).ready(function(){
$(document).on('submit', '#signup', function(e){
e.preventDefault();
var email = $('input[name="email"]').val();
var name = $('input[name="name"]').val();
var password1 = $('input[name="password1"]').val();
var password2 = $('input[name="password2"]').val();
var url = '/signup'
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if(req.responseText == 'true' ){
alert('account created')
}
}
};
req.open("POST", url, true);
req.send();
})
});
urls.py
urlpatterns = [
path('',login_required(StockView.as_view(), login_url='login'), name='stock'),
path('login/', LoginView.as_view(), name='login'),
path('signup/', SignupView.as_view(), name='signup'),
path('logout',LogoutView.as_view(), name='logout'),
path('addproduct/', login_required(AddProduct.as_view(), login_url='login'), name='addproduct'),
path('update/<int:pk>', login_required(EditProduct.as_view(), login_url='login'), name='editproduct'),
path('delete/', login_required(DeleteProducts.as_view(), login_url='login'), name='deleteproducts'),
view.py
class SignupView(TemplateView):
template_name = 'stock/signup.html'
def get(self, request):
form = SignUpForm()
args = {'form': form}
return render(request, self.template_name, args)
def post(self, request):
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=raw_password)
login(request, user)
return redirect('home')
else:
args = {'form': form}
return render(request, self.template_name, args)
form.py
class SignUpForm(UserCreationForm):
username = forms.CharField(max_length=30,widget=forms.TextInput(attrs={'class':'form-control','name':'name'}))
email = forms.EmailField(widget=forms.EmailInput(attrs={'class':'form-control'}))
password1 = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control'}),help_text='Password Should Match',label='Password')
password2 = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control'}),label='Password Confirmation')
class Meta:
model = AppUser
fields = ('username', 'email', 'password1', 'password2' )
template.html
<form method="post" id="signup" >
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-primary" >Signup</button>
</form>
</div>
<script src="{% static 'assets/signup.js' %}"></script>
CONSOLE ERROR:
signup.js:21 POST http://127.0.0.1:8000/signup 404 (Not Found)
(anonymous) # signup.js:21
dispatch # jquery-2.1.4.js:4435
elemData.handle # jquery-2.1.4.js:4121
Try to send csrf token as you're trying to send data using the POST method. Inspect the form and you get a hidden input tag of csrf_token, include that in you ajax.
I am trying to pass a JSON object to a view. This view will print out the JSON object in a template. This is just a test to see what data I am passing in Django.
Before the JSON object gets sent, I have javascript that will validate the data being sent. If the validation passes then the data is sent via AJAX.
I currently cannot get anything to be sent to the desired view. I am getting a 403 for the POST.
[22/Dec/2014 21:36:52] "POST /test/ HTTP/1.1" 403 2295
Here is the gist of my code: https://gist.github.com/liondancer/a9df593daeeecce7f180
JS:
$(document).ready(function() {
// Data to describe what kind of test
var testData = {
"timestamp": "",
"hive": 0,
"hdfs": 0,
// Contains a list of testData objects
"beacons":[]
};
var testRun = document.getElementById("test-form");
testRun.addEventListener('submit', function(event) {
event.preventDefault();
var selectedTest = document.querySelector('input[name=test-select]:checked');
alert(selectedTest);
var testType = selectedTest.id;
if (testType == "hdfs-test") {
testData["hdfs"] = 1;
testData["hive"] = 0;
} else if (testType == "hive-test") {
testData["hdfs"] = 0;
testData["hive"] = 1;
} else if (testType == "hdfs-hive-test") {
testData["hdfs"] = 1;
testData["hive"] = 1;
} else {
// null
}
var events = document.getElementById("event-textarea").value;
// check in valid input
var eventSource = events.replace("],[","],,,,[");
// beaconLists allows users to submit --> [{beacon1}, {beacon2}, ...], [{beacon3}, {beacon4}, ...]
var beaconLists = eventSource.split(",,,,");
for (var i = 0; i < beaconLists.length; i++) {
// inspect one list in beaconLists [{beacon1}, {beacon2}, ...]
var beaconList = beaconLists[i];
try {
// list of JSON objects
var beaconObjList = JSON.parse(beaconList);
for (var j = 0; j < beaconObjList.length; j++) {
var beaconObj = beaconObjList[j];
if (beaconObj["data"] && beaconObj["application"]) {
// successful parse to find events
// describe beacon being tested
alert("yes");
var beacon = {
"app_name": beaconObj["application"]["app_name"],
"device": beaconObj["application"]["device"],
"device_id": beaconObj["application"]["device_id"],
"os": beaconObj["application"]["os"],
"os_version": beaconObj["application"]["os_version"],
"browser": beaconObj["application"]["browser"],
"beacon": beaconObj
};
// append to testData
testData["beacons"].push(beacon);
// reset beacon so we can append new beacon later
beacon = {};
} else {
// notify event isn't in the correct format?
alert("no");
}
}
} catch (e) {
// notify bad JSON
alert("failed");
}
}
console.log(testData);
//$.ajaxSetup({
// beforeSend: function(xhr, settings) {
// if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
// xhr.setRequestHeader("X-CSRFToken", csrftoken);
// }
// }
//});
$.ajax({
type: "POST",
url: "/test/",
data: testData,
success: function () {
alert("yay");
},
failure: function () {
alert("boo");
}
});
});
});
html:
{% extends 'index/index.html' %}
{% load staticfiles %}
{% block head %}
<script type="text/javascript" src="{{ STATIC_URL }}home/js/home.js" async></script>
<link href="{{ STATIC_URL }}home/css/home.css" rel="stylesheet">
{% endblock head %}
{% block content %}
<div>Welcome to Trinity E2E testing</div>
<form id="test-form">
{% csrf_token %}
<input id="hdfs-test" type="radio" name="test-select" class="btn btn-default btn-lg">HDFS
<input id="hive-test" type="radio" name="test-select" class="btn btn-default btn-lg">HIVE
<input id="hdfs-hive-test" type="radio" name="test-select" class="btn btn-default btn-lg">BOTH
<textarea id="event-textarea" rows="8" class="form-control" placeholder="Events..."></textarea>
<input id="submit-test" type="submit" class="btn btn-default btn-lg" value="Submit">
</form>
{% endblock content %}
home/views.py:
from django.shortcuts import render
def load_homepage(request):
return render(request, 'home/home_page.html', '')
def scan_events(request):
if request == "POST":
# json = request.POST['testData']
# condition statement for file upload ot c/p events
return render(request, 'home/test.html', {'data': request.POST})
test.html:
{{ data }}
urls.py:
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'parser/', include("parser.urls", namespace="parser")),
url(r'^$', 'home.views.load_homepage', name='home'),
# url(r'form_data', 'parser.views.form_handler', name='')
url(r'test/$', 'home.views.scan_events'),
)
try to send CSRF token
$.ajax({
type: "POST",
url: "/test/",
data: {
csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value, testData,
},
success: function () {
alert("yay");
},
failure: function () {
alert("boo");
}
});
i am working on for a basic feedback system. I just want to submit feedback with ajax, for example if fields are empty ajax will return some error msg and update the div at the same page with no redirection. if everything is ok it will update the feedbacks div with the new one...
Here is my code
models.py
from django.db import models
# Create your models here.
class FeedBack(models.Model):
title = models.CharField(max_length=255)
description = models.TextField()
def __unicode__(self):
return self.title
class Meta:
ordering = ["-title"]
views.py
import json
from django.shortcuts import *
from django.template import RequestContext
from submission.forms import *
def feedback(request):
if request.method == "POST":
form = FeedBackForm(request.POST)
message = 'Oops!'
if(form.is_valid()):
message = request.POST['title']
return HttpResponse(json.dumps({'message': message}))
return render_to_response('index.html',
{'form':FeedBackForm()}, RequestContext(request))
urls.py
from django.conf.urls import patterns, include, url
from submission.views import *
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^feedback/', feedback, name='feed_back'),
)
index.html
<html>
<head>
<script type="text/javascript" src="../static/helper.js"></script>
</head>
<body>
<h1>Leave a Suggestion Here</h1>
<div class="message"></div>
<div>
<form id="feed_form" action="" method="POST">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit Feedback" />
</form>
</div>
</body>
</html>
helper.js
$(document).ready(function() {
$('#feed_form').submit(function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: '', // the file to call
success: function(data) { // on success..
$('.message').html(data); // update the DIV
},
error: function(e, x, r) { // on error..
$('.message').html(e); // update the DIV
}
});
return false;
});
});