Submitting form after JS logic in Django - javascript

I have a form that enables user input. Upon submit, some javascript will perform some logic to be passed to /test/ URL. Right now the issue is that I am not being redirected to/test/ URL.
JS:
$(document).ready(function() {
var testRun = document.getElementById("test-form");
testRun.addEventListener('submit', function(event) {
testData["timestamp"] = new Date().getTime();
event.preventDefault();
// more logic
return jsonData;
});
});
home_page.html
<form id="test-form" action="/test/" method="post"> {# pass data to /test/ URL #}
{% csrf_token %}
<div class="test-button-set">
<button type="button" id="hdfs-test" class="btn btn-default btn-lg selected">HDFS</button>
<button type="button" id="hive-test" class="btn btn-default btn-lg">HIVE</button>
<button type="button" id="hdfs-hive-test" class="btn btn-default btn-lg">BOTH</button>
</div>
{{ form.event_textarea }}
<button id="submit-test" type="submit" class="btn btn-default btn-lg">Submit</button>
</form>
forms.py
class TestForm(forms.Form):
event_textarea = forms.CharField(widget=forms.Textarea(attrs={'rows': '8', 'class': 'form-control', 'placeholder': 'Events...', 'id': 'event-textarea'}))
views.py
from django.shortcuts import render
from forms import TestForm
from django.http import HttpResponseRedirect
def home(request):
if request == 'POST':
# create a form instance and populate it with data from the request
form = TestForm(request.POST)
if form.is_valid():
# process the data in form.cleaned_data as required
form.cleaned_data()
# redirect to a new URL:
return HttpResponseRedirect('/test/')
# if a GET (or any other method) we'll create a blank form
else:
form = TestForm()
return render(request, 'home/home_page.html', {'form': form})
def test(request):
return render(request, 'home/test.html', {'post': request.POST})
My /test/ url is made to display the post request so I can see for sure what I am posting. Currently the JS logic (I've set up indicators of the output) is working but I am not being redirected so I'm not sure if anything is getting posted to the URL

This line will prevent the default event (the form submission) from happening:
event.preventDefault();
Remove that and the form should submit as expected.

Related

Django modal forms with ajax tables

I am using modal forms with django ajax tables:
https://pypi.org/project/django-bootstrap-modal-forms/
https://pypi.org/project/django-ajax-tables/
How can I update data asychronously by the modal form?
Here is some example code:
Registered Views:
def index(request):
return render(request, 'proto/index.html')
class BookTableView(View):
model = Books
my_table = BooksTable
def get(self, request):
data = self.model.objects.all()
#filtering
table = self.my_table(data)
RequestConfig(request, paginate = {"per_page": 6, "paginator_class": LazyPaginator}).configure(table)
return HttpResponse(table.as_html(request))
class BookUpdateView(BSModalUpdateView):
model = Books
template_name = 'proto/books/update_book.html'
form_class = BookModelForm
success_message = 'Success: Book was updated.'
success_url = reverse_lazy('index')
Table:
class BooksTable(tables.Table):
column1 = tables.TemplateColumn(verbose_name='Read',
template_name='proto/columns/column1.html',
orderable=False)
column2 = tables.TemplateColumn(verbose_name='Update',
template_name='proto/columns/column2.html',
orderable=False)
class Meta:
model = Books
Column2 html template button
<button type="button" class="update-book btn btn-sm btn-primary" data-form-url="{% url 'update_book' record.id %}" onclick="updateBookModalForm()">
<span class="fa fa-pencil"></span>
Close update buttons on update_book.html modal form
<button type="button" class="close" data-dismiss="modal" aria-label="Close" onclick="update_books_id('', '/proto/books')">
<span aria-hidden="true">×</span>
</button>
...
<div class="modal-footer">
<button type="button" class="submit-btn btn btn-primary">Update</button>
</div>
Calling ajax tables on index.html and javascript for modals :
...
<div class="col-12 mb-3">
{% ajax_table "books_id" "books" %}
</div>
<script>
function updateBookModalForm() {
$(".update-book").each(function () {
$(this).modalForm({
formURL: $(this).data("form-url"),
asyncUpdate: true,
asyncSettings: {
closeOnSubmit: false,
successMessage: asyncSuccessMessageUpdate,
dataUrl: "books/",
dataElementId: "#books-table",
dataKey: "table",
addModalFormFunction: updateBookModalForm
}
});
});
}
updateBookModalForm();
</script>
Surprisingly this works and appears assyncronouse on the frontend even not adding a books/ url, but I get a Not Found proto/books on terminal as expected. My question is how to make the update asynchronous on the ajax table without redirecting to the homepage. I really have tried a lot of things with the javascript function, but any modifications I make, mostly taking things out makes it break the update. Really just making the update is enough, what i want is no redirection after the update or any advice on what is the best way to go from here.
Thank you for your time.
reivaJ

Pop up message in Django

I have a form in Django where I upload many files and then perform some data processing on those files. I want to display a loader message while it's still processing in the backend.
I know we can use messages in django but it only shows after the processing is complete, I want to display a little animation while data is being processed. I didn't use ajax to post the form since it was easier with the simple method.
Is there any other way to achieve this?
Forms.py
class UploadFileForm(forms.Form):
file_A = forms.FileField(label= "Upload File-A ")
file_B = forms.FileField(label= "Upload File-B ")
year = forms.IntegerField()
Views.py
def display_uploadpage(request):
if request.method == 'POST':
form = BudgetForm(request.POST, request.FILES)
if form.is_valid():
file_A = form.cleaned_data["file_A"]
file_B = form.cleaned_data["file_B"]
year = form.cleaned_data["year"]
fs = FileSystemStorage()
file_A_name = fs.save(file_A.name, file_A)
file_B_name = fs.save(file_B.name, file_B)
p = ProcessData(year, file_A,file_A_name, file_B, file_B_name)
msg = p.process()
messages.info(request, msg )
return render(request, 'website/upload.html')
else:
form = UploadFileForm()
context = {'form': form}
return render(request, 'website/upload.html', context)
upload.html
<form method="post" enctype="multipart/form-data"> <!-- form method -->
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-danger" id="upload">Upload</button>
</form>
I wanted to add this animation in the page while it's still processing.

Error while sending JavaScript generated image to Django ModelForm

I’m trying to use https://github.com/szimek/signature_pad to attach a signature to a form and send it to the server. I’ve been able to successfully upload images with a standard ImageField, and have also used szimek/signature_pad to download the signature. But when I try to get the signature to the server, I get "(Hidden field signature) No file was submitted. Check the encoding type on the form." So I think I’m at least successfully sending an image to the field, but am not sure how to encode it.
HTML
<form id="form" action="{% url ‘my_app:testFormPage' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<div id="signature-pad">
<canvas></canvas><br>
</div>
 <input type="hidden" name="signature" value=“signatureImage”>
<button type="submit" data-action="formSig">Submit</button>
</form>

Python
# Models.py
class testModel(models.Model):
name = models.CharField(max_length=50)
date = models.DateTimeField(default=timezone.now)
signature = models.ImageField (null=True, max_length=3000)
# Forms.py
class testForm(forms.ModelForm):
class Meta:
model = testModel
fields = ‘__all__’
widgets = { 'signature': forms.HiddenInput(),}
# Views.py
def testFormPage(request):
if request.method == 'POST':
form = testForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('/thanks/')
else:
form = testForm()
context = {'form': form}
return render(request, 'client_visits/testFormPage.html', context)
Javascript

The full javascript app can be found at https://github.com/szimek/signature_pad/tree/master/docs/js. Here’s just what I added
var formSig = wrapper.querySelector("[data-action=formSig]");
formSig.addEventListener("submit", function (event) {
var signatureImage = signaturePad.toDataURL();
});

Jquery Modal Confirmation on Django form submit for deletion of object

I am using Django with Crispy forms and am also using the Shopify Embedded Apps SDK. I am trying to have a modal window appear to let the user confirm that they want to delete an object.
My code is attached so far. I have the modal window appearing with the following code, however, the form is not submitted (and the object is not deleted) after the user selects 'delete' on the modal window:
It just closed the modal and nothing happens.
I have tried various methods from around the net, but haven't had any luck.
form.py
class MyForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.helper = FormHelper(self)
self.helper.form_id = 'edit_form'
self.helper.layout = Layout(
[... some input fields...]
)
# Add delete button
self.helper.layout.append(Button('delete', 'delete'))
# Normal submit button
self.helper.layout.append(Submit('save', 'save'))
views.py
#login_required
def edit_object(request, *args, **kwargs):
# Form handling logic
with request.user.session:
object = get_object_or_404(models.Object, pk=kwargs['object_id'], ...)
if request.method == "POST":
form = forms.MyForm(request.POST, request=request, instance=object)
if not form.is_valid():
[... do some stuff ...]
if form.is_valid():
# If the save button is pressed
if request.POST.get('save'):
[... do some stuff to save and redirect to url of my choice ...]
# If the delete button is pressed <<<< The Modal should appear prior to this
if request.POST.get('delete'):
[... delete to object and redirect to url of my choice ... ]
else:
form = forms.MyForm(request=request, instance=supplier)
return render(request, 'template.html', {'form': form})
template.html using Shopify Embedded App SDK:
<script type="text/javascript">
[...]
ShopifyApp.ready(function() {
ShopifyApp.Bar.initialize({});
$("#button-id-delete").click(function(ev){
ShopifyApp.Modal.confirm({message: "Are you sure you want to delete?"}, function(result){
if(!result){
result.preventDefault();
}
else {
alert("Contine");
$("form#edit_form").submit();
}
});
});
});
</script>
<form enctype="multipart/form-data" method="post">
{% crispy form %}
</form>
rendered html
<form enctype="multipart/form-data" method="post">
<form id="edit_form" method="post" > <input type='hidden' name='csrfmiddlewaretoken' value='.......' />
[.... various input fields .....]
<input type="button"
name="delete"
value="delete"
class="btn destroy btn"
id="button-id-delete"
/>
<input type="submit"
name="save"
value="save"
class="btn btn-primary"
id="submit-id-save"
/>
</form>
</form>
Your delete button (<input type="button" name="delete"...) never gets sent.
A quick way for you to have debugged this would have been to examined the request.POST variable in django in your view.
Here you are submitting the form programmatically and so the "delete" never gets received.
else {
alert("Contine");
$("form#edit_form").submit();
}
I'd recommend either adding a field to the form via javascript before it gets submitted:
else {
alert("Continue");
$('<input>').attr({
type: 'hidden',
name: 'delete'
value: 'delete'
}).appendto('#edit_form');
$("form#edit_form").submit();
}
Or set your delete button to <input type="submit"... so it gets sent with the form.
I was able to get it working with this js:
$("#submit-id-delete").click(function(ev){
ev.preventDefault();
var deleteBtn = $(this);
ShopifyApp.Modal.confirm(
{
title: "Delete?",
message: "Are you sure you want to delete this?",
okButton: "Yes, delete",
style: "danger"
},
function(result){
if(!result){
return false;
}
else {
deleteBtn.parents('form').append('<input type="hidden" name="delete" id="delete" value="delete" />').submit();
return true;
}
});
});

Add Friend with Ajax - Django

I'm using Django-Friends
I'm trying to have it so when a user clicks on the add friend, the button disappears(or ideally says Request sent). However, when I click the button, it doesn't disappears. I am new at Django and Ajax, so I'm assuming that this is an error on my part. Most likely the HttpResponse.
That part actually confuses me a lot. The HttpResponse, render, render_to_response, etc. I know that I can use render or render_to_response when I want to load a template. But what if I don't want to load up a new template or go to a new page? Like I want to be able to complete an action like add a friend, or add a page, etc; all on one page. I know you can use ajax to do it, but I don't know the django technical aspect of it.
Anyway, here's my code. Right now, nothing happens. The button doesn't disappear, and there is no friendships request sent.
profile.html
<div class="text-center">
<div>
"{{currUserprofile.tagline}}"
</div>
{{currUser.profile.city}}, {{currUser.profile.state}}
{{currUser.id}}
</div>
<!-- <button id="addfriend" data-profileid="{{currUser.id}}" class="btn btn-primary" type="button"> <span class="glyphicon glyphicon-plus"></span>
Request Friend</button>
--> <!--Find a way to signify looking or not looking to mentor -->
<button id="addfriend" data-profileid="{{currUser.id}}" class="btn btn-primary" type="button"> <span class="glyphicon glyphicon-plus"></span>
Request Friend</button>
ajax.js
$(document).ready(function () {
$('#addfriend').click(function () {
var profile_id = $(this).data("profileid");
$.get('/myapp/addfriend/id=' + profile_id, function (data) {
$('#addfriend').fadeOut();
});
});
})
views.py
#login_required
def profile(request, id):
context = RequestContext(request)
currUser = User.objects.get(pk = id)
profile = UserProfile.objects.filter(user = currUser)
return render_to_response('myapp/profile.html', {'currUser': currUser, 'UserProfile': UserProfile}, context)
#login_required
def addfriend(request, id):
context = RequestContext(request)
other_user = User.objects.get(pk=id)
new_relationship = Friend.objects.add_friend(request.user, other_user)
profile = UserProfile.objects.filter(user = other_user)
return HttpResponse(new_relationship)
Here is a working JSFiddle, but you can't post data {profile_id: profile_id}with a getyou should use a postor add the data as params, as I did:
HTML:
<button id="addfriend" data-profileid="{{currUser.id}}" class="btn btn-primary" type="button"> <span class="glyphicon glyphicon-plus"></span>
Request Friend</button>
JS:
$(document).ready(function () {
$('#addfriend').click(function () {
var profile_id = $(this).data("profileid");
$.get('/myapp/addfriend/?profile_id=' + profile_id, function (data) {
$('#addfriend').fadeOut();
});
});
});

Categories

Resources