Django:如果用户是工作人员,如何排除表单域? [英] Django : How to exclude form field if the user is staff?

查看:160
本文介绍了Django:如果用户是工作人员,如何排除表单域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果用户不是员工,如何排除表单域?我试过这个,但没有工作,给出错误:

How to exclude form fields if the user is not staff ? I tried this but didn't work , giving an error :

全局名称'user'未定义 / p>

global name 'user' is not defined

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']

view.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))


推荐答案

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

This can be achieved in the template when rendering the form. It will need to allow null values or have a default value in the model definition or alternatively have its validation overridden:

<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

Similarly you can check for is_superuser or check permissions, see the docs: https://docs.djangoproject.com/en/dev/topics/auth/default/#permissions

这篇关于Django:如果用户是工作人员,如何排除表单域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