在过去的 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})