Reputation: 452
I can't seem to grasp this very well. So I have an Album model, which is using a class based view and I'm giving it the context with all objects:
class Album(models.Model):
# Columns
artist = models.CharField(max_length=50)
album_title = models.CharField(max_length=200)
genre = models.CharField(max_length=100)
album_logo = models.FileField()
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
The default was put to see if it was working within the Admin page, which it did. On every Album object there was a user field, but when I tried to display it on a template, it wasn't showing.
{% for album in all_albums %}
<h2>{{ album.album_title }}</h2>
<h4>{{ album.artist }}</h4>
<h6 class="text-muted">Created by: {{ album.user }}</h6>
{% endfor %}
The album_title and artist displayed just fine, but not the User (str is username). When I tried getting it up on the shell, I got this:
django.contrib.auth.models.DoesNotExist: User matching query does not exist.
EDIT: I just noticed this. On the template tag I do this:
<h6 class="text-muted">Created by: {{ album.user_id }}</h6>
And it does display the user id that corresponds to that individual Album. But there's no method for the username or the email, etc.
Upvotes: 3
Views: 1740
Reputation: 46290
The error says it:
django.contrib.auth.models.DoesNotExist: User matching query does not exist.
Apparently the user id stored in the foreign key column of the album table does not exist in the user table. It's best to not have dead foreign key relations, then you won't have these errors.
However, it might still happen sometimes. You can protect yourself against it like this:
try:
user = album.user
except DoesNotExist:
user = None
In templates you unfortunately cannot do this. So you'll have to do it in python and pass it in the template context or you could make a custom template tag where you put these try except lines.
Upvotes: 2
Reputation: 357
Well Hello There.
Let's look at this question from the information you gave us.
You are trying to reference a model within your template and access that models foreign key values.
example
record = Example.objects.get()
# pass into context
context = {"record": record}
#
# now we access in template
{{ record.user.username }}
Make sure you are getting the record. "DoesNotExist" seems to indicate you haven't correctly queried, or the record you are searching for is not correct, check username and password and auth settings.
Make sure you pass it to the context of the template hence "record". You access the foreign relations by {{ record.user (object) }} {{ record.user.username (ex. id, username, email, etc.) }}
Upvotes: 1