Skip to content Skip to sidebar Skip to footer

Django Restrict Pages To Certain Users

I have starting trying to implement users on a website I am working on. Perhaps this is not a good method as I am new to django; what I have so far is a simple template check to pr

Solution 1:

Ideally you want to keep this kind of logic out of the template. Calculate the download url in the view, and pass it to the template. Then your template simplifies to something like:

{% if download_url %}<a href="{{ download_url }}">Download</a>{% else %}No downloads{% endif %}

In your view, you can start with an if/elif statement to determine the download url.

defget_download_url(self):
    if user.username == 'user1':
        download_url = '/downloads/user1/'elif user.username == 'user2':
        download_url = '/downloads/user2/'else:
        download_url = None

If that gets to complex, you could use a dictionary or a database table, and you shouldn't have to update your template.

def get_download_url(user):
    download_urls = {
        'user1': '/downloads/user1/',
        'user2': '/downloads/user2/',
    }
    return download_urls.get(user.username)

Ultimately, you might want to store the information in the database. Note that you do not need a custom user. You just need models with a foreign key/one to one/many to many field that links to user.

class Download(models.Model):
    user= models.OneToOneField('auth.User')  # onetoone field limits toone download url peruser
    download_url = models.CharField()

Then in the view:

defget_download_url(user):
    try:
        download = Download.objects.get(user=user)
        return download.download_url
    except Download.DoesNotExist:
        returnNone

I'm sure all of these snippets could be improved or tweaked to suit your use better. My main point is that you'll find it easier to get the logic correct if you use Python instead of the Django template language.

Solution 2:

Your approach will fall over pretty quickly if a user were to change their name (i.e get married/divorced/funky), What would be better would be to provide a Many-to-many relationship between a downloads model and a user, then you can just iterate over these in your template to retrieve all the downloads available to a particular user.

Post a Comment for "Django Restrict Pages To Certain Users"