【问题标题】:Django NameError: name ' ' is not definedDjango NameError:名称\'\'未定义
【发布时间】:2022-10-16 15:06:42
【问题描述】:

我正在尝试创建一个按主题过滤博客帖子的视图,我在我的帖子表单中添加了一个名为“主题”的字段,并且,

我创建了一个视图: 我在 urls.py 中定义了路径:

我在终端中收到此错误:

    model = Post
    template_name = 'blog/political_posts.html' # <app>/<model>_<viewtype>.html
    context_object_name = 'posts'
    paginate_by = 5

    def get_queryset(self):
        user = get_object_or_404(User, username=self.kwargs.get('username'))
        return Post.objects.filter(topic=Political).order_by('date_posted') ```



```    path('politics/', PoliticalPostListView.as_view(), name='political-posts'), ```

I used a template from a working user_posts.html to test:

``` {% extends "blog/base.html" %}
{% block content %}
    <h1 class="md-3"> Posts by {{ view.kwargs.username }} ({{ page_obj.paginator.count }})</h1>
    {% for post in posts %}
        <article class="media content-section">
            <img class="rounded-circle article-img" src="{{post.author.profile.image.url }}">
            <div class="media-body">
            <div class="article-metadata">
                <a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{ post.author }}</a>
                <small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small>
                <small class="text-muted">{{ post.topic }}</small>
            </div>
            <h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2>
            <p class="article-content">{{ post.content }}</p>
            </div>
        </article>
    {% endfor %} ```
 

File "/Users/leaghbranner/Desktop/django_project/blog/urls.py", line 21, in <module>
    path('politics/', PoliticalPostListView.as_view(), name='political-posts'),
NameError: name 'PoliticalPostListView' is not defined

And "This Site Cannot Be Reached." pagein my browser.

Any thoughts?

【问题讨论】:

  • 您需要在 urls.py 中导入 PoliticalPostListView
  • 'PoliticalPostListView' 是您正在使用的 views.py 中的视图名称。请检查视图名称和您在 url.py 中定义的视图名称是否相同

标签: python django django-models django-views django-forms


【解决方案1】:

在你的urls.py。

如果像这样使用导入:

from . import views

# then use:
path('politics/', views.PoliticalPostListView.as_view(), name='political-posts'),

但如果使用:

from .views import PoliticalPostListView

# then use:
path('politics/', PoliticalPostListView.as_view(), name='political-posts'),

【讨论】:

    猜你喜欢
    • 2018-07-14
    • 2017-12-25
    • 2021-07-17
    • 2012-05-13
    • 2017-08-17
    • 2020-02-24
    • 2021-04-14
    • 2020-08-17
    • 2021-03-09
    相关资源
    最近更新 更多