我有一个Model
,其中UUID为pk。
class Product(models.Model):
uuid = models.UUIDField(
primary_key=True,
default=uuid.uuid4,
editable=False)
我需要使用ModelForm
编辑其他一些字段,并且需要在POST数据中提交UUID以识别Product
。目前,我得到了:
django.core.exceptions.FieldError: 'uuid' cannot be specified for Product model form as it is a non-editable field
显然,我可以让这个字段不可编辑,以便快速解决这个问题。然而,在我看来,拒绝对该字段的写访问应该发生在比ModelForm
更低的逻辑级别(即我认为应该在尝试编辑它时引发异常)。是否可以这样做呢?
编辑:清理回溯
File "/webapps/myapp/urls.py", line 6, in <module>
from my_app import views
File "/webapps/myapp/views/__init__.py", line 2, in <module>
from .my_view import MyView
File "/webapps/myapp/views/my_view.py", line 12, in <module>
from my_app.forms import ProductForm
File "/webapps/myapp/forms.py", line 5, in <module>
class ProductForm(forms.ModelForm):
File "/webapps/myapp/lib/python3.5/site-packages/django/forms/models.py", line 242, in __new__
opts.field_classes)
File "/webapps/myapp/lib/python3.5/site-packages/django/forms/models.py", line 138, in fields_for_model
f.name, model.__name__)
django.core.exceptions.FieldError: 'uuid' cannot be specified for Product model form as it is a non-editable field
表格代码:
class ProductForm(forms.ModelForm):
uuid = forms.UUIDField(required=False, widget=forms.HiddenInput())
答案 0 :(得分:1)
指定表单的instance
argument以更改现有对象:
def edit_product(request, uuid):
product = get_object_or_404(Product, uuid=uuid)
...
if request.method == 'POST':
form = ProductForm(request.POST, instance=product)
if form.is_valid():
form.save()
...