Reputation: 175
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 provide different links to different people:
{% extends 'base.htm' %}
{% block content %}
{% if user.username == 'user1' %}
<p>User 1 Downloads</p>
{% elif user.username == 'user2' %}
<p>User 2 Downloads</p>
{% else %}
<p>There are no Downloads for this User</p>
{% endif %}
{% endblock %}
This is a new site for my company and I expect to have maybe 20 users at most and while I could if/case through them there is probably a better way to do this. In addition I would like to be able to have for example: user1 to user5 have access to download 1, user6 to user10 have access to download 2, etcetera. Is this something already accounted for in django that I can implement or do I need to make my own users table with an "access" column with an id to be used for what they can see, rather than using the username?
Upvotes: 3
Views: 2314
Reputation: 309089
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.
def get_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') # one to one field limits to one download url per user
download_url = models.CharField()
Then in the view:
def get_download_url(user):
try:
download = Download.objects.get(user=user)
return download.download_url
except Download.DoesNotExist:
return None
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.
Upvotes: 4
Reputation: 43320
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.
Upvotes: 1