How to integrate Django form with Ajax? - javascript

I've gone through many tutorials in how to integrate ajax with django form but all were complicated. I have a Signup model with Signup form and a views like the following.
models.py
from django.db import models
class SignUp(models.Model):
name = models.CharField(max_length=120, blank=True, null=True)
email = models.EmailField()
def __unicode__(self):
return self.email
and forms.py
from django import forms
from .models import SignUp
class SignUpForm(forms.ModelForm):
class Meta:
model = SignUp
fields = ['name', 'email']
def clean_name(self):
name = self.cleaned_data.get('name')
return name
def clean_email(self):
email = self.cleaned_data.get('email')
try:
match = SignUp.objects.get(email=email)
except SignUp.DoesNotExist:
return email
raise forms.ValidationError('This email address is already subscribed.')
views.py
from django.shortcuts import render
from django.core.mail import send_mail
from django.conf import settings
from .forms import SignUpForm
def index(request):
form = SignUpForm(request.POST or None)
if form.is_valid():
name = form.clean_name()
email = form.clean_email()
instance = form.save()
subject = 'Bruke Church news'
from_email = settings.EMAIL_HOST_USER
to_email = [email]
contact_message = "%s:Thank you for signing up for our newsletter via %s. we'll be in touch" %(
name,
email)
send_mail (subject,
contact_message,
from_email,
to_email,
fail_silently=False)
context = {
"form": form
}
return render(request, "index.html",context)
and my html form looks like this
<form action="" method="POST">
{% csrf_token %}
{{form|crispy}}
<input type="submit" value="Sign up" class="btn btn-primary">
</form>
This code runs well but it loads the full page and I want to load only the form. After googling, I found a concept of Ajax but am really having problem in doing so. please help me Thank you

Example of Ajax Post
on button click submit
this method needs to run
put this in your HTML
function AddData(){
var name = $("#name").val();
var email = $("#email").val();
// You should extract each and every id from your form fields
var signupData = { name:name, csrfmiddlewaretoken: '{{ csrf_token }}',email:email};
$.ajax({
type: "POST",
url: "../../index/",
data: signupData,
success: function(data) {
alert("You Have Sucessfully Signed Up ");
},
statusCode: {
500: function() {
alert("You Have Already Signed Up ");
}
},
})
}
In your Views.py
def index(request):
if request.method == 'POST': # From Frontend we are getting the data in a POST method and we are checking if front end is giving POST Method or not
get_email = request.POST.get('email') # Taking The DATA from front end in form of POST to Django USER EMAIL ADDRESS
get_name = request.POST.get('name')# Taking The DATA from front end in form of POST to Django NAME
queryset_list = SignUp.objects.all().values_list("email",flat=True)# Performing a Django Query and getting all Signup Email Address
if get_email in queryset_list:
return HttpResponse(status=500)
else:
SignUp.objects.create(name=get_name,email=get_email)
return HttpResponse('')

Related

get value from a django form using javascript

