Django - how to implement an example.com/username url system

前端 未结 3 655
离开以前
离开以前 2020-12-15 01:56

I am trying to implement on my website a simple and friendly address system.

What i\'m thinking about is when the user logged in, his username will be displayed in t

3条回答
  •  误落风尘
    2020-12-15 03:01

    1. Regarding

    How can i redirect to

    Based on the answer from https://stackoverflow.com/a/20143515/4992248

    # settings.py:
    ACCOUNT_ADAPTER = 'project.your_app.allauth.AccountAdapter'
    
    # project/your_app/allauth.py:
    from allauth.account.adapter import DefaultAccountAdapter
    
    class AccountAdapter(DefaultAccountAdapter):
    
      def get_login_redirect_url(self, request):
          return 'request.user.username'  # probably also needs to add slash(s)
    

    Would be better to use get_absolute_url, ie return 'request.user.get_absolute_url'. In this case you need to do:

    # 1. Add `namespace` to `yoursite/urls.py`
    urlpatterns = patterns('',
        ...
        url(r'^(?P\w+)/', include('userapp.urls', namespace='profiles_username')),
    )
    
    # 2. Add the code below to the Users class in models.py
    def get_absolute_url(self):
        # 'user_profile' is from the code shown by catavaran above
        return reverse('profiles_username:user_profile', args=[self.username])
    

    2. Regarding

    show the correct template

    catavaran wrote correct urls which leads to views.profile, so in view.py you need to write:

    from django.shortcuts import render
    
    from .models import UserProfile  # import model, where username field exists
    from .forms import UserProfileForm  # import Users form
    
    def profiles(request, username):
        user = get_object_or_404(UserProfile, username=username)
    
        return render(request, 'home/profiles.html', {'user_profile_form': user})
    

    In template (i.e. profiles.html) you can show user's data via {{user_profile_form.as_p}}

提交回复
热议问题