marckr
marckr

Reputation: 59

Use foreign key as variable in Django template

I am new to Django and Python (and even newish to programming) and am now creating my first application. I have a model that includes a foreign key, which is a many-to-one relation (a line can hold many articles, but every article only relates to one line). In my template I want to concatenate a number of values to create an url for an image source.

relevant information in models.py:

class Article(models.Model):
  line = models.ForeignKey(Line, null=True)
  article = models.CharField(max_length=128)
  slug = models.SlugField(null=True)

class Line(models.Model):
  line = models.CharField(max_length=128, unique=True)

The relevant view sends Article.objects.get(slug=article_slug) as article in context_dict to the template. In my template I include the following and returns the expected values correctly: {{ article.article }} and {{ article.line }}. If I concatenate the value of article.article it returns the expected value:

{% with article.article as a %}

Here {{ a }} shows the value of article.article. However when I try concatenate the value of article.line, I get no value.

{% with article.line as l %}

{{ l }} doesn't return anything. I assume this is because the foreign key can also be interpreted as one-to-many and so I tried to specify which value (I also used variations such as article.line.all.0).

{% with article.line_set|first as l %}

Here {{ l }} also doesn't return anything.

Why can I return the value of article.line as text in the template, but I can't include it in a concatenation?

Upvotes: 1

Views: 857

Answers (1)

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52103

article.line_set is not the correct way of printing related Line objects as there is no such relation between them.

As for the problem, it is very likely that article.line is None and I think Django template engine is silently suppressing possible Models.DoesNotExist exception when trying to access .line property of the article.line instance which is null.

Make sure article.line is not None so that you can print out the text representation of it as follows:

{% with article.line.line as l %}

Upvotes: 1

Related Questions