0

I have the following custom User model:

class User(AbstractBaseUser, PermissionsMixin):
    username = models.CharField(_('username'), max_length=30)
    email = models.EmailField(unique=True, null=True)
    slug = models.SlugField(max_length=100, blank=True)

In addition I have the UserProfile model related with their respective Manager() to perform some operations of follow users betwenn them:

class UserProfileManager(models.Manager):
    use_for_related_fields = True

    def is_following(self, user, followed_by_user):
        user_profile, created = UserProfile.objects.get_or_create(user=user)
        if created:
            return False
        if followed_by_user in user_profile.following.all():
            return True
        return False

class UserProfile(models.Model):
    # user.profile
    user = models.OneToOneField(settings.AUTH_USER_MODEL,   on_delete=models.CASCADE, related_name='profile')

    # user.profile.following -- users I follow
    # user.profile.followed_by -- users that follow me -- reverse relationship
    following = models.ManyToManyField(settings.AUTH_USER_MODEL,
        blank=True, related_name='followed_by')

    objects = UserProfileManager()  

    def __str__(self):
        return str(self.user)

Then, I create the detail view of an User, which I want visualize when an user is logged and too where an user is anonymous.

I have the URL:

url(r"^(?P<slug>[\w.@+-]+)/$", views.UserDetailView.as_view(), name='detail'),

The UserDetailView is the following:

class UserDetailView(generic.DetailView):   
    template_name = 'accounts/user_detail.html'
    queryset = User.objects.all()

    def get_object(self):
        return get_object_or_404(User,                slug__iexact=self.kwargs.get("slug") 
                    )

    def get_context_data(self, **kwargs):
        context = super(UserDetailView, self).get_context_data(**kwargs)
        user = self.request.user
        following = UserProfile.objects.is_following(self.request.user, self.get_object())
        context['following'] = following

        if user.is_authenticated():
            context['userprofile'] = user.profile

        return context

When I access to http://localhost:8000/accounts/profiles/<username>/ URL , when the user who perform the request is authenticated, ALL is O.K

[17/Apr/2018 00:01:07] "GET /accounts/profiles/bgarcial/ HTTP/1.1" 200 41394

But, I want that this view to be acceded from anonymous users or un-authenticated users, which does not register in my application, then, when an anonymous user access to http://localhost:8000/accounts/profiles/<username>/ URL I get this message:

TypeError: 'AnonymousUser' object is not iterable
[17/Apr/2018 00:01:57] "GET /accounts/profiles/bgarcial/ HTTP/1.1" 500 147208

The inconvenient is in the custom manager method ( is_following() ) created in the UserProfileManager class and which are called in the UserDetailView

File "/home/bgarcial/workspace/hostayni_platform/accounts/views.py", line 89, in get_context_data
    following = UserProfile.objects.is_following(self.request.user, self.get_object())
  File "/home/bgarcial/workspace/hostayni_platform/accounts/models.py", line 572, in is_following
    user_profile, created = UserProfile.objects.get_or_create(user=user)
  File "/home/bgarcial/.virtualenvs/hostayni/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/bgarcial/.virtualenvs/hostayni/lib/python3.6/site-packages/django/db/models/query.py", line 473, in get_or_create

I try manage the request when this came from an anonymous user using the dispatch function inside my UserDetailView cbv:

def dispatch(self, request, slug, *args, **kwargs):
    if request.user.is_anonymous():
        username = User.objects.filter(slug__iexact=slug)
        return HttpResponseRedirect(reverse_lazy("accounts:detail", slug=username))
    else:
        return super(UserDetailView, self).dispatch(request, slug, *args, **kwargs)

But I get this error message

TypeError: reverse() got an unexpected keyword argument 'slug'
[17/Apr/2018 00:07:43] "GET /accounts/profiles/bgarcial/ HTTP/1.1" 500 97476

 return self.dispatch(request, *args, **kwargs)
  File "/home/bgarcial/workspace/hostayni_platform/accounts/views.py", line 68, in dispatch
    return HttpResponseRedirect(reverse_lazy("accounts:detail", slug=username))
  File "/home/bgarcial/.virtualenvs/hostayni/lib/python3.6/site-packages/django/http/response.py", line 417, in __init__

I change the dispatch method by get method to get the anonymous request:

def get(self, request, slug, *args, **kwargs):
    if request.user.is_anonymous():
        username = User.objects.filter(slug__iexact=slug)
    return redirect("accounts:detail", slug=username)

An I get NoReverseMatch message:

django.urls.exceptions.NoReverseMatch: Reverse for 'detail' with arguments '()' and keyword arguments '{'slug': <QuerySet [<User: @bgarcial>]>}' not found. 1 pattern(s) tried: ['accounts/profiles/(?P<slug>[\\w.@+-]+)/$']

the url requested does not match with the pattern that expected, the slug username field ...

I don't have clear when I should use get or dispatch method with the order to catch the anonymous request user and manage it.

Or can I manage this anonymous request user in the get_context_data method?

Any orientation that points me in the right direction will be highly appreciated

Best Regards

2
  • try to use login_required decorator to view class Apr 17, 2018 at 7:24
  • @AnjaneyuluBatta thanks for your observations, but my goal is that anonymous users can access to UserDetailView without they have create an user and sign in.
    – bgarcial
    Apr 17, 2018 at 13:42

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.