I was trying for a long time to figure out how to get the value from a django.form using javascript, however I didn't get any straight answer to it.
here is my project:
views.py:
from django.shortcuts import render, redirect
from .forms import TextForm
from .Functions import GetData
def get_name(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = TextForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
print("is valid")
text = form.cleaned_data['date']
x = GetData(text.day, text.month, text.year)
x.getInfo()
context = {
'text': text,
'form': form,
}
return render(request, 'index.html', context)
# if a GET (or any other method) we'll create a blank form
else:
form = TextForm()
print("not valid")
return render(request, 'index.html', {'form': form})
forms.py
from django import forms
class TextForm(forms.Form):
date = forms.DateField(widget=forms.SelectDateWidget(), label="inputDate")
let's say the html file is very basic, like this:
<form action=" " method="post" id="form">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
SO the main thing, that I need, is to get the date value from the form

Django form is sent but doesent save to database

I´m doing a simple user-business application, where a user has one or many business. The problem is that my create business forms is not saving its data to the database. The user has all the permissions and is active, and I can save data from the create user form with no problem. What is wrong?
View.py:
class crear_negocio(LoginRequiredMixin, FormView):
template_name = "tienda/crear_negocio.html"
form_class= Negocio_Form
success_url = reverse_lazy('tienda_app:crear_negocio')
login_url = reverse_lazy('register_app:logIn')
form.py:
class Negocio_Form(forms.ModelForm):
class Meta:
model = Negocio_Model
fields = ("Nombre_Negocio","Administrador","Descipcion_Negocio",'Correo_Negocio','Telefono_Negocio','Direccion_Negocio')
Model.py:
class Negocio_Model(models.Model):
Nombre_Negocio = models.CharField(max_length=25)
Administrador = models.ForeignKey(Usuario_Model, on_delete=models.CASCADE)
Descipcion_Negocio = models.TextField(null=True, blank=True)
Correo_Negocio = models.EmailField()
Telefono_Negocio = models.CharField(max_length=13)
Direccion_Negocio = models.CharField(max_length=25)
def __str__(self):
return self.Nombre_Negocio+' '+self.Correo_Negocio+' '+self.Telefono_Negocio+' '+self.Direccion_Negocio
Database config:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'bdtg1',
'USER':'juan',
'PASSWORD':'juanjo123',
'HOST':'127.0.0.1',
'PORT':'3306'
}
}
A FormView does not .save() the form, thus it will indeed not create a record at the database. By default in case the form is successful, it redirects to the success URL, that's all. A typical use case of a FormView is for example to send an email instead of saving it to the database.
You can override the form_valid(…) method [Django-doc] to save the form, but it might be better to make use of a CreateView [Django-doc]:
from django.views.generic.edit import CreateView
class crear_negocio(LoginRequiredMixin, CreateView):
template_name = 'tienda/crear_negocio.html'
form_class= Negocio_Form
success_url = reverse_lazy('tienda_app:crear_negocio')
login_url = reverse_lazy('register_app:logIn')

How to after django form is submitted to be redirected to another webpage and have form data to be sent to backend database

Aim: for when django form is submitted for data to be sent and saved to admin side.
problem: i can redirect it to another page after form is submitted but when i go onto admin side the data is not saved. how can i fix this? using django or javascript?
html:
<form method="post" >
{% csrf_token %}
{{form.as_p}}
<input class="btn" type="submit" value="Log In">
</form>
models.py:
from django.db import models
from django import forms
class Customer(models.Model):
first_name = models.CharField(max_length=200, verbose_name='')
last_name = models.CharField(
max_length=200, verbose_name='')
def __str__(self):
return self.first_name + ', ' + self.last_name
forms.py:
from django.forms import ModelForm
from django import forms
from .models import Customer
class CustomerForm(ModelForm):
class Meta:
model = Customer
fields = '__all__'
views.py:
from django.shortcuts import render
from .forms import CustomerForm
def index(request):
form = CustomerForm()
if request.method == 'POST':
form = CustomerForm(request.POST)
if form.is_valid():
form.save()
context = {'form': form}
return render(request, 'app/index.html', context)
Ash this is what it gives me:
if you need any other files just ask
the redirect error i get
After writing form.save() you can say:
return redirect(link to redirect to)
This will redirect you to the chosen place after the form is validated and saved.
Add one line after your form will save
# put link inside -> " "
return redirect("Link")
Change the html as method="POST"
if request.method == 'POST':
form = CustomerForm(request.POST)
if form.is_valid():
form.save()
return redirect('urlname')
else:
form = CustomerForm()
context = {'form': form}
return render(request, 'app/index.html', context)

POST request to "/" returns a 403 forbidden

