如何在Django的一个url地址中调用多个视图?

时间:2018-02-11 09:08:55

标签: python django django-views django-urls

我试图在index.html上显示由new_measurement定义的表单,但我只是设法使IndexView()起作用。我尝试了IndexView()new_measurement()之间的各种组合,但这些组合根本没有用。我知道IndexView()没有传递任何与new_measurement()相关的内容,而且new_measurement()没有被调用,这是我问题的核心。如果对Django更有经验的人能告诉我我能做什么或应该做什么,我真的很感激。谢谢。

这是 views.py

from django.shortcuts import render
from django.utils import timezone
from .models import Measurement
from .forms import MeasurementForm
from django.views import generic


class IndexView(generic.ListView):
    model = Measurement
    context_object_name = 'measurement_list'
    template_name = 'index.html'
    queryset = Measurement.objects.all()


def new_measurement(request):
    if request.method == "POST":
        form = MeasurementForm(request.POST)
        if form.is_valid():
            measurement = form.save(commit=False)
            measurement.measurement_date = timezone.now()
            measurement.save()
    else:
        form = MeasurementForm()

    return render(request, 'index.html', {'form': form})

urls.py

from django.urls import path
from . import views


urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
]

forms.py

class MeasurementForm(forms.ModelForm):
    class Meta:
        model = Measurement
        fields = ('measurement_value', 'measurement_unit')

的index.html

{% extends "base.html" %}

{% block content %}
    <h1>Climate Measurement Tool</h1>

    <h2>Add a new measurement</h2>
    <form method="POST" class="post-form">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit" class="save">Add</button>
    </form>

    <h2>Measurements</h2>
    {% if measurement_list %}
    <ul>
        {% for measurement in measurement_list %}
        <li>
            <p>{{ measurement }}</p>
        </li>
        {% endfor %}
    </ul>
    {% else %}
        <p>No measurements yet</p>
    {% endif %}    
{% endblock %}

3 个答案:

答案 0 :(得分:3)

您无法在一个网址中映射多个视图,但您可以在一个视图中执行多个视图。 更新你的views.py,因为你可以看到我在该视图中发送(查询和形式)

views.py

def new_measurement(request):
    if request.method == "POST":
        form = MeasurementForm(request.POST)
        if form.is_valid():
            measurement = form.save(commit=False)
            measurement.measurement_date = timezone.now()
            measurement.save()
    else:
        form = MeasurementForm()

    qs = Measurement.objects.all()
    context = {'form': form, 'measurement_list': qs}
    return render(request, 'index.html', context)

更新urls.py

from django.urls import path
from . import views


urlpatterns = [
    path('', views.new_measurement, name='index'),
]

答案 1 :(得分:0)

您无法为一个网址调用2个观看次数。基本上每个网址都必须链接到一个视图,这是你无法真正改变的。

但是如果你希望你的代码更干净并具有多种功能,你可以在你的视图中调用它们,基本上你可以做的是创建一个视图并在使用url或甚至多个url时调用它并在该视图中决定使用哪个功能

示例:

def god_view(request):
    if request.method == "POST"
        return post_func(request)
    return get_func(request)

这是一个非常简单的例子,但你可以做很多其他事情。

答案 2 :(得分:0)

在一个网址中无法获得更多观看次数,但可以模拟它。我这样做就像一个视图,在这个视图的模板中是javascript,它加载了 Highcharts.stockChart('container', { chart: { events: { load: function(event) { // Get the volume series by id. var volSeries = this.series.find(function(s) { return s.userOptions.id === 'volume'; }); // Override the pointAttribs function on the volume series. volSeries.pointAttribs = (function(original) { return function(point, state) { // Call the original pointAttribs function. var attribs = original.apply(this, arguments); // Get the price series using the id. var priceSeries = point.series.chart.series.find(function(s) { return s.userOptions.id === 'price'; }); // Find the candle corresponding to the current volume point. var candle; if (point.series.hasGroupedData) { // With grouped data, we need to find the candle from the grouped data. var datagroup = point.dataGroup; var groupIdx = point.series.groupMap.indexOf(datagroup); candle = priceSeries.groupedData[groupIdx]; } else { // Non-grouped data, we can just use the normal data. candle = priceSeries.data[point.index]; } // Choose the color for the volume point based on the candle properties. var color = 'blue'; if (candle.close > candle.open) { color = 'green'; } else if (candle.close < candle.open) { color = 'red'; } // Set the volume point's attribute(s) accordingly. attribs.fill = color; // Return the updated attributes. return attribs; }; })(volSeries.pointAttribs); // Need to call update so the changes get taken into account on first draw. this.update({}); } } }, ... 的响应的第二个视图,并用第二个视图的内容填充了所属元素。第二个视图不是完整的模板,而是从一些AJAX标记开始,这些标记放在第一个模板中。我试着给你一个例子

<强>视图

div

<强> first_template.html

def first_view(request):
    return render(
        request,
        'first_template.html',
        {
            'first_content': 'Some heavy content'
        })


def second_view(request):
    return render(
        request, 
        'second_template.html', 
        {
            'second_content': 'Some heavier content!'
        })

<强> second_template.html

...
<body>

    <div id="1">
        {{ first_content }}
    </div>
    <div>
        ... loading ...
    </div>

    <script>

    window.onload = function() {
        $.ajax({
            url: {% url 'to_second_view' %},
            method: 'GET',
            success: function(response) {
                $('#2').html(response);
            }
        })
    }

    </script>

</body>
...