当我尝试创建帖子时,它会显示此错误
Exception Type: AttributeError at /home/
Exception Value: 'HomeView' object has no attribute 'user'
我的view.py是
class HomeView(TemplateView):
template_name = 'home/home.html'
def get(self, request):
form = HomeForm()
posts = Post.objects.all().order_by('-created')
users = User.objects.exclude(id=request.user.id)
friend = Friend.objects.get(current_user=request.user)
friends = friend.users.all()
args = {
'form': form, 'posts': posts, 'users': users, 'friends': friends
}
return render(request, self.template_name, args)
@login_required
def post(self, request):
if request.method == 'POST':
form = HomeForm(request.POST or None, request.FILES or None)
if form.is_valid():
post = form.save(commit=False)
post.user = request.user
post.save()
return redirect('home:home')
else:
return redirect(reverse('home:home'))
else:
form = HomeForm()
args = {'form': form}
return render(request, self.template_name, args)
回溯:
文件 " /home/zola/lib/python3.5/site-packages/django/core/handlers/exception.py" 在内心 39. response = get_response(request)
文件 " /home/zola/lib/python3.5/site-packages/django/core/handlers/base.py" 在_get_response中 187. response = self.process_exception_by_middleware(e,request)
文件 " /home/zola/lib/python3.5/site-packages/django/core/handlers/base.py" 在_get_response中 185. response = wrapped_callback(request,* callback_args,** callback_kwargs)
文件 " /home/zola/lib/python3.5/site-packages/django/views/generic/base.py" 在视野中 68.返回self.dispatch(request,* args,** kwargs)
文件 " /home/zola/lib/python3.5/site-packages/django/views/generic/base.py" 在发货 88.返回处理程序(request,* args,** kwargs)
文件 " /home/zola/lib/python3.5/site-packages/django/contrib/auth/decorators.py" 在_wrapped_view中 22.如果是test_func(request.user):
请帮助
我已经失踪很久了。使用这种语言。然后帮我解决这个错误
答案 0 :(得分:4)
而不是使用@login_required
装饰器,在post方法上使用@method_decorator(login_required)
,如下所示:
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
class HomeView(TemplateView):
# ...
@method_decorator(login_required)
def post(self, request):
# ...
您之所以看到错误消息,是因为login_required
是函数装饰器 - 因此它希望request
对象成为传递的第一个参数在你看来您的post
定义是方法,因此self
(HomeView
)是第一个被传递的参数,这就是{{1尝试用作Request实例。
login_required
用于将每个函数装饰器转换为方法装饰器。 See the docs for more info