gpt4 book ai didi

Django : How to exclude form field if the user is staff?

转载 作者:行者123 更新时间:2023-12-02 02:23:28 25 4
gpt4 key购买 nike

如果用户不是员工,如何排除表单字段?我尝试了这个,但没有成功,给出了一个错误:

未定义全局名称“用户”

class PostForm(ModelForm):

class Meta:
model = Photo
exclude = ['author','featured','published']

def __init__(self, *args, **kwargs):
published = kwargs.pop('published', None)
super(PostForm, self).__init__(*args, **kwargs)
if not user.is_staff:
del self.fields['published']

查看.py

def addpost(request):

if request.method == 'POST':
form = PostForm(request.POST,request.FILES,user=request.user)
if form.is_valid():

post = form.save(False)
post.author = request.user
form.save()

return HttpResponseRedirect(reverse('insight.content.views.index', ))

else:
form = PostForm(user=request.user)


ispost = True
return render_to_response('form_add_place.html', {'form': form,'ispost':ispost},context_instance=RequestContext(request))

最佳答案

这可以在渲染表单时在模板中实现。它将需要允许空值或在模型定义中具有默认值,或者覆盖其验证:

<form method="post">{% csrf_token %}
{% if request.user.is_staff %}
<p>{{ form.published }}</p>
{% endif %}

<p>{{ form.author }}</p>

<!-- ... your other fields -->
</form>

同样,您可以检查 is_superuser 或检查权限,请参阅文档:https://docs.djangoproject.com/en/dev/topics/auth/default/#permissions

关于 Django : How to exclude form field if the user is staff?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9900383/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com