Calling a django function from html button - django

I am new to django.
What i am trying to do is to run a django function from my "main.py" file when a html button is pressed.
what I've done is created a button in html:
<input type="button" value="Formatting excel" onclick="excel_formatting">
And then in my "main.py " I have:
def excel_formatting():
print("hello world")
return()
The website loads fine, but when i press the button nothing is printed in the terminal. i must be doing something wrong.

you can have a button that is a link and when the user presses the button it will redirect them to the link which will activate the function.
views.py
def button(request):
print('hello')
urls.py
from . import views as main_views
path('button/', main_views.button, name="button"),
index.html
<a href="{% url 'button' %}" class="btn btn-primary">Button</button>

Related

How to create user status active deactivate toggle button in Django?

I want something like this in my Django .
enter image description here
Can anyone tell me how should I code in html template and views.py ?
If you want to change the boolean field value status on click, you need to use Jquery.
I created an app named toggle, so you need to replace it with your app's name and is_working with your status button.
here is the full code
urls.py::
from django.urls import path
from toggle.views import home, toggle
urlpatterns = [
path('', home),
path('toggle/', toggle),
]
views.py:
from django.shortcuts import render
def home(request):
w, created = Work_Experience.objects.get_or_create(id=1)
return render(request,'home.html', {'workexperiance': w})
from django.http import HttpResponse
from toggle.models import Work_Experience
def toggle(request):
w = Work_Experience.objects.get(id=request.POST['id'])
w.is_working = request.POST['isworking'] == 'true'
w.save()
return HttpResponse('success')
home.html:
<div style="display:inline-block">
<label>Currently working here?</label>
<label class="switch">
<input type="checkbox" id="checkbox" value="{{workexperiance.is_working}}">
<span class="slider round"></span>
</label>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script> <!-- Import Jquery Here-->
<script type="text/javascript">
$(document).ready(function() {
$('#checkbox').change(function() {
$.post("/toggle/", {
id: '{{workexperiance.id}}',
isworking: this.checked,
csrfmiddlewaretoken: '{{ csrf_token }}'
});
});
});
</script>
run: ./manage.py runserver and visit: http://localhost:8000
when you click the Currently working here? check box, will instantly change the boolean field value "is_working".
reference to originally answered question :
Originally answered link

How to make popup 'add' window in Django 3?

In django admin, when there is a ForeignKey or ManyToManyField, there is [+] button to add it like this :
How can I make that [+] button with popup window using forms in templates ?
UPDATE 01:
I WANT TO CREATE POPUP WINDOW LIKE THIS IN MY TEMPLATE, NOT IN MY ADMIN PANEL.
You can use the admin reverse urls.
So in code:
<button class="button" onClick="window.open('{% url 'admin:model_add' %}');">
<span class="icon-plus">+</span>
</button>
This is not tested! It's just a quick try out of my brain.

Call function from button in django

On one of my pages I want to display a button, whenever this button is clicked I want to display the following in my display "Button clicked".
However the following message displays in my console.""GET /account/all-plan/?print_btn=Click HTTP/1.1" 200 5025"
This is my view
def print_from_button(request):
if(request.GET.get('print_btn')):
print('Button clicked')
return HttpResponse('testklik')
html
<form method="get">
<input type="submit" class="btn" value="Click" name="print_btn">
</form>
and url in urls.py
path('all-plan/print_from_button', views.print_from_button, name='print_from_button'),
Can anyone point me into the right direction, I cannot find what I am missing. Thanks a lot!
You seem to have to URLs:
/account/all-plan/
/account/all-plan/print_from_button
In the first URL you are creating a <form> which uses the GET method, but no action attribute is specified. The result is that your form submits to the same URL as the current page (first URL). This can be seen as your console print says it's using the first URL with an extra GET parameter.
In order to get your form to use the correct URL you need to specify the action attribute with the correct URL:
<form method="get" action="{% url "app_name:print_from_button" %}">
...
</form>

Dajax example doesnt work

