gpt4 book ai didi

python - Django如何在一个url地址调用多个 View ?

转载 作者:太空宇宙 更新时间:2023-11-03 15:48:09 26 4
gpt4 key购买 nike

我试图在 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'),
]

表单.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 %}

最佳答案

您不能在一个 url 中映射多个 View ,但可以在一个 View 中执行多项工作。更新您的 views.py,因为您可以看到我正在该 View 中发送(查询列表和表单)

View .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'),
]

关于python - Django如何在一个url地址调用多个 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48729966/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com