How do I hyperlink an item returned from a queryset automatically
I have a model
class Transaction(models.Model):
sender = models.ForeignKey(MyBankAccount, unique=False, related_name="transactions_sent")
receiver = models.ForeignKey(RecipientBankAccount, unique=False, related_name="transactions_received")
created = models.DateField('transfer request date')
amount = models.FloatField()
createdby=models.ForeignKey(User,null=True)
which I display using
<li>{{ item.sender }} {{ item.receiver }} {{ item.amount 开发者_StackOverflow社区}}</li>
I d like item.sender to be automatically hyperlinked to
http://example.com/johnsmith/trans/ where johnsmith is the name of the user that creates the transaction (aka createdby). I already implemented the view of this url. I just need to link to it.
So, presumably your url.py looks something like:
urlpatterns = patterns(
'',
# Patterns:
url(r'^(?P<username>[\w-]+)/(?P<createdby>[\w-]+)/$', transaction, name="transaction"),
....
Your view is:
def transaction(request, username, createdby):
...
Then your template fragment is:
<a href="{% url transaction item.sender item.receiver %}">{{ item.sender }}</a>
Or you could define the following in your Transaction
class (the urls.py file must remain):
def get_absolute_url(self):
from django.core.urlresolvers import reverse
return reverse('transaction', kwargs={'username': self.sender, 'createdby': self.receiver})
And then your template would look like:
<a href="{{ item.get_absolute_url }}">{{ item.sender }}</a>
But geez, this is all Django 101.
精彩评论