如何使用Django通用更新视图来使用单个表单字段值更新我的模型



models.py:

from django.db import models
class Location(models.Model):
name = models.CharField(max_length=20)
is_source = models.BooleanField(default=False)
is_destination = models.BooleanField(default=False)
def __str__(self):
return self.name

views.py

from django.shortcuts import render
from django.urls import reverse_lazy
from django.views import generic
from .models import Location
class LocationsListView(generic.ListView):
model = Location
template_name = 'locations/list.html'
context_object_name = 'locations'

class LocationUpdateView(generic.edit.UpdateView):
model = Location
fields = ['name', 'is_source', 'is_destination']
context_object_name = 'location'
template_name = 'locations/update.html'
success_url = reverse_lazy('locations:list')
class LocationDeleteView (generic.edit.DeleteView):
model = Location
template_name = 'locations/confirm_delete.html'
context_object_name = 'location'
success_url = reverse_lazy('locations:list')

locations/update.html

{% extends 'base.html' %}
{% block title %}Location Update{% endblock %}
{% block content %}
<section>
<div class="container">
<h1>Location Update</h1>
<div class="form-container">
<form method="post">
{% csrf_token %}
{% if form.errors %}
<div class="p-3 mb-3 border border-danger border-3 rounded">{{ form.errors }}</div>
{% endif %}
<div class="mb-3">
<label for="" class="form-label">Name</label>
<input type="text" class="form-control" value="{{ form.name.value }}">
</div>
<div class="mb-3">
<input type="checkbox" class="form-check-input" {% if form.is_source.value %} checked {% endif %}>
<label for="">Source</label>
</div>
<div class="mb-3">
<input type="checkbox" class="form-check-input" {% if form.is_destination.value %} checked {% endif %}> 
<label for="">Destination</label>
</div>
<input type="submit" class="btn btn-success mb-3" value="Save">
</form>
</div>
</div>
</section>
{% endblock %}

locations.urls.py

from django.urls import path
from . import views
app_name = 'locations'

urlpatterns = [
path('', views.LocationsListView.as_view(), name='list'),
path('update/<int:pk>/', views.LocationUpdateView.as_view(), name='update'),
path('delete/<int:pk>/', views.LocationDeleteView.as_view(), name='delete'), 
]

当我尝试更新我的模型,使用{{form.name.value}}单独呈现表单字段时,我得到一个错误,即我的名称字段是必需的,但它已被填充。例如,如果使用{{form.as_p}}将表单作为一个整体呈现,则不会出现错误。我做错了什么?

我尝试使用{{form.as_p}},结果成功了。但我需要单独的字段渲染,这样我就可以设计我的表单。

您需要为每个字段<input>标记提供name属性。如果手动渲染,则应使用字段的html_name属性

<input name="{{ form.name.html_name }}" type="text" class="form-control" value="{{ form.name.value }}">

最新更新