Django Post request not sent on button click











up vote
3
down vote

favorite
1












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?










share|improve this question
























  • $(document).on('submitme', '#new_user_form', function(e)){- this doesn't look right, surely the first argument should be 'click'?
    – Robin Zigmond
    Nov 8 at 14:59












  • Hi tried this : $('#submit').click(function()) instead of the previous header but it did not make a difference and no POST request is sent either
    – faboys
    Nov 8 at 15:08










  • That will only work if you give the submit button id="submit"
    – Robin Zigmond
    Nov 8 at 15:18










  • Yes did that, still no post request is sent.
    – faboys
    Nov 8 at 15:23















up vote
3
down vote

favorite
1












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?










share|improve this question
























  • $(document).on('submitme', '#new_user_form', function(e)){- this doesn't look right, surely the first argument should be 'click'?
    – Robin Zigmond
    Nov 8 at 14:59












  • Hi tried this : $('#submit').click(function()) instead of the previous header but it did not make a difference and no POST request is sent either
    – faboys
    Nov 8 at 15:08










  • That will only work if you give the submit button id="submit"
    – Robin Zigmond
    Nov 8 at 15:18










  • Yes did that, still no post request is sent.
    – faboys
    Nov 8 at 15:23













up vote
3
down vote

favorite
1









up vote
3
down vote

favorite
1






1





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?










share|improve this question















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?







python jquery django post web-applications






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 8 at 15:02









nosklo

150k46247268




150k46247268










asked Nov 8 at 14:57









faboys

161




161












  • $(document).on('submitme', '#new_user_form', function(e)){- this doesn't look right, surely the first argument should be 'click'?
    – Robin Zigmond
    Nov 8 at 14:59












  • Hi tried this : $('#submit').click(function()) instead of the previous header but it did not make a difference and no POST request is sent either
    – faboys
    Nov 8 at 15:08










  • That will only work if you give the submit button id="submit"
    – Robin Zigmond
    Nov 8 at 15:18










  • Yes did that, still no post request is sent.
    – faboys
    Nov 8 at 15:23


















  • $(document).on('submitme', '#new_user_form', function(e)){- this doesn't look right, surely the first argument should be 'click'?
    – Robin Zigmond
    Nov 8 at 14:59












  • Hi tried this : $('#submit').click(function()) instead of the previous header but it did not make a difference and no POST request is sent either
    – faboys
    Nov 8 at 15:08










  • That will only work if you give the submit button id="submit"
    – Robin Zigmond
    Nov 8 at 15:18










  • Yes did that, still no post request is sent.
    – faboys
    Nov 8 at 15:23
















$(document).on('submitme', '#new_user_form', function(e)){- this doesn't look right, surely the first argument should be 'click'?
– Robin Zigmond
Nov 8 at 14:59






$(document).on('submitme', '#new_user_form', function(e)){- this doesn't look right, surely the first argument should be 'click'?
– Robin Zigmond
Nov 8 at 14:59














Hi tried this : $('#submit').click(function()) instead of the previous header but it did not make a difference and no POST request is sent either
– faboys
Nov 8 at 15:08




Hi tried this : $('#submit').click(function()) instead of the previous header but it did not make a difference and no POST request is sent either
– faboys
Nov 8 at 15:08












That will only work if you give the submit button id="submit"
– Robin Zigmond
Nov 8 at 15:18




That will only work if you give the submit button id="submit"
– Robin Zigmond
Nov 8 at 15:18












Yes did that, still no post request is sent.
– faboys
Nov 8 at 15:23




Yes did that, still no post request is sent.
– faboys
Nov 8 at 15:23












2 Answers
2






active

oldest

votes

















up vote
0
down vote













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.')





share|improve this answer























  • Just tried this solution, still no POST request is sent from the submit button. I also don't understand what you mean by no need for Models.py - without the database where would the data be saved?
    – faboys
    Nov 8 at 15:26










  • docs.djangoproject.com/en/2.1/topics/auth/default look at the django docs for this, it will make it clearer how it works in the Django world I think
    – Karina K
    Nov 8 at 15:32










  • Also, models.py is diffrent from the database. It's like an explanation of what should the columns of a table in the database be.
    – Karina K
    Nov 8 at 15:41










  • Models.py creates the tables in the database when the migrate commands are run is my understanding. However, my main problem with this is the Post command is not being sent when the button is clicked and there's no obvious reason why its doing this and the solutions suggested here havent worked so far for me
    – faboys
    Nov 8 at 15:55


















up vote
0
down vote













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.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














     

    draft saved


    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53210329%2fdjango-post-request-not-sent-on-button-click%23new-answer', 'question_page');
    }
    );

    Post as a guest
































    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote













    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.')





    share|improve this answer























    • Just tried this solution, still no POST request is sent from the submit button. I also don't understand what you mean by no need for Models.py - without the database where would the data be saved?
      – faboys
      Nov 8 at 15:26










    • docs.djangoproject.com/en/2.1/topics/auth/default look at the django docs for this, it will make it clearer how it works in the Django world I think
      – Karina K
      Nov 8 at 15:32










    • Also, models.py is diffrent from the database. It's like an explanation of what should the columns of a table in the database be.
      – Karina K
      Nov 8 at 15:41










    • Models.py creates the tables in the database when the migrate commands are run is my understanding. However, my main problem with this is the Post command is not being sent when the button is clicked and there's no obvious reason why its doing this and the solutions suggested here havent worked so far for me
      – faboys
      Nov 8 at 15:55















    up vote
    0
    down vote













    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.')





    share|improve this answer























    • Just tried this solution, still no POST request is sent from the submit button. I also don't understand what you mean by no need for Models.py - without the database where would the data be saved?
      – faboys
      Nov 8 at 15:26










    • docs.djangoproject.com/en/2.1/topics/auth/default look at the django docs for this, it will make it clearer how it works in the Django world I think
      – Karina K
      Nov 8 at 15:32










    • Also, models.py is diffrent from the database. It's like an explanation of what should the columns of a table in the database be.
      – Karina K
      Nov 8 at 15:41










    • Models.py creates the tables in the database when the migrate commands are run is my understanding. However, my main problem with this is the Post command is not being sent when the button is clicked and there's no obvious reason why its doing this and the solutions suggested here havent worked so far for me
      – faboys
      Nov 8 at 15:55













    up vote
    0
    down vote










    up vote
    0
    down vote









    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.')





    share|improve this answer














    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.')






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 8 at 15:37

























    answered Nov 8 at 15:06









    Karina K

    344416




    344416












    • Just tried this solution, still no POST request is sent from the submit button. I also don't understand what you mean by no need for Models.py - without the database where would the data be saved?
      – faboys
      Nov 8 at 15:26










    • docs.djangoproject.com/en/2.1/topics/auth/default look at the django docs for this, it will make it clearer how it works in the Django world I think
      – Karina K
      Nov 8 at 15:32










    • Also, models.py is diffrent from the database. It's like an explanation of what should the columns of a table in the database be.
      – Karina K
      Nov 8 at 15:41










    • Models.py creates the tables in the database when the migrate commands are run is my understanding. However, my main problem with this is the Post command is not being sent when the button is clicked and there's no obvious reason why its doing this and the solutions suggested here havent worked so far for me
      – faboys
      Nov 8 at 15:55


















    • Just tried this solution, still no POST request is sent from the submit button. I also don't understand what you mean by no need for Models.py - without the database where would the data be saved?
      – faboys
      Nov 8 at 15:26










    • docs.djangoproject.com/en/2.1/topics/auth/default look at the django docs for this, it will make it clearer how it works in the Django world I think
      – Karina K
      Nov 8 at 15:32










    • Also, models.py is diffrent from the database. It's like an explanation of what should the columns of a table in the database be.
      – Karina K
      Nov 8 at 15:41










    • Models.py creates the tables in the database when the migrate commands are run is my understanding. However, my main problem with this is the Post command is not being sent when the button is clicked and there's no obvious reason why its doing this and the solutions suggested here havent worked so far for me
      – faboys
      Nov 8 at 15:55
















    Just tried this solution, still no POST request is sent from the submit button. I also don't understand what you mean by no need for Models.py - without the database where would the data be saved?
    – faboys
    Nov 8 at 15:26




    Just tried this solution, still no POST request is sent from the submit button. I also don't understand what you mean by no need for Models.py - without the database where would the data be saved?
    – faboys
    Nov 8 at 15:26












    docs.djangoproject.com/en/2.1/topics/auth/default look at the django docs for this, it will make it clearer how it works in the Django world I think
    – Karina K
    Nov 8 at 15:32




    docs.djangoproject.com/en/2.1/topics/auth/default look at the django docs for this, it will make it clearer how it works in the Django world I think
    – Karina K
    Nov 8 at 15:32












    Also, models.py is diffrent from the database. It's like an explanation of what should the columns of a table in the database be.
    – Karina K
    Nov 8 at 15:41




    Also, models.py is diffrent from the database. It's like an explanation of what should the columns of a table in the database be.
    – Karina K
    Nov 8 at 15:41












    Models.py creates the tables in the database when the migrate commands are run is my understanding. However, my main problem with this is the Post command is not being sent when the button is clicked and there's no obvious reason why its doing this and the solutions suggested here havent worked so far for me
    – faboys
    Nov 8 at 15:55




    Models.py creates the tables in the database when the migrate commands are run is my understanding. However, my main problem with this is the Post command is not being sent when the button is clicked and there's no obvious reason why its doing this and the solutions suggested here havent worked so far for me
    – faboys
    Nov 8 at 15:55












    up vote
    0
    down vote













    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.






    share|improve this answer



























      up vote
      0
      down vote













      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.






      share|improve this answer

























        up vote
        0
        down vote










        up vote
        0
        down vote









        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.






        share|improve this answer














        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.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited 22 hours ago

























        answered Nov 9 at 8:47









        Zollie

        28615




        28615






























             

            draft saved


            draft discarded



















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53210329%2fdjango-post-request-not-sent-on-button-click%23new-answer', 'question_page');
            }
            );

            Post as a guest




















































































            Popular posts from this blog

            Florida Star v. B. J. F.

            Danny Elfman

            Lugert, Oklahoma