So I'm trying to get the hang of Dajaxice for Django. Everything was fine till I used Dajaxice, but just I tried Dajax I gat trouble.
I made a new project and inside it an example app. So then I made a button - Button 1 in a template which uses a function in ajax.py, this worked fine. Button 2 did not work though, which uses the second function in ajax.py. I have pasted the index.html and ajax.py code below. How can I get the Button 2 to work, and make it do what I want it to do.
index.html
{% load dajaxice_templatetags %}
{% dajaxice_js_import %}
<input type="button" value="Button 1" onclick="Dajaxice.example.sayhello(my_js_callback);"/>
<br>
<input type="text" id="text"/>
<input type="button" value="Button 2" onclick="Dajaxice.example.saytext(my_js_callback, {'text':$('#text').val()});"/>
<script type="text/javascript">
function my_js_callback(data){
alert(data.message);
}
</script>
ajax.py
from django.utils import simplejson
from dajaxice.decorators import dajaxice_register
#dajaxice_register
def sayhello(request):
return simplejson.dumps({'message':'Hello World!'})
#dajaxice_register
def saytext(request, text):
return simplejson.dumps({'message':'%s' % text})
this has been said multiple times over the last few years. The Dajaxice project is a bad idea and you should just use JQuery and AJAX instead to post/receive data to your django view.
The author has stated on his Github page; "These days using this project is a bad idea."

Customizing Django-PayPal View

I am using django paypal to allow users to make a payment on my site however i have a few queries.
The way how it is currently working for me is that i have a template called profile.html. When a user clicks the button "Click for more subscription options" he will be redirected to the subscriptions.html template showing a table of the subscriptions and a paypal button. When the button is clicked, the user gets redirected to another template called paypal.html which shows another paypal button derived from django-paypal's forms.py
My question here would be how i can modify the paypal view such that i can do away with the paypal.html and direct the user directly to the actual paypal website when he clicks the paypal button in subscription.html?
I hope my description of the question is clear enough.
in my views.py:
def paypal(request):
paypal_dict = {"business":settings.PAYPAL_RECEIVER_EMAIL,"amount": "1.00","item_name": "Milk" ,"invoice": "12345678", "notify_url": "%s%s" % (settings.SITE_NAME, reverse('paypal-ipn')),"return_url": "http://rosebud.mosuma.net",}
# Create the instance.
form = PayPalPaymentsForm(initial=paypal_dict)
context = {"form": form.sandbox()}
return render_to_response("paypal.html", context)
in my profile.html:
....
<INPUT TYPE="submit" Value="Click to find out subscription plans" name="subscription" onClick="/subscribe/>
in my subscription.html:
<form method="post" action="paypal/">
<select name="subscription_input" id="id_subscription" style = "float: center">
<option>Monthly</option>
<option>Yearly</option>
</select></br></br>
{{ form }}
</form>
in my urls.py:
url(r'^paypal/$', 'r2.views.paypal', name='paypal'),
url(r'^profile/paypal/$', 'r2.views.paypal', name='paypal'),
If you want the user to go directly to the PayPal website the moment he clicks the PayPal button in subscription.html, you will have to render the PayPal form in subscription.html instead of paypal.html. Moreover you need to subclass the PayPalPaymentsForm in forms.py to override the default PayPal image of "Buy Now" because you want your own button to work in the first place.
forms.py
from paypal.standard.forms import PayPalPaymentsForm
from django.utils.html import format_html
class ExtPayPalPaymentsForm(PayPalPaymentsForm):
def render(self):
form_open = u'''<form action="%s" id="PayPalForm" method="post">''' % (self.get_endpoint())
form_close = u'</form>'
# format html as you need
submit_elm = u'''<input type="submit" class="btn btn-success my-custom-class">'''
return format_html(form_open+self.as_p()+submit_elm+form_close)
views.py
from .forms import ExtPayPalPaymentsForm
def paypal(request):
paypal_dict = {"business":settings.PAYPAL_RECEIVER_EMAIL,"amount": "1.00","item_name": "Milk" ,"invoice": "12345678", "notify_url": "%s%s" % (settings.SITE_NAME, reverse('paypal-ipn')),"return_url": "http://rosebud.mosuma.net",}
# Create the instance.
form = ExtPayPalPaymentsForm(initial=paypal_dict)
context = {"form": form.sandbox()}
return render_to_response("subscription.html", context)