在另一个应用程序模板中包含一个应用程序的Django模板

时间:2017-09-08 02:01:24

标签: python django

我试图在用户的个人资料中添加一个显示用户帖子的模板。我使用了包含标签但是帖子没有显示在用户的个人资料中。但它确实可以在主页上工作,该主页设置为该应用程序的PostListView。

userprofile_detail.html中的包含标记:

<div class="content-right">
    {% include 'feed/userpost_list_inner.html' %}
</div>

userpost_list.html中的帖子(Feed)的实际列表:

{% for post in userpost_list %}
    <div class="post">
        <h2 class="post-title">{{ userpost.post.title }}</h2>
        <p class="accent">{{ post.author }}</p>
        <p class="accent">{{ post.post_date }}</p>
        <p class="body">{{ post.post_body }}</p>
    </div>
{% endfor %}

我没有收到任何错误,但帖子没有显示在用户的个人资料页面上。

修改:这是我的Feed应用views.py:

from django.shortcuts import render,get_object_or_404,redirect
from django.utils import timezone
from feed.models import UserPost,UserComment
from feed.forms import PostForm,CommentForm
from django.urls import reverse_lazy
from django.contrib.auth.decorators import login_required

from django.contrib.auth import get_user_model

from django.contrib.auth.mixins import LoginRequiredMixin
from braces.views import SelectRelatedMixin

from django.views.generic import (TemplateView,ListView,
                                    DetailView,CreateView,
                                    UpdateView,DeleteView)

User = get_user_model()

# Create your views here.

##Posts Views
class HomeView(LoginRequiredMixin,ListView):
    login_url = 'login'
    model = UserPost
    ordering = ['-post_date']

class CreatePostView(LoginRequiredMixin,CreateView):
    login_url = 'login'
    redirect_field_name = '/userpost_list.html'
    model = UserPost

    def form_valid(self,form):
        form.instance.author = self.request.user
        self.object = form.save(commit=False)
        self.object.user = self.request.user
        self.object.save()
        return super(CreatePostView, self).form_valid(form)

class UpdatePostView(LoginRequiredMixin,UpdateView):
    login_url = 'login'
    redirect_field_name = '/userpost_detail.html'
    form_class = PostForm
    model = UserPost

class DeletePostView(LoginRequiredMixin,DeleteView):
    model = UserPost
    select_related = ('user',)
    success_url = reverse_lazy('userpost_list')

    def get_queryset(self):
        queryset = super().get_queryset()
        return queryset.filter(user_id=self.request.user.id)

    def delete(self,*args,**kwargs):
        return super().delete(*args,**kwargs)



##Comments Views
def add_comment_to_post(request,pk):
    post = get_object_or_404(UserPost,pk=pk)
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.save()
            return redirect('userpost_list',pk=userpost.pk)
        else:
            form = CommentForm()
        return render(request,'feed/userpost_list.html',{'form':form})

这是我的用户应用views.py:

from django.shortcuts import render
from users.forms import UserForm,UserProfileForm
from users.models import UserProfileInfo

from django.contrib.auth import authenticate,login,logout
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required

from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import (TemplateView,ListView,
                                    DetailView,CreateView,
                                    UpdateView,DeleteView)

# Create your views here.
def user_login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')

        user = authenticate(username=username,password=password)

        if user:
            if user.is_active:
                login(request,user)
                return HttpResponseRedirect(reverse('index'))
            else:
                return HttpResponse("Account now active")

        else:
            print("Login Unsuccessful")
            return HttpResponse("Username and/or password are not correct")

    else:
        return render(request,'login.html',{})

def register(request):
    registered = False

    if request.method == 'POST':
        user_form = UserForm(data=request.POST)
        profile_form = UserProfileForm(data=request.POST)

        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save()
            user.set_password(user.password)
            user.save()

            profile = profile_form.save(commit=False)
            profile.user = user

            if 'profile_pic' in request.FILES:
                profile.profile_pic = request.FILES['profile_pic']

            profile.save()
            registered = True
        else:
            print(user_form.errors,profile_form.errors)
    else:
        user_form = UserForm()
        profile_form = UserProfileForm()

    return render(request,'register.html',{
                                        'user_form':user_form,
                                        'profile_form':profile_form,
                                        'registered':registered
                                        })

@login_required
def user_logout(request):
    logout(request)
    return HttpResponseRedirect(reverse('index'))

