Django不是sh

出于某种原因,我的forms.py不会查看任何字段,相反,它只显示“添加”按钮,我不知道该怎么做 . 如果有人知道他们在做什么可以告诉我我做了什么,或者没有做什么,我真的很感激 .

请注意,我是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:来自django导入表单来自.models import Measurement

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 %}

回答(1)

2 years ago

new_measurement() 视图正确初始化表单实例并将其传递给模板 .

不幸的是,这种观点从未被调用过 .

urls.py 仅定义一个由 IndexView.as_view() 处理的URL,该URL不会将表单实例传递给模板 .