python - 如何根据会话用户将只读属性设置为整个 Django 表单
问题描述
我创建了一个可用于更新/创建/查看记录的表单。当用户选择记录时,记录数据将呈现在表单中。这样用户就可以查看/编辑表单。这里的问题陈述是,如果记录是由其他用户创建的,那么会话用户将无法编辑(只有创建者应该有权编辑)。
我正在考虑编写一个逻辑,以便当会话用户创建记录时,只有他/她会编辑。否则,用户将仅使用相同的表单查看记录。
下面是我的视图文件
current_blog = Blog.objects.get(pk=blog_id)
init_dict = {
"blog_title": current_blog.blog_title,
"blog_description": current_blog.blog_description,
"last_modified": current_blog.last_modified
}
form = NewBlog(initial=init_dict)
return render(request, "myblog/blog.html", {"new_blog": form})
表格.py
class NewBlog(forms.Form):
blog_title = forms.CharField(label="Form Title", max_length=250, widget=forms.TextInput(
attrs={"class": "form-control", "placeholder": "Enter title here"}
))
blog_description = forms.CharField(label="Blog Description", widget=forms.Textarea(
attrs={"class": "form-control", "placeholder": "Enter blog Description"}
))
博客.html
{% for field in new_blog %}
<div class="col-sm-12">
<fieldset>
{{ field.label }}
{{ field }} <div class="text-danger">{{ field.errors }}</div>
</fieldset>
</div>
{% endfor %}
解决方案
首先,如果您只想让用户查看详细信息,那么您不需要表单。您可以在 p 标签或标题标签中显示用户数据。其次,您可以设置 html 输入标签的只读属性,这样用户就不会对其进行编辑。
- 你可以在 forms.py attr 对象中添加 attrs={"readonly": "true"} //
- 或者你可以使用 jquery : $('input').attr('readonly', true);
推荐阅读
- node.js - ava 动态语法导入启用支持
- r - 使用R中的“openxl”将数据添加到excel文件中的新工作表
- c# - 覆盖 AspNetCore.Identity 表中的默认索引
- android - 回到 com.android.incallui 中的活动 InCallActivity
- excel - 向下拖动到相邻行时对值或单元格引用进行硬编码
- angular-material - 从 angular5 的按钮列表中禁用垫子按钮
- laravel - 我可以通过选项数组在 if 语句中进行比较吗
- oracle - 选择数字范围不重叠的位置
- jenkins - Jenkins 管道中的列表和并行任务
- python - 如何在不创建列表的情况下调用生成器?