0

Django 1.10 Python 3.5.3

Using CBV, I am able to log a user into the site. However, I cannot get the user to redirect to their profile after login. I want them to go to this page after login: https://example.com/profiles/user. Instead, I get this error:

NoReverseMatch at /accounts/login/
Reverse for 'profile' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['profile/(?P<slug>[\\w-]+)/$']

How can I pass the username to the url?

models.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(max_length=500, blank=True)
    location = models.CharField(max_length=30, blank=True)
    birth_date = models.DateField(null=True, blank=True)
    username = models.CharField(max_length=30,
                                unique = True,
                                default='')
    email = models.EmailField(default='',
                                unique = True,
                                max_length=100)
    profile_image = models.ForeignKey(Image, null=True)
    slug = models.SlugField(default='')
    is_active = models.BooleanField(default=True)
    is_authenticated = models.BooleanField(default=True)
    is_anonymous = models.BooleanField(default=False)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['name']

    @receiver(post_save, sender=User)
    def create_user_profile(sender, instance, created, **kwargs):
        if created:
            Profile.objects.create(user=instance)

    @receiver(post_save, sender=User)
    def save_user_profile(sender, instance, **kwargs):
        instance.profile.save()

    def next_birthday(born):
        today = date.today()

        return today.year - born.year - ((today.month, today.day) < (born.month, born.day))

    def get_absolute_url(self):
        return reverse('profiles:profile', kwargs={'slug': self.slug})

    def __str__(self):
        return self.username

views.py

class LoginView(FormView):

    template_name = 'registration/login.html'

    """
    Provides the ability to login as a user with a username and password
    """
    success_url = 'profile/<slug>'
    form_class = AuthenticationForm
    redirect_field_name = REDIRECT_FIELD_NAME

    @method_decorator(sensitive_post_parameters('password'))
    @method_decorator(csrf_protect)
    @method_decorator(never_cache)

    def dispatch(self, request, *args, **kwargs):
        # Sets a test cookie to make sure the user has cookies enabled  
        request.session.set_test_cookie()

        return super(LoginView, self).dispatch(request, *args, **kwargs)

    def form_valid(self, form):
        auth_login(self.request, form.get_user())

        # If the test cookie worked, go ahead and
        # delete it since its no longer needed
        if self.request.session.test_cookie_worked():
            self.request.session.delete_test_cookie()

        return super(LoginView, self).form_valid(form)

    def get_success_url(self):  
        redirect_to = self.request.GET.get(self.redirect_field_name)
        if not is_safe_url(url=redirect_to, host=self.request.get_host()):
            redirect_to = self.success_url

        return redirect_to

urls.py

urlpatterns = [
    url(r'^(?P<slug>[\w-]+)/$',
        ProfileView.as_view(),
        name = 'profile'),

settings.py

LOGIN_REDIRECT_URL = 'profiles:profile'

Thanks in advance.

user2901792
  • 677
  • 3
  • 7
  • 24

1 Answers1

1

Try using this in your :

settings.py

LOGIN_REDIRECT_URL = '/accounts/home_page/<username>/'

urls.py

from .views import *
from . import views
from django.conf import settings
from django.conf.urls import url

urlpatterns = [
    url(r'^accounts/home_page/(?P<username>[\w-]+)/$', UserProfileView.as_view(), name='user_profile_view'),
]

views

class UserProfileView(View):
    @method_decorator(login_required)
    def get(self, request, username):
        if request.user.username == username:
            profile = get_object_or_404(User, user=request.user)
            return render(request, 'registration/home.html', {'profile': profile})
        else:
            raise Http404

WARNING: It could give you a 404 error if their is no temp page for the user I'm still working on that...

Durodola Opemipo
  • 319
  • 2
  • 12
  • The problem is you can't have a dynamic parameter like `` in `LOGIN_REDIRECT_URL`. You have to use a url without the username, then redirect to the url with the username. See my answer to the [duplicate question](http://stackoverflow.com/questions/36092760/django-login-and-redirect-to-user-profile-page). – Alasdair Jan 06 '17 at 12:18
  • is that why I get the 404 error – Durodola Opemipo Jan 06 '17 at 12:21
  • If you have `LOGIN_REDIRECT_URL = '/accounts/home_page//'` then Django will try to go to that exact url. It won't substitute the username as you might expect, e.g. `/accounts/home_page/emmanuel/`. Since `[\w-]+` doesn't accept `<` or `>`, you'll get a 404. – Alasdair Jan 06 '17 at 12:31
  • @Alasdair Following what we have in http://stackoverflow.com/questions/4870619/django-after-login-redirect-user-to-his-custom-page-mysite-com-username I get this error I'm actually using class based views "Reverse for 'app.views.UserProfileView' with arguments '(u'Emmanuel_Castor',)' and keyword arguments '{}' not found. 0 pattern(s) tried: []" – Durodola Opemipo Jan 06 '17 at 12:53
  • You need to use the name of the url `user_profile_view`, not the path `app.views.UserProfileView`. If you have any more problems, please ask a new question - the comments of this answer are not the right place to fix bugs in your code. – Alasdair Jan 06 '17 at 13:24