4👍
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.
1👍
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.