Communicate template with view

Asked

Viewed 445 times

0

I have a Django project where I ask the user to enter two dates (initial and final), and through them I make a query in an external database, making an input works, but wanted to take this information from the site and play it in the view.py variable to treat it and then generate the result.

Follow picture, I want to put the dates in the text places and press the button to generate the chart

inserir a descrição da imagem aqui

Follow my.py views where I want the test variables 3 and 4 to be generated by requesting the template from the user

py views.

def index(request):
    fig = Figure()
    ax = fig.add_subplot(1,1,1)
    ax.plot(teste3, teste4)
    #ax.bar(x_axis, y_axis, width=width_n, color=bar_color, align='center')
    ax.grid()
    buf = io.BytesIO()
    canvas = FigureCanvas(fig)
    canvas.print_png(buf)
    response=HttpResponse(buf.getvalue(), content_type='image/png')
    return response

Graphical template_list.html

{% extends 'base.html' %}

{% block main %}

Edit


<form method="post">
    {% csrf_token  %}

    <input size="16" type="text" value="{{ descricao }}" class="form_datetime">

    <script type="text/javascript">
        $(".form_datetime").datetimepicker({ format: 'dd/mm/yyyy hh:ii' });
    </script>

    <input size="16" type="text" value="{{ descricao2 }}" class="form_datetime">

    <script type="text/javascript">
        $(".form_datetime").datetimepicker({ format: 'dd/mm/yyyy hh:ii' });
    </script>


    <a href="{% url 'tela_graficos' %}" class="btn btn-primary">Grafico</a>
</form>
{% endblock %}
  • See my answer, just adapt.

1 answer

0

Comparing the code with the title of the question, it doesn’t seem to make much sense to me that I’m out of context, so I’ll try to answer myself by paying attention exclusively to the title of the question.

To show how the view "communicates" with the template, create, in the view, two variables (data1 and data2), initially with the value None for the two and send to the template where I present a form requesting the two dates and then the Czech code if it was ever sent to the form, if yes, the last send is presented.

To make things easy, I put all the code in just two files (main.py and template1.html), this is not usual in Django, but I make comments on the code where each party should be by convention (the ones I remembered).

Copy the content of the topic below "main.py" to a file .py and the topic "template1.html" obligatorily for a file with that name.

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
# Novamente, 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):

    data1 = None
    data2 = None

    if request.method=='POST':
        data1 = request.POST['data1']
        data2 = request.POST['data2']
        # Faça aqui o que vc quiser com data1 e data2, aqui vou apenas enviar de volta ao site

    return render(request, 'template1.html', {'data1': data1, 'data2': data2})

# 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)

template1.html

<form method="POST">
    {% csrf_token %}
    <label for="data1">Data Inicial:</label>
    <input id="data1" type="date" name="data1" value="" /><br>
    <label for="data2">Data Final:</label>
    <input id="data2" type="date" name="data2" value="" /><br>
    <input type="submit">

    {% if data1 != None %}
        <br><br>
        <p>
            Sua última digitação:<br>
            Data Inicial: {{data1}}<br>
            Data Final: {{data2}}<br>
        </p>
    {% endif %}
</form>

rotate the .py from the command line, assuming you have named the main.py, turn it like this:

python main.py runserver

Point your Rowse to http://127.0.0.1:8000/ and you will see the site requesting two dates, initial and final, from the moment you enter, the site will always inform the last entry.

Exit:

inserir a descrição da imagem aqui

  • Dude, it helped a lot, but a small detail, when I click the send button, it gives an error: 'Multivaluedictkeyerror at /polls/' polls would be my app for this views and this template

  • I don’t see the "send" button on your code.

  • I had implemented yours, but I’ve already got, a doubt only, in your code, the variable data1 can be treated in the view? or can only get the value None?

  • See my comment in the code # Faça aqui o que vc quiser com data1 e data2 ..., None is the initial value.

  • yes, I understood that, but he votes the value for my views, I move it and it turns into a template with a graphic, after treating everything, I click on the graphic button, it generates the right screen?

  • Perae... in the example, data1 is a date variable, you want to turn a date variable into a graphic template? I don’t understand.

  • i take the variable type of the date and play as the date for consultation in the bank, ai through the result generated in this query I make a graph and play in a template, the question is, this date type information passed by the user is received in the views and so can be used for this query?

  • Yes, take my example and where this comment makes some tests with the 2 variables, you can make a print, consult a bank that brings the results you want and send to the template in a dictionary, for example. In the template you can manipulate this data and plot a chart if quiiser, now... If you haven’t mastered these concepts yet, I suggest you study Django, start with documentation tutorial, totally de gratis, just dedicate yourself.

  • show, to with other problems here nothing to do with the post, but solving them I test and tell you here

Show 4 more comments

Browser other questions tagged

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