For the past 2hrs i've been trying to accomplish the following in Django 1.5: I want to retrieve records from my database based on the user's email, which is stored in a session. Here are my ideal algorithms:
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
I've referenced the docs and a post on this matter but can't seem to get my head around it. I decided to use the get method to retrieve the session and it works...the only issue is i'm not sure how i can access the variable returned by this method. I looked at this answer but didn't find it too helpful. If this question exist else where point me to it so i can delete this one. Thanks!
#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)
This is the solution in a function based view...how do i implement it in class based view is what i'm asking.
def AccountView(request):
account = Account.objects.get(verified=1, email=request.session['email'])
return render(request, 'accounts/view_account.html', {'account': account})