Question

How can I make the FileField only available to download for logged in users ?

Was it helpful?

Solution

You need a different ModelForm (or just Form) if you want to display a different form to the user. This form should look something like this:

class FormWithoutFormField(RegularForm):
    class Meta:
        exclude = ('field_name',)

This goes inside of the new form that you want to display. Note that you're extending the other form you were using. This should keep just about everything intact, and you can simply exclude the field you don't want.

You then need to check if the user is logged in somewhere in your view. That is, something like:

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.

OTHER TIPS

You didn't explain if you need it for the django admin or a custom template. If it is for a custom template/view you don't need a different form, just do this in your template.

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

Provided that you've read about handling static files in django.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top