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)
Related
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.
So i have got my html and i would like to add my django view in div "radio2".
I am using JQuery function Load() but i have a problem because it returns error 404 with get request "http://127.0.0.1:8000/post/afafa/%7B%" and its not loading nothing in div
post_detail.html
<div class="post__recommendation__posts">
<div id="radio2" class="radio2">
</div>
{% for post in posts|slice:":3" %}
<div class="post__recommendation__post">
<div class="post__recommendation__post-image">
<img src={% static post.image.url %} alt="shakhur" />
</div>
<div class="post__recommendation__post-description">{{post.short_description}}</div>
</div>
{% endfor %}
</div>
Js function
$(document).ready(function (){
console.log("Loading page")
$(".radio-btn").click(function(){
console.log("radio - btn")
console.log($(this)[0].id)
$.ajax({
url: "/radio/",
type: 'POST',
data:{
radio: "radio",
input: $(this)[0].id
},
success: update_item()
})
})
})
function update_item() {
$('#radio2').load(
"{% url 'radio2' %}"
);
}
View
#csrf_exempt
def radio_test(request):
return render(request, 'blogapp/radio2.html')
radio2.html
<div class="radiodiv">
This is Radio2
</div>
my results in console
Not Found: /post/afafa/{%
[28/Sep/2020 15:52:19] "GET /post/afafa/%7B% HTTP/1.1" 404 3938
[28/Sep/2020 15:52:19] "POST /radio/ HTTP/1.1" 200 79
[28/Sep/2020 15:52:22] "GET /post/afafa/ HTTP/1.1" 200 10761
It seems that you're trying to use Django's templating engine in a static file.
This will not work because static files are not passed into the templating engine.
There are work-arounds. Easiest is to create a global variable in the main template and pass that into load:
<script>
var radio2_url = "{% url 'radio2' %}";
</script>
Put this before your other script.
Then in your js:
function update_item() {
$('#radio2').load(radio2_url);
}
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 let the user select x and y coordinates from an image using cropper.js and pass the data with using ajax to the next view. I am using Django 1.9.4. I am also not really practiced with Javascript, the Javascript part is not written by me.
Using the Firefox Dev Tools Network Tab I seem to get a 500 Internal Server Error. In the Dev Tools view the request has the needed JSON data. However Django does not seem to work the request properly. Why?
Relevant part from views.py:
def render_stl(request):
print("Got to STL render")
if request.method == 'POST':
print("BELOW DATA")
print(request.POST) # <QueryDict: {}>
print(request.is_ajax()) # False
print(request.POST.__dict__) # {'_encoding': 'utf-8', '_mutable': False}
# This is old from a former version, but should be updated if ajax works
x_start = request.POST.get("x_start")
z_start = request.POST.get("z_start")
x_end = request.POST.get("x_end")
z_end = request.POST.get("z_end")
print(x_start, z_start, x_end, z_end)
run_stl_render(x_start, z_start, x_end, z_end)
# os.chdir(settings.MEDIA_ROOT)
stl_file = open(settings.MEDIA_ROOT + "/mySTL.stl", "r")
django_file = File(stl_file)
return render(request, 'img_crop/render_stl.html', {'django_file': django_file})
urls.py:
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^render_img$', views.upload_file, name='render_img'),
url(r'^render_stl$', views.render_stl, name='render_stl'),
url(r'^download_stl$', views.download_stl, name='download_stl'),
# url(r'^media/mySTL.stl', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
]
Javascript (the csrftoken is defined in another function):
sendDataOfCroppedImage = function(dataOfCroppedImage) {
// var data = 'data : [' + JSON.stringify(dataOfCroppedImage) + ']';
var data_s = JSON.stringify(dataOfCroppedImage);
console.log('data',data_s);
$.ajax({
async: true,
crossDomain: true,
method: 'POST',
data: data_s,
dataType: 'json',
headers: {
'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest',
'content-type': 'application/json',
'cache-control': 'no-cache',
'X-CSRFToken': csrftoken
},
url: 'render_stl',
success: function () {
console.log('sendDataOfCroppedImage okay');
}
});
},
The template:
<html>
{% load staticfiles %}
<head>
<title>
Your rendered image
</title>
<script src="{% static 'img_crop/js/jquery-3.2.1.js' %}"></script>
<script src="{% static 'img_crop/js/cookie.js' %}"></script>
<script src="{% static 'img_crop/js/cropper.js' %}"></script>
<link href="{% static 'img_crop/css/cropper.css' %}" rel="stylesheet">
<style>
#image {
max-width: 100%;
}
</style>
</head>
<body>
<h1>Hier ist das generierte Bild aus Ihrer Welt!</h1>
<h2>Wählen Sie nun Ihren Bereich aus: </h2>
<div style="overflow: hidden; width: 400px; height: calc(400px / 16 * 9);">
<div>
<img id="image" src="{% static "img_crop/MC2px.png" %}" alt="Rendered image"/>
</div>
</div>
<button id="getDataBtn" class="button get-data">Submit Choice</button>
request.POST is only for form-encoded data. If you are sending json encoded data then you should access request.body instead.
data = json.loads(request.body.decode('utf-8'))
If you get a 500 error with DEBUG=True, then you should be able to see the traceback using your browser dev tools. If DEBUG=False, then look in your logs or the error email sent to the site admins.
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;
});
});