Как использовать TemplateView с 2 методами (получить и опубликовать) - PullRequest
0 голосов
/ 11 июня 2019

Я пытаюсь использовать Templateview в Django для рендеринга страницы с опциями как для добавления в базу данных, так и для извлечения некоторой информации из базы данных и ее отображения.Я использую его на уроке https://www.youtube.com/watch?v=VxOsCKMStuw

views.py:

class TestView(TemplateView):
    template_name = 'app/sensor_name_tmpl.html'

    def get(self, request):
        form = SensorForm()
        posts = Sensor.objects.all()

        args = {'form': form, 'posts': posts}
        return render(request, self.template_name, args)


    def post(self, request):
        form = SensorForm(request.POST)
        if form.is_valid():
            form.save()
            text = form.cleaned_data['post']
            form = SensorForm()
            return redirect('sensor_name_tmpl:sensor_name_tmpl')

        args = {'form': form, 'text': text}
        return render(request, self.template_name, args)

urls.py:

urlpatterns = [
    path('', views.index, name='index'),
    url(r'^form1/$', views.get_sensor_name, name='GiveSensorName1'),
    #url(r'^form2/$', TestView.as_view(), name='sensor_name_tmpl.html'),
    path('form2/', TestView.as_view(), name='app/sensor_name_tmpl.html'),
    url(r'^nested_admin/', include('nested_admin.urls')),
]

HTML-шаблон:

    <!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
        <script>
            $('#toggle').click(function() {
            $('form').toggle('slow');
            });
        </script>
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

    <title>Hello world!</title>
  </head>


  <body>
    <h3 class="text-success">Add Sensor</h3>
    <br>

<!--    <form style="display:none;" method="post">-->
        <form method="post">
        {% csrf_token %}
        <div class="row align-items-center">
            <div class="col-sm-8">
                <table>
                   {{ form1.as_table}}
                </table>
                <div class="mx-sm-2">
                    <input type="submit" value="Submit">
                </div>

                <br>
                <br>

                <h3 class = "text-success">Add Sensor View</h3>
                <table>
                   {{ form2.as_table}}
                </table>
                  <div class="mx-sm-2">
                        <input type="submit" value="Submit">
                  </div>
                <br>
                <br>

                <h3 class="text-success">View Sensors</h3>

                <table class="table">
                    <thead>
                        <tr>
                            <th scope="col">Sensor ID</th>
                            <th scope="col">Sensor Name</th>
                        </tr>
                    </thead>
                <tbody>
                {%for obj in obj%}
                    <tr>
                        <td>{{obj.sensor_id}}</td>
                        <td>{{obj.sensor_name}}</td>
<!--                        <th scope="row">1</th>-->
                    </tr>
                {% endfor %}
                </tbody>
                </table>





            </div>
        <div>
    </form>


    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->

    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>

  </body>
</html>

Страница отображает шаблон, но не заполняет его ни полями формы, ни данными из базы данных.

1 Ответ

0 голосов
/ 11 июня 2019

Проблема была в шаблоне HTML, где form1 и form2 теперь заменены на form, а obj в цикле for заменены на posts. Шаблон теперь выглядит следующим образом:

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
        <script>
            $('#toggle').click(function() {
            $('form').toggle('slow');
            });
        </script>
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

    <title>Hello world!</title>
  </head>


  <body>
    <h3 class="text-success">Add Sensor</h3>
    <br>

<!--    <form style="display:none;" method="post">-->
        <form method="post">
        {% csrf_token %}
        <div class="row align-items-center">
            <div class="col-sm-8">
                <table>
                   {{ form.as_table}}
                </table>
                <div class="mx-sm-2">
                    <input type="submit" value="Submit">
                </div>

                <br>
                <br>

                <h3 class = "text-success">Add Sensor View</h3>
                <table>
                   {{ form.as_table}}
                </table>
                  <div class="mx-sm-2">
                        <input type="submit" value="Submit">
                  </div>
                <br>
                <br>

                <h3 class="text-success">View Sensors</h3>

                <table class="table">
                    <thead>
                        <tr>
                            <th scope="col">Sensor ID</th>
                            <th scope="col">Sensor Name</th>
                        </tr>
                    </thead>
                <tbody>
                {%for obj in posts%}
                    <tr>
                        <td>{{obj.sensor_id}}</td>
                        <td>{{obj.sensor_name}}</td>
<!--                        <th scope="row">1</th>-->
                    </tr>
                {% endfor %}
                </tbody>
                </table>





            </div>
        <div>
    </form>


    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->

    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>

  </body>
</html>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...