Table Multiplication

Как вызвать функцию Django при нажатии кнопки?

Я пытаюсь написать приложение Django, и я застрял в том, как я могу вызвать функцию представления при нажатии кнопки. В моем шаблоне у меня есть кнопка ссылки, как показано ниже, при нажатии на которую вы переходите на другую веб-страницу:

Когда кнопка нажата, я также хочу вызвать функцию просмотра Django (наряду с перенаправлением на целевой веб-сайт). Функция просмотра увеличивает значение в базе данных, в которой хранится количество нажатий кнопки. column_3_item.link_for_item представляет собой ссылку на внешний веб-сайт (например, www.google.com). Прямо сейчас, когда эта кнопка нажата, она открывает новое окно, которое приводит вас на сайт Google. Я хотел бы также вызвать функцию просмотра Django, когда нажата кнопка, которая обновляет базу данных без обновления страницы. Как мне этого добиться?

Я не понимаю твой вопрос. Ваш код вызывает функцию представления для любого column_3_item.link_for_item в котором отображается ваш urlconf.

добавление к комментарию Даниэля: если вам нужно нажать -> «обновить в реальном времени», не обновляя страницу, возможно, вам придется переписать свой вопрос. Если у вас есть вид, указывающий на эту ссылку, у вас уже есть то, что вам нужно

Читайте также:  Отделит строку до пробела java

извините за путаницу. column_3_item.link_for_item — это ссылка на внешний сайт (пример: — www.google.com). Прямо сейчас, когда нажимается эта кнопка, открывается новое окно, которое открывается на сайте Google. то, что я хотел бы сделать, это вызвать функцию просмотра Django также при нажатии кнопки, которая обновляет базу данных без обновления страницы.

Вы можете сделать это разными способами, но если вы не хотите перезагрузить / изменить страницу, я думаю, что вы должны полагаться на javascript (например, сделать ajax-вызов для представления, которое обновляет счетчик из того же тега , который вы используете для открытия новой страницы). Является ли использование javascript проблемой?

@furins — Не могли бы вы привести пример, как я могу сделать это с помощью JavaScript. Извините, что спросил это, я только новичок в веб-разработке.

Источник

Run Python function by clicking on HTML Button in Django

In this Python Django tutorial, I will explain how to run python function by clicking on HTML button in Django.

While working on a Django project, I need an HTML button for calling the python function. So, I have done the research and finally create an HTML button that prints table multiplication on click.

  • How to set up project in Django
  • How to create HTML button to execute python function in Django
  • Run Python function by clicking on HTML Button in Django to get multiplication table
  • How to use for loop in Django template tag
  • How to use range function in Django
  • Create Django Form using FormClass

At the end of this article, you can download the code for executing the python script with the click of an HTML button.

This is what we will build here.

execute python multiplication table function in django

Run Python function by clicking on HTML Button in Django

Now, let us see, step by step how to run the Python function on button click and display table multiplication in Django.

Set up Django Project

Firstly, we need to establish a project in Django using the below-given command. Here HTMLButtonProject is the name of the project.

django-admin startproject HTMLButtonProject

Within the Django project, create a Django app named MyApp using the command as follows.

python manage.py startapp MyApp

html button to run python function in django

Open the settings.py file located in the project directory, and add MyApp to the INSTALLED_APP list.

how to run python function by clicking on HTML button

A request in Django first comes to urls.py located inside the project directory and then goes to the matching URLs in urls.py inside the app directory. Add the below code in it.

from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('',include('MyApp.urls')), ]

Create Django Form

Create the Django form that the MyApp application will use to take input a number from the user. Add the following code to the forms.py file we created inside the app directory.

from django import forms class TableForm(forms.Form): num = forms.IntegerField(label='Please Enter Number:')

Here, we create a form using forms.Form class named TableForm. And it has num as Django IntegerField. Additionally, we change its label by passing the label keyword.

Run Python function by clicking on HTML Button in Django to get multiplication table

Create a subdirectory called Templates in the main project directory to store the HTML file of a Django application.

Open the settings.py file, and update the DIRS to refer to the Templates folder’s location.

execute python code by django html button

To define the frontend for the table multiplication function on the HTML button click, create an HTML file named home.html inside the Templates folder. And add the below-given code.

            

Welcome to PythonGuides



>


Number to print its multiplication table:>



> x > =
  • First, load your CSS by adding the stylesheet’s link to your page’s header before any other stylesheets.
  • Then, to add bootstrap padding and spacing use the div class mt-md-5, div class pl-sm-5, and div class pr-sm-5 respectively.
  • To build the form that we use to input a number from the user, we use the form tag with the POST method. Then, use the csrf_token to protect the form from cyber attacks and form.as_table to render the form field in table format.
  • Add a submit button to print the table multiplication. And, use the p tag and print the multiplication table. And then, we will use the for loop to get one value at a time from the sequence.
  • Then, we use this single value to get the table multiplication of the input number. To get the table multiplication, we are using a widthratio filter, and in the filter, (Number 1 x) simply means (Number * x).
  • Additionally, we use the h3, br, and hr tags to add a heading, break the line, and horizontal line respectively.

