Django: UpdateView не показывает правильное значение BooleanField в шаблоне
У меня есть следующий проект Django, разработанный с использованием Generic Class Based View.
models.py
from datetime import datetime
from django.urls import reverse
class Product(models.Model):
prodName = models.CharField(max_length=50, default=None, unique=True)
def __str__(self):
return self.prodName
class Shipment(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
cost = models.IntegerField(max_length=4)
orderDate = models.DateTimeField(default=datetime.now, editable=False)
quantity = models.IntegerField(max_length=4)
receieved = models.BooleanField()
def __str__(self):
return f'{self.product}: {self.orderDate}
views.py
from django.urls import reverse_lazy
from django.views.generic import CreateView, UpdateView, DeleteView, ListView
from .models import Product, Shipment
# Create your views here.
class ShipmentListView(ListView):
model = Shipment
fields = '__all__'
class ProductCreateView(CreateView):
model= Product
fields = ['prodName']
success_url= reverse_lazy('modalform:shipDetail')
class ShipmentCreateView(CreateView):
model = Shipment
fields = ('product', 'cost', 'quantity', 'receieved')
success_url= reverse_lazy('modalform:shipDetail')
class ShipmentUpdateView(UpdateView):
model= Shipment
# template_name: str= 'modal_form/shipment_update.html'
fields = ('product', 'cost', 'quantity', 'receieved')
success_url= reverse_lazy('modalform:shipDetail')
class ShipmentDeleteView(DeleteView):
model = Shipment
success_url= reverse_lazy('modalform:shipDetail')
shipment_form.html
{% block content %}
<div class="border rounded-1 p-4 d-flex flex-column">
{% if not form.instance.pk %}
<h3>Create Shipment</h3>
{% else %}
<h3>Update Shipment</h3>
{% endif %}
<hr>
<form action="" method="post">
<label class="form-check-label" for="product">
Product
</label>
<select class="form-control" name="product" id="product">
{% for id, choice in form.product.field.choices %}
<option value="{{ id }}" {% if form.instance.pk and choice|stringformat:'s' == shipment.product|stringformat:'s'%} selected {% endif %} >
{{ choice }}
</option>
{% endfor %}
</select>
<label class="form-check-label" for="cost">
Cost
</label>
<input type="number" name="cost" id="cost" placeholder="0.00" class="w-100 p-2 form-control" value="{{ shipment.cost }}">
<label class="form-check-label" for="quantity">
Quantity
</label>
<input type="number" name="quantity" id="quantity" placeholder="0" class="w-100 p-2 form-control" value="{{ shipment.quantity }}">
{% if form.instance.pk %}
<input type="checkbox" name="receieved" id="receieved" class="form-check-input p-2" {% if shipment.receieved %} checked="checked" {% endif %}>
<label class="form-check-label" for="receieved">
Received ?
</label>
{% endif %}
{% csrf_token %}
<hr>
{% if not form.instance.pk %}
<input type="submit" class="btn btn btn-primary" value="Create Shipment">
{% else %}
<input type="submit" class="btn btn-secondary" value="Update Shipment">
{% endif %}
<a href="{% url 'modalform:shipDetail' %}" class="btn btn-primary">Cancel</a>
</form>
</div>
This is Create Page
<div class="border rounded-1 p-4 d-flex flex-column">
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
{{field.label}}: {{ error|escape }} <br>
{% endfor %}
{% endfor %}
{% endif %}
</div>
{% endblock %}
urls.py
from django.urls import re_path as url
from .views import ProductCreateView, ShipmentCreateView, ShipmentListView,ShipmentUpdateView, ShipmentDeleteView
app_name = 'modalform'
urlpatterns = [
url(r'^$', ShipmentListView.as_view(), name='shipDetail'),
url(r'^create_prod/$', ProductCreateView.as_view(), name='create_prod'),
url(r'^create_ship/$', ShipmentCreateView.as_view(), name='create_ship'),
url(r'^update_ship/(?P<pk>\d+)/$', ShipmentUpdateView.as_view(), name='update_ship'),
url(r'^delete_ship/(?P<pk>\d+)/$', ShipmentDeleteView.as_view(), name='delete_ship'),
]
В форме Create Shipment
поля OrderDate
и Received
не отображаются и после создания устанавливаются как datetime.now
и False
соответственно.
Когда я пытаюсь update
отправить груз, я могу получить сохраненные значения для всех полей, кроме receieved
. Это значение всегда отображается как False
, даже когда значение в Backend равно True, и также правильно отображается в ShipmentListView.
Примечание: Поскольку форма UpdateView не показывала данные сохранения автоматически, я использовал {{shipment.field_name}} для установки значений полей.