I am trying to send an a 320 character text post through a POST request to the / route. In that route I have a Twitter-like social network website for making posts and following users. To make and write posts I want it to be asynchronous, i mean, i want the user to write a post and when he presses the button to post it, there shouldn't be a page reload.
This is my html file:
<div class="container">
<h1>All Posts</h1>
<div class="row">
<div class="span12 well">
<form method="post">
{% csrf_token %}
<textarea class="span11" id="new_message" name="new_message"
placeholder="Write something nice" rows="5"></textarea>
<h6 id="characters">320 characters remaining</h6>
<button class="btn btn-info" type="submit">Post New Message</button>
</form>
</div>
</div>
</div>
This is what I'm trying to do in JavaScript, but i'm getting a 403:
document.querySelector("form").onsubmit = () => {
//sending values by POST method
fetch('/', {
method: 'POST',
body: JSON.stringify({
content: document.querySelector('#new_message').value,
})
})
.then(response => response.json())
.then(result => {
// Print result
console.log(result);
})
event.preventDefault()
}
});
I'm also not very sure if this is the correct way to do it.
Backend:
def index(request):
if request.method == "POST":
content = request.POST["new_message"]
print(request.user)
print(content)
return render(request, "network/index.html")
#post = Posts(user=request.user, content=content)
return render(request, "network/index.html")
def login_view(request):
if request.method == "POST":
# Attempt to sign user in
username = request.POST["username"]
password = request.POST["password"]
user = authenticate(request, username=username, password=password)
# Check if authentication successful
if user is not None:
login(request, user)
return HttpResponseRedirect(reverse("index"))
else:
return render(request, "network/login.html", {
"message": "Invalid username and/or password."
})
else:
return render(request, "network/login.html")
def logout_view(request):
logout(request)
return HttpResponseRedirect(reverse("index"))
def register(request):
if request.method == "POST":
username = request.POST["username"]
email = request.POST["email"]
# Ensure password matches confirmation
password = request.POST["password"]
confirmation = request.POST["confirmation"]
if password != confirmation:
return render(request, "network/register.html", {
"message": "Passwords must match."
})
# Attempt to create new user
try:
user = User.objects.create_user(username, email, password)
user.save()
except IntegrityError:
return render(request, "network/register.html", {
"message": "Username already taken."
})
login(request, user)
return HttpResponseRedirect(reverse("index"))
else:
return render(request, "network/register.html")
Since 403 means forbidden I would try to check the permissions of the entity that you are trying to call. Make sure that the proper file has execute permissions from the right level. Check your error log through either apache or other flavor of web server your using and the access log might find something there. Also, in your JS you are logging something to the console, what does JS push to the console?

Ajax POST method to Django. Always results in "Not Ajax"

I have been trying to create an AJAX function which sends two JS variables, Score and Mistake, back to the Django backend and to update an extended user model with them.
To do this I started with an AJAX function which looks like this:
$(document).ready(function() {
$("#test").submit(function(event){
event.preventDefault();
console.log("form submitted!");
$.ajax({
type:"POST",
url:"/update/quiz/",
data: {
csrfmiddlewaretoken: window.CSRF_TOKEN,
'score': score,
'mistake' : mistake
},
success: function(){
$('#message').html("<h2>Contact Form Submitted!</h2>")
}
});
return false;
});
});
Views.py
class Quiz(TemplateView):
template_name='quiz.html'
def post(self, request, *args, **kwargs):
if request.is_ajax():
message = "Yes, Ajax!"
else:
message = "Not Ajax!"
return HttpResponse(message)
URLS.py
from django.urls import path
from home.views import HomepageName, Homepage, Quiz
from . import views
urlpatterns = [
path('quiz/', Quiz.as_view()),
path('update/quiz/', Quiz.post),
path('<slug:slug>/', HomepageName.as_view()),
path('', Homepage.as_view()),
]
And the template
<form method='POST' id ='test'>
{% csrf_token %}
<input type='submit' value='Test button'/>
<div id = 'message'>Initial text</div>
</form>
I've already tried to move around the URL routing and add a new URL thinking that would work but when the Submit button is clicked then it always loads a new page and then on that page it shows "Not Ajax!"
I assume that it is doing the default HTML form action and not the AJAX since their is no output to the console either which I added to get some more information
Thanks for all your help. Please comment if I need to provide more information!

Categories

Resources