我正在编写完全用Django编写的论坛应用程序,但是每当我尝试访问没有头像的用户主题时(我不想让它成为必需),它就会引发ValueError。我已尝试评论模板上所有提及化身的内容,但仍然无法正常工作。
topic.html(模板)
{% for post in posts %}
<div class="row mb-3">
<div class="col-sm-10">
<div class="d-flex col mt-0 text-white" style="background-image: linear-gradient(to right, darkblue , blue);">
{{ topic.titleName }}
</div>
<div class="d-flex col bg-secondary">
<div class="row">
<div class="col-sm-3 border-right border-light">
<!--img src="{{post.author.avatar.url|default:"user_avatars/None/placeholder.jpg"}}" alt=" " class="avatar-forum rounded-circle"-->
<br>
{{ post.author }}
</div>
<div class="col-sm-9">
<div class="d-flex col">
Przez:{{post.author}} >> {{ post.created_date }}
</div>
<div class="d-flex col">
{{ post.postData }}
</div>
</div>
</div>
</div>
</div>
<div class="col-sm-2">
</div>
</div>
{% endfor %}
views.py-独立主题的视图
def RBFTopic(request, slug):
topic = get_object_or_404(Topic, titleSlug = slug)
posts_list = Post.objects.filter(topic = topic.pk)
paginator = Paginator(posts_list, 20)
page = request.GET.get('page', 1)
try:
posts = paginator.page(page)
except PageNotAnInteger:
posts = paginator.page(1)
except EmptyPage:
posts = paginator.page(paginator.num_pages)
return render(request, 'topic.html', {'topic': topic, 'posts':posts})
models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
avatar = models.ImageField(upload_to='user_avatars/', default = 'user_avatars/None/placeholder.jpg')
is_blocked = models.BooleanField(default=False)
@receiver(post_save, sender=User)
def update_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
instance.profile.save()
def __str__(self):
return self.user.username
...
#Model of forum topic
class Topic(models.Model):
author = models.ForeignKey(Profile,null=True, on_delete=models.SET_NULL)
titleCat = models.ForeignKey(Category, on_delete=models.CASCADE)
titleName = models.CharField(max_length=200)
created_date = models.DateTimeField(default=timezone.now)
titleSlug = models.SlugField()
def save(self, *args, **kwargs):
if not self.id:
# Newly created object, so set slug
self.titleSlug = slugify(self.titleName)
super(Topic, self).save(*args, **kwargs)
def __str__(self):
return self.titleName
#Model of forum post
class Post(models.Model):
author = models.ForeignKey(Profile,null=True, on_delete=models.SET_NULL)
topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
postData = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
跟踪
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/retrobaza/topic/x
Django Version: 2.1.7
Python Version: 3.7.2
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'retrobaza']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Template error:
In template D:\ZPW\mysite\retrobaza\templates\base.html, error at line 11
The 'avatar' attribute has no file associated with it.
1 : {% load static %}
2 : <!DOCTYPE html>
3 : <html>
4 : <head>
5 : <title>RetroBaza.pl</title>
6 : <meta charset="UTF-8">
7 : <link href="https://fonts.googleapis.com/css?family=Merriweather|VT323" rel="stylesheet">
8 : <link rel="stylesheet" href="{% static 'styles/basestyle.css' %}">
9 : <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
10 : <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
11 : <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/ popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clH TMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
12 : <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
13 : </head>
14 : <body>
15 : <div class="pageHeader">
16 : <div class="title">
17 : <h1><a href="{% url 'retrobaza-index' %}">RetroBaza-Nowe miejsce dla starych maszyn</a></h1>
18 : </div>
19 : <nav class="mb-1 navbar navbar-expand-lg navbar-dark default-color ">
20 : <a class="navbar-brand" href="{% url 'retrobaza-index' %}">RetroBaza</a>
21 : <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent-333"
Traceback:
File "D:\ZPW\env\lib\site-packages\django\template\base.py" in _resolve_lookup
829. current = current[bit]
During handling of the above exception ('ImageFieldFile' object is not subscriptable), another exception occurred:
File "D:\ZPW\env\lib\site-packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "D:\ZPW\env\lib\site-packages\django\core\handlers\base.py" in _get_response
126. response = self.process_exception_by_middleware(e, request)
File "D:\ZPW\env\lib\site-packages\django\core\handlers\base.py" in _get_response
124. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\ZPW\mysite\retrobaza\views.py" in RBFTopic
70. return render(request, 'topic.html', {'topic': topic, 'posts':posts})
File "D:\ZPW\env\lib\site-packages\django\shortcuts.py" in render
36. content = loader.render_to_string(template_name, context, request, using=using)
File "D:\ZPW\env\lib\site-packages\django\template\loader.py" in render_to_string
62. return template.render(context, request)
File "D:\ZPW\env\lib\site-packages\django\template\backends\django.py" in render
61. return self.template.render(context)
File "D:\ZPW\env\lib\site-packages\django\template\base.py" in render
171. return self._render(context)
File "D:\ZPW\env\lib\site-packages\django\template\base.py" in _render
163. return self.nodelist.render(context)
File "D:\ZPW\env\lib\site-packages\django\template\base.py" in render
937. bit = node.render_annotated(context)
File "D:\ZPW\env\lib\site-packages\django\template\base.py" in render_annotated
904. return self.render(context)
File "D:\ZPW\env\lib\site-packages\django\template\loader_tags.py" in render
150. return compiled_parent._render(context)
File "D:\ZPW\env\lib\site-packages\django\template\base.py" in _render
163. return self.nodelist.render(context)
File "D:\ZPW\env\lib\site-packages\django\template\base.py" in render
937. bit = node.render_annotated(context)
File "D:\ZPW\env\lib\site-packages\django\template\base.py" in render_annotated
904. return self.render(context)
File "D:\ZPW\env\lib\site-packages\django\template\loader_tags.py" in render
62. result = block.nodelist.render(context)
File "D:\ZPW\env\lib\site-packages\django\template\base.py" in render
937. bit = node.render_annotated(context)
File "D:\ZPW\env\lib\site-packages\django\template\base.py" in render_annotated
904. return self.render(context)
File "D:\ZPW\env\lib\site-packages\django\template\defaulttags.py" in render
209. nodelist.append(node.render_annotated(context))
File "D:\ZPW\env\lib\site-packages\django\template\base.py" in render_annotated
904. return self.render(context)
File "D:\ZPW\env\lib\site-packages\django\template\base.py" in render
987. output = self.filter_expression.resolve(context)
File "D:\ZPW\env\lib\site-packages\django\template\base.py" in resolve
671. obj = self.var.resolve(context)
File "D:\ZPW\env\lib\site-packages\django\template\base.py" in resolve
796. value = self._resolve_lookup(context)
File "D:\ZPW\env\lib\site-packages\django\template\base.py" in _resolve_lookup
837. current = getattr(current, bit)
File "D:\ZPW\env\lib\site-packages\django\db\models\fields\files.py" in url
61. self._require_file()
File "D:\ZPW\env\lib\site-packages\django\db\models\fields\files.py" in _require_file
38. raise ValueError("The '%s' attribute has no file associated with it." % self.field.name)
Exception Type: ValueError at /retrobaza/topic/x
Exception Value: The 'avatar' attribute has no file associated with it.
答案 0 :(得分:0)
问题是您正在访问url
字段的avatar
属性,但不确定是否为空:
<img src={{post.author.avatar.url|default:"user_avatars/None/placeholder.jpg"}}" alt=" " class="avatar-forum rounded-circle">
执行此操作:
{% if post.author.avatar %}
<img src="{{ post.author.avatar.url }}" alt=" " class="avatar-forum rounded-circle">
{% else %}
<img src="user_avatars/None/placeholder.jpg" alt=" " class="avatar-forum rounded-circle">
{% endif %}