如何在Django的类视图UpdateView中添加不可编辑的UUID字段?
解决Django UpdateView显示不可编辑UUID字段的方案
下面提供三种可行的解决方案,按需选择:
方法1:直接在模板中调用对象UUID(最简单)
UpdateView会自动将当前编辑的对象传入模板上下文,你可以直接在模板里通过object或模型小写名称(比如employee)访问UUID,无需修改视图代码:
模板wfp/employee.html中生成链接的示例:
<a href="{% url 'item_allocation' employee_uuid=object.uuid %}">查看该员工的物品分配</a> <!-- 或者用模型名小写,效果一致 --> <a href="{% url 'item_allocation' employee_uuid=employee.uuid %}">查看该员工的物品分配</a>
方法2:通过get_context_data主动传递UUID到视图
如果需要在视图里做额外处理后再传递UUID,可以重写get_context_data方法,把UUID单独存入上下文:
修改后的视图代码:
class EmployeeView(generic.edit.UpdateView): model = Employee fields = '__all__' template_name = 'wfp/employee.html' def get_object(self, queryset=None): return Employee.objects.get(uuid=self.kwargs.get("employee_uuid")) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # 将UUID存入上下文,模板中用{{ employee_uuid }}调用 context['employee_uuid'] = self.object.uuid return context
模板中使用示例:
<a href="{% url 'item_allocation' employee_uuid=employee_uuid %}">查看物品分配</a>
方法3:自定义表单让UUID显示为不可编辑字段
如果希望UUID在表单中显示(但禁止修改),可以自定义ModelForm,给UUID字段添加disabled或readonly属性:
首先定义表单:
from django import forms from .models import Employee class EmployeeForm(forms.ModelForm): class Meta: model = Employee fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # 设为不可编辑,用户无法修改 self.fields['uuid'].widget.attrs['disabled'] = True # 也可以用readonly,视觉效果略有不同 # self.fields['uuid'].widget.attrs['readonly'] = True
然后修改视图使用这个表单:
class EmployeeView(generic.edit.UpdateView): model = Employee form_class = EmployeeForm # 指定自定义表单 template_name = 'wfp/employee.html' def get_object(self, queryset=None): return Employee.objects.get(uuid=self.kwargs.get("employee_uuid"))
模板中既可以显示表单里的UUID字段,也可以用它生成链接:
<!-- 显示不可编辑的UUID字段 --> <div class="form-group"> <label>员工UUID</label> {{ form.uuid }} </div> <!-- 生成链接 --> <a href="{% url 'item_allocation' employee_uuid=form.uuid.value %}">查看物品分配</a>
内容的提问来源于stack exchange,提问作者Sam
相关产品推荐
相关产品推荐

