Hax0
Hax0

Reputation: 103

Django No reverse error when user uses email as Username

When a User uses an email as the Username the reverse for view fails. But when I change the username to a non-email username using admin panel, it works great. I have searched a lot but couldn't find similar issue.

My User Model:

class CustomUser(AbstractUser):    
    date_joined = models.DateField(auto_now_add=True)    
    email = models.EmailField(unique=True)

    def __str__(self):
        return self.username

View responsible:

class UserUpdateView(SuccessMessageMixin, LoginRequiredMixin, UpdateView):
    template_name = "accounts/user_update.html"
    form_class = UserChangingForm
    model = CustomUser
    slug_field = 'username'
    slug_url_kwarg = 'username'
    success_message = '%(username)s was updated successfully'

    def get_success_url(self):
        return reverse('accounts:user_update', kwargs={'username': self.object.username})

Urls.py:

from . import views
from django.contrib.auth import views as authViews

app_name = 'accounts'

urlpatterns = {
    path('signup/', views.UserSignupView.as_view(), name='signup'),
    path('login/', views.UserLoginView.as_view(), name='login'),
    path('logout/', authViews.LogoutView.as_view(), name='logout'),
    path('<slug:username>/profile/', views.UserUpdateView.as_view(), name='user_update'),}

The error in template is thrown by: Error message:

NoReverseMatch at /

Reverse for 'user_update' with arguments '('[email protected]',)' not found. 1 pattern(s) > tried: ['accounts/(?P[-a-zA-Z0-9_]+)/profile/$']

I am thinking of preventing users from using special character in Username field while signup. Where am I wrong?

Upvotes: 0

Views: 116

Answers (1)

Sharif Chowdhury
Sharif Chowdhury

Reputation: 256

error is in this line

path('<slug:username>/profile/', views.UserUpdateView.as_view(), name='user_update'),

here your username name is an email. but you defined it as a slug field. change slug field.

update it with

path('<username>/profile/', views.UserUpdateView.as_view(), name='user_update'),

if you want to prevent the special character in Username field then you can use a regex and you'll need to use re_path() or url()

from django.urls import re_path

re_path(r'(?P<username>\w+|[\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})/profile/$', views.UserUpdateView.as_view(), name='user_update'),

please use proper regex here. for email you cab check this. How to Find or Validate an Email Address

Upvotes: 1

Related Questions