A
A
Ayaks772017-04-06 20:07:46
Django
Ayaks77, 2017-04-06 20:07:46

Viewing a Django User Profile?

Good day! I can not figure out how to implement viewing someone else's profile. There is a slightly modified user model, login form:

class LoginFormView(FormView):
form_class = AuthenticationForm
template_name = "login.html"
success_url = "/"

def form_valid(self, form):
    self.user = form.get_user()
    login(self.request, self.user)
    return super(LoginFormView, self).form_valid(form)

def form_invalid(self, form):
    return super(LoginFormView, self).form_invalid(form)

profile itself:
class ProfileView(LoginRequiredMixin, DetailView):
model = User
template_name = 'profile.html'
pk_url_kwarg = 'user_pk'

and the edit form:
class UpdateProfileView(LoginRequiredMixin, UpdateView):
form_class = UpdateForm
model = User
template_name = 'profile_update.html'
pk_url_kwarg = 'user_pk'

def get(self, request, *args, **kwargs):
    user = User.objects.get(pk=self.kwargs['user_pk'])
    if user != request.user:
        return HttpResponseForbidden()
    else:
        return super(UpdateProfileView, self).get(request, *args, **kwargs)

def get_success_url(self):
    return reverse('profile_update', kwargs={'user_pk': self.kwargs['user_pk']})

The bottom line is that if I change the user id in the address bar when viewing the profile, there is a re-login under the corresponding id. And if in the edit view in the get method I inserted a crutch check for a specific user, so that otherwise I would restrict access, then I just can’t figure out what to do when viewing.
url:
url(r'^profile/(?P<user_pk>\d+)/$', ProfileView.as_view(),  name='profile')

in the template I do this:
<li><a href="{% url 'profile' user_pk=user.pk %}">профиль</a></li>

How can I make it so that I can just view someone's profile without automatically re-login under this user?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
Bobsans, 2017-04-07
@Ayaks77

@login_required
def view_user_profile(request, user_pk):
    user = User.objects.get(pk=user_pk)
    form = UpdateForm(instance=user)
    return render(request, 'profile.html', {
        'form': form
    })

that's about it. what for to fence a mountain of classes?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question