【问题标题】:template code not working in different app template模板代码在不同的应用程序模板中不起作用
【发布时间】:2021-01-12 04:02:11
【问题描述】:

我尝试学习 Django,我确信我的问题很愚蠢,但我认为每个初学者都必须通过这条成功之路,当然要在专业人士的帮助下。

另外,我有一个包含 2 个应用程序、配置文件和帖子的网站在这个项目中,我可以在模板 (posts/main.html) 的列表中看到我关注的人,问题是我也需要相同的列表另一个模板(profiles/main.html)。

我已经复制了一段代码,但它不起作用。我真的不知道如何更好地解释它,或者我不知道如何准确搜索它。 我试过这个: 1.) 如何在不同的应用模板中使用视图 2.) 如何从其他应用视图导入视图 3.) 还有更多,我阅读了所有的东西,但找不到我要找的东西

非常感谢您的帮助。

发帖应用

posts/models.py

class Post(models.Model):
    ...
    author = models.ForeignKey(Profile, on_delete=models.CASCADE)
    text = models.TextField(default='no text...')
    ...
    def __str__(self):
        return str(self.text)[:30]

posts/urls.py

from django.urls import path
from .views import posts_of_following_profiles, index, contact, about, category, PostListView, PostDetailView, post, detay
from profiles.views import ProfileListView
app_name="posts"

urlpatterns = [
    ...
    path('following/', ProfileListView.as_view(), name='posts-follow-view'),
    ...
    ]

posts/views.py

def posts_of_following_profiles(request):
    
    # get logged in user profile
    profile = Profile.objects.get(user=request.user)

    # check who we are following
    users = [user for user in profile.following.all()]

    # initial values for variables
    posts = []
    qs = None

    # get the posts of people who we are following
    for u in users:
        p = Profile.objects.get(user=u)
        p_posts = p.post_set.all()
        posts.append(p_posts)
    
    # our posts
    my_posts = profile.profile_posts()
    posts.append(my_posts)

    # sort and chain qs and unpack the post list
    if len(posts)>0:
        qs = sorted(chain(*posts), reverse=True, key=lambda obj: obj.ilan_tarihi)


    return render(request, 'posts/main.html', {'profile':profile, 'posts':qs})

posts/main.html

这部分运行良好

<h3>list of followings</h3>
{% for p in profiles.following.all %}
<br>{{p}} <br>
{% endfor %}

个人资料应用

profiles/models.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    following = models.ManyToManyField(User, related_name='following', blank=True)
    text = models.TextField(default='no text...')
    
    def profile_posts(self):
        return self.post_set.all()

    def __str__(self):
        return str(self.user.username)  

profiles/urls.py

from django.urls import path
from .views import ProfileListView, ProfileDetailView, follow_unfollow_profile
from posts.views import posts_of_following_profiles

app_name = 'profiles'

urlpatterns = [
    path('switch_follow/', follow_unfollow_profile, name='follow-unfollow-view'),
    path('portfolio/', posts_of_following_profiles, name='profile-list-view'),
    path('<pk>/', ProfileDetailView.as_view(), name='profile-detail-view'),
]

profiles/views.py

def follow_unfollow_profile(request):
    if request.method=="POST":
        my_profile = Profile.objects.get(user=request.user)
        #profile_pk is the name of the input in detail.html
        pk = request.POST.get('profile_pk')
        obj = Profile.objects.get(pk=pk)

        if obj.user in my_profile.following.all():
            my_profile.following.remove(obj.user)
        else:
            my_profile.following.add(obj.user)
        return redirect(request.META.get('HTTP_REFERER'))
    return redirect('profiles:profile-list-view') 

profiles/main.html

这就是我想要的,这个代码不起作用(它与 posts/main.html 中的代码相同)

<h3>list of followings</h3>
{% for p in profiles.following.all %}
<br>{{p}} <br>
{% endfor %} 

 

【问题讨论】:

    标签: django django-models django-views django-templates django-urls


    【解决方案1】:

    在profiles/urls.py中,即使你已经导入了follow_unfollow_profile(view)。 试试下面的代码:

    path('switch_follow/', views.follow_unfollow_profile, name='follow-unfollow-profile'),

    这就是 django 能够设置路径但无法按照 views.py 文件中提到的说明进行操作的原因。

    还要确保,

    'DIRS':[TEMPLATE_DIR,],

    包含在根目录的 settings.py 文件中,在 TEMPLATES 部分下。

    【讨论】:

    • 我的 settings.py : 'DIRS': [os.path.join(BASE_DIR, 'templates')], 编辑后的 ​​urls.py: from django.urls import path from .views import ProfileListView, ProfileDetailView,follow_unfollow_profile 来自 .从 posts.views 导入视图 import posts_of_following_profiles app_name = 'profiles' urlpatterns = [ path('switch_follow/', views.follow_unfollow_profile, name='follow-unfollow-profile'), path('portfolio/', posts_of_following_profiles, name=' profile-list-view'), path('/', ProfileDetailView.as_view(), name='profile-detail-view'), ] 但没有任何改变