首页 > 解决方案 > 如何根据会话用户将只读属性设置为整个 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 %}

标签: pythondjangodjango-forms

解决方案


首先,如果您只想让用户查看详细信息,那么您不需要表单。您可以在 p 标签或标题标签中显示用户数据。其次,您可以设置 html 输入标签的只读属性,这样用户就不会对其进行编辑。

  • 你可以在 forms.py attr 对象中添加 attrs={"readonly": "true"} //
  • 或者你可以使用 jquery : $('input').attr('readonly', true);

推荐阅读