Define View

To define the main logic, open the views.py file and add the code given below.

from django.shortcuts import render from .forms import TableForm # Create your views here. def html_button(request): if request.method == "POST": form = TableForm(request.POST) if form.is_valid(): num = form.cleaned_data['num'] return render(request, 'home.html', ) else: form = TableForm() return render(request,'home.html',)
  • First, import the TableForm from the forms.py and create a view named html_button.
  • Then call the if statement and check whether the request method is POST.
    • If yes, we pass TableForm(request.POST) that binds the data to the form class, so we can do validation.
    • Now, call the is_valid method to validate the input entered by the user, and if validation success call the form cleaned_data[‘form field’] to validate the data.
    • Return home.html with num and range() function to get a list of numbers from 1 to 10 by passing to the render function.

    Now, we must map the view with the URL in order to call it, thus we must create a file called urls.py in the app directory. Include the code below in it.

    from django.urls import path from . import views urlpatterns = [ path('', views.html_button, name='htmlbutton'), ]

    Execute Django Application

    To launch a development server type the below-given command in the terminal and run the server.

    python manage.py runserver

    It successfully opens the web page used to do table multiplication which looks like this.

    Run Python function by clicking on HTML Button in Django

    Now, fill out the number whose table you want to print and click on the Print Table button.

    create html button to execute python function in django

    For example, here I enter the number 7 and it will print the table of 7 on clicking on the Print Table button.

    using django create html button to execute python function

    This is how we run the Python function by clicking on HTML Button using Django.

    Download the complete code to Run Python function by clicking on HTML Button in Django

    Conclusion

    With this, we have successfully created a Python function that will execute on an HTML button click. We have also learned to create a form using the Form Class that will take input from the user in the integer field.

    Additionally, we have also covered the following topic

    • How to set up project in Django
    • How to create HTML button to execute python function in Django
    • Run Python function by clicking on HTML Button in Django to get multiplication table
    • How to use for loop in Django template tag
    • How to use range function in Django
    • Create Django Form using FormClass

    Also, check the following tutorials on Python Django

    I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

    Источник

    How to Call a Function by clicking a Button in the Django Template File from a Django Application

    This is an article where the main function is just to show how to call a certain function exist in the Django application. Normally, the function exist in the ‘views.py’ file which is part of the Django application. The following is the structure of the normal Django application exist in a Django project :

    (env) C:\project\apps>dir Volume in drive C is Windows-SSD Volume Serial Number is CA30-19A4 Directory of C:\project\apps 09/06/2022 08:19 PM . 09/06/2022 07:13 AM .. 08/24/2022 10:02 AM 215 admin.py 08/24/2022 08:43 AM 146 apps.py 08/26/2022 02:19 PM migrations 08/26/2022 02:05 PM 1,548 models.py 09/06/2022 07:01 PM templates 08/24/2022 08:43 AM 63 tests.py 09/06/2022 08:03 AM 118 urls.py 09/08/2022 06:43 AM 871 views.py 08/24/2022 08:43 AM 0 __init__.py 09/08/2022 06:43 AM __pycache__ 7 File(s) 2,961 bytes 6 Dir(s) 66,276,225,024 bytes free (env) C:\project\apps>

    The content of the original ‘views.py’ file exist as follows :

    from django.shortcuts import render # Create your views here.

    So, the main target for this article is to just describe how to click in a page which is represented by a Django template file. After clicking the button exist in that page, it will directly call a function exist in the Django application.

    How to Call a Function by clicking a Button in the Django Template File

      First of all, Just define the function in the ‘views.py’ file as follows for an example :

    def my_function(request): print("This is a click request from a Django template file")
    from django.shortcuts import render # Create your views here. def my_function(request): print("This is a click request from a Django template file")
    from django.urls import path from apps import views urlpatterns = [ path('', views.index, name="index"), path('my_function', views.my_function, name="my_function"), ]

    In the above line, it wraps the button inside a hyperlink tag. So, if there is a click on the button which in turns will also click the hyperlink, it will process the URL exist in the ‘href’ attribute’. In this case, it is processing the URL of ‘my_function’. So, where is the exact URL of ‘my_function’ ?. Actually it is already exist in the previous step. It is defining the URL of ‘my_function’. So, the final revision of the ‘index.html’ file will exist as follows :

    (env) C:\project\project>python manage.py runserver Watching for file changes with StatReloader Performing system checks. System check identified no issues (0 silenced). September 08, 2022 - 06:28:36 Django version 4.1.1, using settings 'model.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK.
    This is a click request from a Django template file [08/Sep/2022 09:49:29] "GET /my_function HTTP/1.1" 200 1477

    Источник

Оцените статью