Search code examples
djangodjango-file-upload

Django: Making filefield only available to logged in users


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


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.