0

在过去的 2 小时里,我一直在尝试在 Django 1.5 中完成以下任务:我想根据存储在会话中的用户电子邮件从我的数据库中检索记录。这是我的理想算法:

In my function based view:
1. Attempt Login
2. If account exists, log user in and save email in request.session['email']

In my DetailView:
1.Get the email from the session and save it to a variable; email.
2. Create a queryset to retrieve the account filtering by email

我已经参考了有关此问题的文档帖子,但似乎无法理解。我决定使用get方法来检索会话并且它可以工作......唯一的问题是我不确定如何访问此方法返回的变量。我查看了这个答案,但没有发现它太有帮助。如果这个问题存在其他地方指向我,所以我可以删除这个。谢谢!



#views.py CBV snippet
class AccountDetailView(DetailView):
    model = Account
    template_name = 'accounts/view_account.html'
    queryset = Account.objects.filter(verified=1)
    slug_field = 'username'
    slug_url_kwarg = 'username'

    def get(self, request, *args, **kwargs):
        email = request.session['email']
        #just to make sure we've accessed the session...print to screen
        return HttpResponse(email)

#views.py FBV snippet
def AccountLogin(request):
    template_name = 'accounts/login.html'
    if request.method == 'POST':
        form = AccountLoginForm(request.POST)
        if form.is_valid() and form is not None:
            clean = form.cleaned_data
            try:
                #only allow login for verified accounts
                account = Account.objects.get(email=clean['email'])
                if account and account is not None and account.verified == 1:
                    #if account exist log user in
                    user = authenticate(username=clean['email'], password=clean['password'])
                    #we'll user this later to pull their account info
                    request.session['email'] = account.email
                    #logs user in
                    login(request, user)


这是基于函数的视图中的解决方案……我要如何在基于类的视图中实现它。


def AccountView(request): 
    account = Account.objects.get(verified=1, email=request.session['email'])
    return render(request, 'accounts/view_account.html', {'account': account})

4

2 回答 2

0

我在这个线程Django - Access session in urls.py中找到了我正在寻找的答案,我肯定是“想多了”,而且我也不知道如何访问self.request.user. 即使我在 PyCharm 编辑器中输入此解决方案时,我也会收到有关request无法访问的警告,可能是因为它是一个动态值……以下是我的最终解决方案。

#views.py
class AccountRead(ListView):
    context_object_name = 'account'
    template_name = 'accounts/view_account.html'

    def get_queryset(self):
        return Account.objects.filter(pk=self.request.user.id)
于 2013-08-08T04:43:05.170 回答
0

你做错了,问题是我不知道你想要完成什么。基于类的视图非常简单直接,几乎不需要重写get˙andpost方法。

为什么要将电子邮件存储在会话中,因为它可以很容易地从经过身份验证的用户那里检索?

即使在您的 FBV 中,您也在做很多不必要的事情;登录最好留给单独的视图,在身份验证后将用户重定向到正确的视图。

于 2013-08-07T18:29:21.387 回答