Reputation: 57
I am trying to create a simple web app in Django and trying to use Ajax so the page will not refresh. The only goal of this app is to have a form that takes some user input and does not refresh when the form is submitted. However, for some reason this does not happen when I click the button. Here is the Index page:
<!DOCTYPE html>
<html>
<body>
<h2>Create product here</h2>
<div>
<form id="new_user_form">
<div>
<label for="name" > Name:<br></label>
<input type="text" id="name"/>
</div>
<br/>
<div>
<label for="email"> email:<br></label>
<input type="text" id="email"/>
</div>
<div>
<label for="password" > password:<br></label>
<input type="text" id="password"/>
</div>
<div>
<input type="submit" value="submitme"/>
</div>
</form>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type = "text/text/javascript">
$(document).on('submitme', '#new_user_form', function(e)){
e.preventDefault()
$.ajax({
type: 'POST',
url:'/user/create',
data:{
name:$('#name').val(),
email:$('#email').val(),
password:$('#password').val(),
}
success.function(){
alert('created')
}
})
}
</script>
</html>
Here is my main urls.py file:
from django.contrib import admin
from django.urls import path
from django.conf.urls import include, url
from testapp import views
import testapp
from django.views.decorators.csrf import csrf_exempt
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^$', testapp.views.index),
url(r'^user/create/$', csrf_exempt(testapp.views.create_user))
]
My views.py file:
from django.shortcuts import render
from testapp.models import User
from django.http import HttpResponse
# Create your views here.
def index(request):
return render(request, 'index.html')
def create_user(request):
if request.method == 'POST':
name = request.POST['name']
email = request.POST['email']
password = request.POST['password']
User.objects.create(
name = name,
email = email,
password = password
)
return HttpResponse('')
And lastly the models.py file:
from django.db import models
# Create your models here.
class User(models.Model):
name = models.CharField(max_length = 32)
email = models.EmailField()
password = models.CharField(max_length = 128)
The aim of this was when the button is clicked, it should send a POST request to the backend which creates a object of type User and saves it to the database. However, for some reason when I click submit, no POST request is sent according to the Network tool on Chrome. Can someone help me out here?
Upvotes: 3
Views: 12038
Reputation: 67
Try Adding method="POST" and action="{% url 'url_name' %}" to html form. Also add name to url for create user.
Upvotes: 0
Reputation: 11
Not sure how relevant this answer will be. But the only reason why "POST" request is not getting created for you is because you have written in your JS <script type = "text/text/javascript">
instead of <script type = "text/javascript">
Upvotes: 0
Reputation: 1211
Your code looks good but I'd like to help you with the following changes: I edited and updated my post since few parts of my earlier suggestions were not applicable in your case (since ajax contentType was OK in your case and so on...), so I cleared my answer for your purpose:
1.
in the HTML form, the input names should be given at the input fields, since that way easier to submit input HTML Form values with AJAX:
<input type="text" name="name" id="name"/>
<input type="email" name="email" id="email"/>
<input type="password" name="password" id="password"/>
The submit button should be changed like this:
<button type="button" name="submitme" id="submitme">Submit</button>
2.
your AJAX call should be reformulated like this (I think the trailing slash is missing from your url and the data could be in simpler format than you made, and the click function is on button id now. And the closing brackets are cleared on the code:
<script type = "text/text/javascript">
var $ = jQuery.noConflict();
$( document ).ready(function() {
$('#submitme').on('click', function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url:'/user/create/',
data: $('form').serialize(),
success: function(){
alert('created');
}
})
})
});
</script>
And your view should look like this to get the ajax submitted data and save as new User (with very small modification):
def create_user(request):
if request.method == 'POST':
name = request.POST.get('name')
email = request.POST.get('email')
password = request.POST.get('password')
new_user = User.objects.create(
name = name,
email = email,
password = password
)
new_user.save()
return HttpResponse('')
This way it must work now. I hope this will be in help of you.
Upvotes: 0
Reputation: 1213
def create_user(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password')
user = authenticate(username=username, password=raw_password)
auth_login(request, user)
return render(request, 'accounts/index.html')
else:
form = SignUpForm()
return render(request, 'accounts/signup.html', {'form': form})
your code should look more like this. Here I use the default django auth system so there is no real need of your model.py
, at least not for now. Also look at the renders i have added - with the HttpReponse
your page will reload. The email is automatically saved with the form.submit()
The SignUpForm should be simply:
class SignUpForm(UserCreationForm):
email = forms.EmailField(max_length=254, help_text='Required.')
Upvotes: 0