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:
Type for example the word "stackoverflow"
And you will get:
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!
– Henrique Nascimento
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.
– Filipe Gonçalves
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 Nascimento
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.
– Filipe Gonçalves