Как отправить данные из формы CBV в шаблон CBV? - PullRequest
0 голосов
/ 02 апреля 2019

Я пытаюсь отправить данные POST из формы CBV в другой CBV.

Я использую метод valid_form, чтобы получить информацию по form.cleaned_data, а затем применяю в этом методе некоторые пользовательские методы.Но я не могу отправить результат в другое представление.

Также я попытался вставить действие в отправку html в другой шаблон, а затем получить данные, но не могу.

views.py

from django.shortcuts import render
from django.views.generic.edit import FormView
from django.views.generic.base import TemplateView

from .forms import QuoteForm
from .models import SmgQuotesTable
from .quotes import Quotes


class QuoteFormView(FormView):
    template_name = 'core/home.html'
    form_class = QuoteForm
    success_url = 'quotes'


    def form_valid(self, form):
        name = form.cleaned_data['name']
        email = form.cleaned_data['email']
        couple = form.cleaned_data['couple']
        age = form.cleaned_data['age']
        kids = form.cleaned_data['kids']
        #query_filter = Quotes().planSelector(couple, kids, age)
        #obj = SmgQuotesTable.objects.filter(composite='Ind. Junior (H25)')
        return super(QuoteFormView, self).form_valid(form)


class QuoteListView(ListView):
    model = SmgQuotesTable


    def get_queryset(self):
        queryset = super(QuoteListView, self).get_queryset()
        queryset = queryset #

        print(queryset)
        return queryset

home.html

{% block content %}
<style>label{display:none}</style>
    <form method="post" action="{% url 'quotes-list' %}">{% csrf_token %}
        {{ form.as_p }}
        <input type="submit" class="btn btn-primary btn-block py-2" value="Cotizar">
    </form>
{% endblock %}

urls.py

from django.urls import path
from .views import QuoteFormView, QuoteListView

urlpatterns = [
    path('', QuoteFormView.as_view(), name='home'),
    path('quotes/', QuoteListView.as_view(), name='quotes-list'),
]

Я ожидаю получить имя, адрес электронной почтызначения, пары, возраст и дети в QuoteView и применить метод Quotes, чтобы я мог напечатать результат в quotes.html

1 Ответ

0 голосов
/ 03 апреля 2019

Я решаю.

В views.py замените метод form_Valid в представлении формы на метод get_query в ListView,С помощью self.request.GET () я получаю информацию и передаю ее в пользовательский метод quot.Затем я возвращаю отфильтрованную информацию с результатом.

from django.shortcuts import render
from django.views.generic.edit import FormView
from django.views.generic.list import ListView

from .forms import QuoteForm
from .models import SmgQuotesTable
from .quotes import Quotes


class QuoteFormView(FormView):
    template_name = 'core/home.html'
    form_class = QuoteForm
    success_url = 'quotes'



class QuoteListView(ListView):
    model = SmgQuotesTable

    def get_queryset(self):
        r_get = self.request.GET
        d_get = {'name': None , 'email':None , 'couple': None, 'age': None, 'kids':None ,}

        for value in d_get:
            d_get[value] = r_get[value]

        query_filter = Quotes().planSelector(d_get['couple'], d_get['kids'], d_get['age'])


        queryset = super(QuoteListView, self).get_queryset().filter(composite=query_filter)
        return queryset

В home.html необходимо изменить метод POST на метод GET , поскольку представление списка не допускает POST.Добавляя в действие к шаблону ListView, я отправляю данные в форме для принятия с self.request.GET в методе get_queryset ().

{% extends 'core/base.html' %}

{% block title %}Cotizador{% endblock %}

{% load static %}


{% block headers %} 
    <h1>Cotizador</h1>
    <span class="subheading">Cotiza tu plan!</span>
{% endblock %} 

{% block content %}
<style>label{display:none}</style>
    <form method="get" action="{% url 'quotes-list' %}">{% csrf_token %}
        {{ form.as_p }}
        <input type="submit" class="btn btn-primary btn-block py-2" value="Cotizar">
    </form>
{% endblock %}

Наконец, я поместил информацию в smgquotestable_list , используя object_list и свойства модели.

{% extends 'core/base.html' %}

{% block title %}Cotización{% endblock %}

{% load static %}


{% block headers %} 
    <h1>Cotización</h1>
    <span class="subheading">Cotización</span>
{% endblock %} 

{% block content %}
{% for item in object_list %}
<div class="table-responsive text-nowrap"></div>
  <table class="table table-striped">
      <thead>
        <tr>
          <th scope="col"></th>
          <th scope="col">SMG01</th>
          <th scope="col">SMG02</th>
          <th scope="col">SMG10</th>
          <th scope="col">SMG20</th>
          <th scope="col">SMG30</th>
          <th scope="col">SMG40</th>
          <th scope="col">SMG50</th>
          <th scope="col">SMG60</th>
          <th scope="col">SMG70</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <th scope="row">{{ item.composite }}</th>
          <td>$ {{ item.smg01 }}</td>
          <td>$ {{ item.smg02 }}</td>
          <td>$ {{ item.smg10 }}</td>
          <td>$ {{ item.smg20 }}</td>
          <td>$ {{ item.smg30 }}</td>
          <td>$ {{ item.smg40 }}</td>
          <td>$ {{ item.smg50 }}</td>
          <td>$ {{ item.smg60 }}</td>
          <td>$ {{ item.smg70 }}</td>
        </tr>
      </tbody>
  </table>
</div>
{% endfor %}
{% endblock %}
...