class UserListView(ListView):
    model = UserProfileInfo
    ordering = ['-join_date']

class UserProfileView(DetailView):
    model = UserProfileInfo

class UserEditProfileView(LoginRequiredMixin,UpdateView):
    login_url = '/login/'
    redirect_field_name = '/users_detail.html'
    form_class = UserProfileForm
    model = UserProfileInfo

Feed app models:

from django.db import models
from django.core.urlresolvers import reverse
from django.conf import settings

from django.contrib.auth import get_user_model
User = get_user_model()

# Create your models here.
class UserPost(models.Model):
    author = models.ForeignKey(User,related_name='userpost',null=True)
    post_date = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=150,blank=False)
    post_body = models.TextField(max_length=1000,blank=False)

    def publish(self):
        self.save()

    def get_absolute_url(self):
        return reverse('index')

    def __str__(self):
        return self.title

class UserComment(models.Model):
    post = models.ForeignKey('feed.UserPost',related_name='comments')
    author = models.ForeignKey(User,related_name='usercomment')
    comment_date = models.DateTimeField(auto_now_add=True)
    comment_body = models.TextField(max_length=500)

    def publish(self):
        self.save()

    def get_absolute_url(self):
        return reverse("userpost_list")

    def __str__(self):
        return self.text

用户app模型:

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from users.choices import *

# Create your models here.
class UserProfileInfo(models.Model):
    user = models.OneToOneField(User)

    join_date = models.DateTimeField(default=timezone.now)
    profile_pic = models.ImageField(upload_to='profile_pics',blank=True)
    location = models.CharField(max_length=150)
    title = models.CharField(max_length=250)
    user_type = models.IntegerField(choices=USER_TYPE_CHOICES,default=1)
    website = models.URLField(max_length=100,blank=True)
    about = models.TextField(max_length=500,default='about')
    twitter = models.CharField(max_length=50,blank=True)
    dribbble = models.CharField(max_length=50,blank=True)
    github = models.CharField(max_length=50,blank=True)

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

用户应用网址:

from django.conf.urls import url
from users import views

app_name = 'users'

urlpatterns = [
    url(r'^$',views.UserListView.as_view(),name='user_list'),
    url(r'^(?P<pk>\d+)/$',views.UserProfileView.as_view(),name='user_profile'),
    url(r'^(?P<pk>\d+)/edit$',views.UserEditProfileView.as_view(),name='user-profile-edit'),
    url(r'^login/$',views.user_login,name='user_login'),
    url(r'^logout/$',views.user_logout,name='user_logout',kwargs={'next_page':'/'}),
    url(r'^register/$',views.register,name='register'),
]

Feed app urls:

from django.conf.urls import url
from feed import views

app_name = 'feed'

urlpatterns = [
    url(r'^new/$',views.CreatePostView.as_view(),name='new_post'),
    url(r'^post/(?P<pk>\d+)/edit/$',views.UpdatePostView.as_view(),name='edit_post'),
    url(r'^post/(?P<pk>\d+)/delete/$',views.DeletePostView.as_view(),name='delete_post'),
    url(r'^post/(?P<pk>\d+)/comment/$',views.add_comment_to_post,name='add_comment_to_post'),
]

来自答案1的错误回溯:

Traceback (most recent call last):
  File "/anaconda/envs/test/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/anaconda/envs/test/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/anaconda/envs/test/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/garrettlove/Desktop/evverest/users/views.py", line 83, in userprofile
    user = get_object_or_404(UserProfileInfo, user__id=pk)
NameError: name 'get_object_or_404' is not defined

1 个答案:

答案 0 :(得分:0)

这是因为userpostuserprofile_detail.html对象不可用。它仅在userpost_list.html中提供。

通过使用视图将其发送到userprofile_detail.html使其可用,它将显示。

from feed.models import UserPost
from .models import UserProfileInfo
from django.shortcuts import render,get_list_or_404,get_object_or_404

def userprofile(request,pk):
    user = get_object_or_404(UserProfileInfo, user__id=pk)
    userpost_list = UserPost.objects.filter(author__id=pk)

    context={'user':user, 'userpost_list':userpost_list}
    return render(request, 'yourtemplate/html', context)

现在位于 urls.py

url(r'^(?P<pk>\d+)/$',views.userprofile,name='user_profile'),