get value from a django form using javascript - 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

Related

How to add default value for Date Picker in Django Model Form

Currently I have a date picker in a django model form that works perfectly fine. However, I want to add an initial (default) value to it. Here is my current code :
class DatePickerInput(forms.DateInput):
input_type = 'date'
class PDFClassificationForm(forms.ModelForm):
class Meta:
model = Documents
fields = [
'id_documenttype',
'dateenvoi',,
'comment']
widgets = {
'dateenvoi' : DatePickerInput(),
}
I tried adding initial as a parameter to DatePickerInput() like so :
widgets = {
'dateenvoi' : DatePickerInput(initial= datetime.now().strftime('%d/%m/%y %H:%M:%S')),
}
However it was unsuccessful, any suggestions ?
Try this:
import datetime
class PDFClassificationForm(forms.ModelForm):
class Meta:
model = Documents
fields = [
'id_documenttype',
'dateenvoi',
'comment',
]
widgets = {
'dateenvoi' : DatePickerInput(widget=forms.TextInput(attrs={'value': datetime.now().strftime('%d/%m/%y %H:%M:%S')})),
}
try adding your desired initial value to the form in the view (views.py)
import datetime
from django.views.generic import TemplateView
from .forms import PDFClassificationForm
class YourView(TemplateView):
template_name = 'your_directory/your_template_name.html'
form_class = PDFClassificationForm
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
return render(request, self.template_name, {'form': form})
def get_context_data(self, *args, **kwargs):
context = super(YourView, self).get_context_data(*args, **kwargs)
request = self.request
context["form"] = PDFClassificationForm(request.POST or None, initial={ "dateenvoi": datetime.today)
return context

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)

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!

django messages for a successfully delete,add or edit item

I have started using django messages for creating items.
It works great for creating adding a new item.
but.. I want to have functions for each action -
delete,create,edit ( I have different buttons for each)
I have only post function.. it really confuse me when I try to create a message that the item has been deleted successfuly.. how can I know a delete was submitted and not post? since everything goes through post function.
The PostEdit and Delete don't have the "request" that it requires for messages.
So for now I h ave only messages.succuess that runs everytime I create a server.
I want to have a different message for delete, edit, create and same for errors.
Does anyone have a clue?
index.html -
{% if messages %}
<ul class="messages">
{% for message in messages %}
<div class="alert alert-success alert-dismissible fade show" role="alert">
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
{% endfor %}
</ul>
{% endif %}
views.py -
# Create your views here.
from django.shortcuts import render_to_response
from django.shortcuts import get_object_or_404
from django.shortcuts import render, redirect
from django.template import RequestContext
from django.views.generic import TemplateView, UpdateView, DeleteView, CreateView
from DevOpsWeb.forms import HomeForm
from DevOpsWeb.models import serverlist
from django.core.urlresolvers import reverse_lazy
from simple_search import search_filter
from django.db.models import Q
from django.contrib import messages
class HomeView(TemplateView):
template_name = 'serverlist.html'
def get(self, request):
form = HomeForm()
query = request.GET.get("q")
posts = serverlist.objects.all()
forms = {}
if query:
posts = serverlist.objects.filter(Q(ServerName__icontains=query) | Q(Owner__icontains=query) | Q(Project__icontains=query) | Q(Description__icontains=query) | Q(IP__icontains=query) | Q(ILO__icontains=query) | Q(Rack__icontains=query))
else:
posts = serverlist.objects.all()
for post in posts:
forms[post.id] = HomeForm(instance=post)
args = {'form' : form,'forms': forms, 'posts' : posts}
return render(request, self.template_name, args)
def post(self,request):
form = HomeForm(request.POST)
posts = serverlist.objects.all()
forms = {}
if form.is_valid(): # Checks if validation of the forms passed
post = form.save(commit=False)
post.save()
messages.success(request,'{0} has been added successfully!'.format(post.ServerName))
return redirect('serverlist')
messages.error(request,'Servername is required, please refresh the page and try again.')
for post in posts:
forms[post.id] = HomeForm(instance=post)
args = {'form' : form, 'forms': forms, 'posts' : posts}
return render(request, self.template_name,args)
class PostDelete(DeleteView):
model = serverlist
success_url = reverse_lazy('serverlist')
class PostEdit(UpdateView):
template_name = 'serverlist.html'
model = serverlist
form_class = HomeForm
#messages.success(request,"The server has been edited successfully")
#fields = ['ServerName','Owner','Project','Description','IP','ILO','Rack','Status']
success_url = reverse_lazy('serverlist')
Override the delete method in the deleteview for changing the message type:
class PostDelete(SuccessMessageMixin, DeleteView):
model = serverlist
success_url = reverse_lazy('serverlist')
success_message = "Object deleted"
def delete(self, request, *args, **kwargs):
messages.warning(self.request, self.success_message)
return super(PostDelete, self).delete(request, *args, **kwargs)
You can do the same by overriding the update method for UpdateView.
class PostEdit(UpdateView):
template_name = 'serverlist.html'
model = serverlist
form_class = HomeForm
#messages.success(request,"The server has been edited successfully")
You can't call messages.success in the class definition like that. The call has to go in a method like post or form_valid.
The messages framework has a SuccessMessageMixin which you might find useful. You add the mixin to each view, and set success_message:
class PostDelete(SuccessMessageMixin, DeleteView):
model = serverlist
success_url = reverse_lazy('serverlist')
success_message = "Object deleted"
See the docs on adding messages to class-based views for more info.

How to integrate Django form with Ajax?

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

Categories

Resources