How to assign a function to a button in Django Python

Asked

Viewed 1,851 times

3

I am doing a Jango course and I would like to know if it is possible to assign a function to a button.

For example:

  <form>
      <label for="word">Digite uma palavra:</label>
      <input id="word" type="text" name="palavra" value="" />
      <input type="submit">                   
  </form>

In this search bar the user would type any word. The moment this user clicked send I would like a function that I called 'Tamanho_da_str' to be executed:

def tamanho_da_str(request):
    palavra_digitada = **Palavra que o usuário digitou na barra de pesquisa**
    len_string = len(palavradigitada)
    dicionario = {'tamanho': len_string}
    return render(request, "resultado.html", dicionario)

For this to work I would need to establish a link between the send button and the function size_da_str, then I would need the word typed by the user to be stored in the typed word variable.

Can you tell me if this is possible and what methods are used ?

Ps : Maybe because I’m not a developer and I don’t know some terms related to the area I couldn’t find anything on the internet, but any direction will be welcome.

  • Opaa Felipe, all right? To be honest, by the time I develop in Python and Django I never got to see an interaction between the button and a function in Django, unless you want to add some data in the database. In this case you could read some of Django’s own documentation in the part related to the forms. But you can do this function you want with Javascript!

  • Beauty Henry I will look in the documentation, but taking advantage of what you said about saving in the database, how would I do it ? I think if I do that I can adapt a solution to my problem. About Javascript I’ve heard but I’m learning the basics of Python yet, messing with other now would only complicate me.

  • Then you would have to create a model and a Forms, then you could send the data to the database. I recommend following the tutorial of Django Girls: https://tutorial.djangogirls.org/pt/django_forms/

  • Henrique thanks a lot for the help I found quite cool in the documentation and I managed to do what I wanted using the method that Rodrigo reported up there, maybe it will be useful for you too, hug.

2 answers

2


Since you are already programming in Django, you probably already know, but I’ll make it clear here: Django is called the MTV framework (Model-Template-View). The view (view) part usually inspects the incoming HTTP request and queries or processes the data to be rendered (presentation).

I will present here an example that Voce can run on your command line, to simplify put the example in just two files, but this is not the usual practice in the world of Jango development, I make some comments on the code (the ones I remembered) explaining what would be the convention adopted by the community, come on:

File: main.py

# Configurações do django, aqui configura-se o projeto django, desde conexoes 
# com banco de dados até recursos estaticos e funcionalidades de internacionalização
# Normalmente, no 'mundo real', essas configuracoes estariam em um arquivo settings.py
from django.conf import settings
import os
ROOT = os.path.dirname(os.path.abspath(__file__))
settings.configure(
    DEBUG=True,
    SECRET_KEY = '0uarl&=3a$o1*0wk-5s@x6@d*0%r576h0&@f65+09ebtkv3jtd',
    ROOT_URLCONF=__name__,
    MIDDLEWARE = (
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ),
    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [ROOT]
        }
    ]
)

# No mundo real esse codigo estaria em um arquivo views.py
from django.http import HttpResponse
from django.shortcuts import render 
def index(request):

    count = None
    palavra = None

    if request.method=='POST':
        palavra = request.POST['palavra']
        count = len(palavra)

    return render(request, 'palavra.html', {'count': count, 'palavra': palavra})

# Para conectar a view à estrutura do site é preciso associa-la a uma URL
# No mundo real esse codigo estaria em um arquivo urls.py
from django.urls import include, path
urlpatterns = (
    path('', index),
)


if __name__ == "__main__":
    import sys
    from django.core.management import execute_from_command_line
    execute_from_command_line(sys.argv)

File: word.html

<form method="POST">
    {% csrf_token %}
    <label for="word">Digite uma palavra:</label>
    <input id="word" type="text" name="palavra" value="" />
    <input type="submit"> 
    {% if count != None %}
        <br><br>
        Palavra digitada: {{palavra}}<br>
        Número de caracteres: {{count}}
    {% endif %}
</form>

Now run on your command line:

$ python main.py runserver

And you will get:

Performing system checks...

System check identified no issues (0 silenced).
February 14, 2019 - 11:55:14
Django version 2.1.1, using settings None
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

On your Rowse, point to http://127.0.0.1:8000/ and you’ll get:

Localhost

Type for example the word "stackoverflow"

And you will get:

Digitação da palavra

  • Perfect, I had already managed to accomplish the task but you were extremely thorough in case someone has the same doubt I had in the future will surely know how to solve with your comment thank you very much.

  • In fact it is not a comment but an answer, it would be interesting that you give the acceptance and, eventually, an upvote on some of the answers, to stimulate those who try to help. :-)

  • 1

    Thanks for the help as said there in the comment, you received upvote however it is not visible because I do not have 15 reps.

  • got 15 reps.

1

Hello, Voce uses the POST method and so Django recognizes HTML by the attribute name

 <form method = 'POST'>
       {% csrf_token %}
      <label for="word">Digite uma palavra:</label>
      <input id="word" type="text" name="palavra" value="" />
      <input type="submit">                   
  </form>

use the request

def tamanho_da_str(request):

if request.method == 'POST':     
 palavra_digitada = request.POST.get('palavra')
 print (palavra_digitada)
 ....

I hope I’ve helped,

And may the force be with you

  • Good morning Rodrigo helped a lot but I’m having this error here 'Forbidden (403) CSRF Verification failed. Request aborted.'

  • opa I managed to solve this thank you very much Rodrigo with this information I will manage to do a lot of things.

  • 1

    hi forgot to put {% csrf_token %}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.