Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'AnonymousUser' object is not iterable? Django

Tags:

django

I'm creating a summary page of all the posts that user has created and returning those posts to the summary page. I get the error above?

It's complaining about this line:

uploaded_aircraft = Aircraft.objects.filter(user=request.user)

View

def aircraft_create(request):
  form = aircraft_form(request.POST or None)
  if form.is_valid():
    instance = form.save(commit=False)
    instance.user = request.user
    instance.save()
    messages.success(request, "Your upload has been successfully added!")
    return HttpResponseRedirect(instance.get_absolute_url())
  else:
    messages.error(request, "There seems to be something wrong. Have a look again..!")
  context = {"form":form,}
  return render(request,'aircraft/aircraft_form.html', context)

Model

class Aircraft(AircraftModelBase):
    user = models.ForeignKey(User)
    manufacturer = SortableForeignKey(Manufacturer)
    aircraft_type = SortableForeignKey(AircraftType)

View

def account_overview(request):
    fav_aircraft = FavoritedAircraft.objects.filter(user__id=request.user.id)
    fav_airline = FavoritedAirline.objects.filter(user__id=request.user.id)

    uploaded_aircraft = Aircraft.objects.filter(user=request.user)

    return render(request,'account/account_overview.html', {'favAircraft':fav_aircraft,
                                                             'favAirline':fav_airline,
                                                             'UploadedAircraft':uploaded_aircraft})

Traceback

Traceback (most recent call last):
  File "/home/csunix/scpython/lib/django/core/handlers/base.py", line 149, in get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/csunix/scpython/lib/django/core/handlers/base.py", line 147, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/cserv1_a/soc_ug/sc13nh/env/v10/accounts/views.py", line 57, in account_overview
    uploaded_aircraft = Aircraft.objects.filter(user=request.user)
  File "/home/csunix/scpython/lib/django/db/models/manager.py", line 122, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/csunix/scpython/lib/django/db/models/query.py", line 790, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "/home/csunix/scpython/lib/django/db/models/query.py", line 808, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "/home/csunix/scpython/lib/django/db/models/sql/query.py", line 1243, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "/home/csunix/scpython/lib/django/db/models/sql/query.py", line 1269, in _add_q
    allow_joins=allow_joins, split_subq=split_subq,
  File "/home/csunix/scpython/lib/django/db/models/sql/query.py", line 1174, in build_filter
    self.check_related_objects(field, value, opts)
  File "/home/csunix/scpython/lib/django/db/models/sql/query.py", line 1073, in check_related_objects
    for v in value:
  File "/home/csunix/scpython/lib/django/utils/functional.py", line 205, in inner
    return func(self._wrapped, *args)
TypeError: 'AnonymousUser' object is not iterable

What seems to be actual problem here?

like image 897
Pakin Sife Avatar asked Apr 21 '17 13:04

Pakin Sife


3 Answers

The error is telling you that request.user is an anonymous user. That means that they are not logged in, so it doesn't make sense to try to filter with filter(user=request.user).

The easiest fix is to use the login_required decorator, to make sure that only logged-in users can access the view.

from django.contrib.auth.decorators import login_required

@login_required
def account_overview(request):
    ...
like image 160
Alasdair Avatar answered Oct 16 '22 19:10

Alasdair


def account_overview(request):

 if request.user.is_authenticated:  # Notice this condition
    fav_aircraft = FavoritedAircraft.objects.filter(user__id=request.user.id)
    fav_airline = FavoritedAirline.objects.filter(user__id=request.user.id)

    uploaded_aircraft = Aircraft.objects.filter(user=request.user)
    return render(request,'account/account_overview.html', {'favAircraft':fav_aircraft,
                                                         'favAirline':fav_airline,
                                                         'UploadedAircraft':uploaded_aircraft})
   return render(request,'account/account_overview.html')

This should fix your issue wrapping the view in with is_authenticated conditional statement to return a context only if the user is authenticated .

like image 28
Alabi E. Oluwaferanmi Avatar answered Oct 16 '22 19:10

Alabi E. Oluwaferanmi


Although in your case it doesn't work (because you use methods instead of classes), you could solve this problem with LoginRequiredMixin:

from django.contrib.auth.mixins import LoginRequiredMixin

class MyView (LoginRequiredMixin, View):
     login_url = '/ login /'
     redirect_field_name = 'redirect_to'
like image 1
cr_hdz Avatar answered Oct 16 '22 19:10

cr_hdz