如何让FileField仅供登录用户下载?
答案 0 :(得分:2)
如果要向用户显示不同的表单,则需要不同的ModelForm(或仅表单)。此表单应如下所示:
class FormWithoutFormField(RegularForm):
class Meta:
exclude = ('field_name',)
这包含您要显示的新表单内部。请注意,您正在扩展您正在使用的其他表单。这应该保持几乎所有的完整,你可以简单地排除你不想要的字段。
然后,您需要检查用户是否已在视图中的某个位置登录。就是这样:
if request.user.is_authenticated():
form_class = FormWithoutFileField
else:
form_class = RegularForm
# Do whatever you did with the normal form, but now with the new form.
答案 1 :(得分:1)
您没有解释是否需要django管理员或自定义模板。如果是自定义模板/视图,则不需要其他表单,只需在模板中执行此操作即可。
<div id="blah">
{% if user.is_authenticated %}
<a href="{{ somemodel.somefilefield.url }}">Download the file</a>
{% else %}
<p>No downloading for you!</p>
{% endif %}
</div>
前提是您已阅读django中的handling static files。