Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Search with or without space in django filter
I have a search by name function, which should return the name of one person if the search matches the name.I need to show results with or without space between them. Eg: ‘A B C’ should show results A B Chacko, AB Chacko, AB Chaks etc. similarly, the search The term ‘ABC’ needs also list the above results. try: term = request.GET['term'] if term: queryset_primary = PrimaryUserSerializer(UserTable.objects.filter(Q(name__icontains =term)|Q(occupation__icontains=term)).order_by('name'), many=True, context=context).data else: pass except: pass The models only have the 'name ' field not have first name, last name -
how to get db unique ids for html form and use it in css and jquery for making dyanmic forms for each form data for django?
I make an edit button which for edit existing data. when pressing the button it will show the form and if there are multiple data then there will be multiple edit buttons which leads to showing multiple forms. The problem is, I cannot get make this. All my edit button and forms are visible. All I need an edit button that shows the form and it will be dynamic as the DB object ids. I'm using Django as a backend for the edit form to saves the edited data. code: $(document).ready(function() { $(".formButton").click(function() { var togle= $('this').attr("id") print(togle) $(togle).hide(); }); }); h1,h2{ font-style: italic; color: green; background-color: inherit; } /* .djangoaccessed{ border: 2px solid black; } */ table, th, td{ border: .5px solid black; } .hello{ display: none; } <!DOCTYPE html> {% load staticfiles %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Index</title> <link rel="stylesheet" href="{% static "css/style.css" %}"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha256-pasqAKBDmFT4eHoN2ndd6lN370kFiGUFyTiUHWhU7k8=" crossorigin="anonymous"></script> </head> <body> <h1>This is Django TODO APP.</h1> {% comment %} <div class="container"> <div class="jumbotron"> <form method="get" action="/search1/"> <p><label for="id_q">Search:</label> <select name="topic"> {% for todo in all_todo %} <option value="{{ todo.id }}">{{ todo.topic }}</option> {% endfor %} </select> <input type="submit" value="Submit" /></p> </form> </div> … -
Deploying Django on Google App Engine gives Bad Request 400 error
I am trying to host Django application on Google App Engine Standard environment. My app gets deployed successfully but when I try visiting appspot.com url I get Bad Request 400 error. Here is the Logs Viewer content: This is my apps.yaml file. runtime: python37 instance_class: F2 entrypoint: gunicorn -b :$PORT scholarity_project.wsgi handlers: - url: /static static_dir: static/ - url: /.* script: auto This is my main.py file: from scholarity_project.wsgi import application app = application I am referring to the Github example over here and this GAE Documentation. Any help will be appreciated. -
How to use class attribute in its instance method in Django?
I want to use variation attribute inside to_representation function in serializers.py. When I tried to implement it an error occured. I think I still don't understand the fundamental of Python class. Here's my serializers.py: class MarketSerializer(serializers.ModelSerializer): regions = serializers.PrimaryKeyRelatedField(many=True, queryset=Region.objects.all()) languages = serializers.PrimaryKeyRelatedField(many=True, queryset=Language.objects.all()) variation = serializers.SerializerMethodField('get_product_variations') class Meta: model = Market fields = ['id', 'regions', 'languages', 'name', 'status', 'variation'] depth = 1 @staticmethod def get_product_variations(self): return Product.objects.filter(distributor__region__market=self).distinct().count() def to_representation(self, instance): if self.context['request'].method == 'GET': regions = RegionSerializer(instance.regions, many=True).data languages = LanguageSerializer(instance.languages, many=True).data data = { 'id': instance.id, 'regions': regions, 'languages': languages, 'name': instance.name, 'status': instance.status, 'variation': self.variation, } return data return Serializer.to_representation(self, instance) 'variation': self.variation gives me this error on browsable API: AttributeError at /api/markets/ 'MarketSerializer' object has no attribute 'variation' While 'variation': MarketSerializer.variation and 'variation': self.__class__.variation give me this error: AttributeError at /api/markets/ type object 'MarketSerializer' has no attribute 'variation' -
Use ManyToManyField as slug in url
I'm trying to have my url include the category and name of product. Rather than using ForeignKey to assign the category for a product I have chose ManyToManyField because some products belong in multiple categories. If I navigate to say http://127.0.0.1:8000/products/shirts/tshirt/. I get Invalid field name(s) given in select_related: 'category'. Choices are: (none) models.py class Product(models.Model): title = models.CharField(max_length=80) category = models.ManyToManyField(Category) model_slug = AutoSlugField(null=True, default=None, unique=True, populate_from='title') class Meta: verbose_name_plural = "Products" def __str__(self): return self.title views.py def model_detail_view(request, category_slug, model_slug): products = Product.objects.select_related('category').get( category__category_slug=category_slug, model_slug=model_slug) context = { "products": products, } return render(request=request, template_name='main/model_detail.html', context=context) urls.py path("products/<str:category_slug>/<str:model_slug>/", views.model_detail_view, name="model_detail_view"), template {% for product in products %} <a class="btn btn-outline" href="{% url 'main:model_detail_view' product.model_slug product.model_slug %}"><i class="fa fa-arrow-circle-right"></i>View Model</a> {% endfor %} -
edit .htaccess in heroku to remove fbclid from url
the app is a python/django app and it's hosted at heroku. site: datafix.io when the site is linked from facebook, facebook adds ?fbclid=xyz to the URL my app breaks when this happens how can I edit .htaccess in heroku to remove fbclid? -
Unit testing Django ModelForm with ImageField, tests show invalid form
Trying to test Django ModelForm, but fails. Passing the required data but still shows "This field is required" and tests show invalid form. I couldn't figure out the reason. models.py # models.py import sys from PIL import Image from io import BytesIO from django.contrib.auth.models import User from django.core.files.uploadedfile import InMemoryUploadedFile from django.db import models from django.utils.translation import ugettext as _ class ProfileImage(models.Model): user = models.OneToOneField(User, verbose_name=_("user"), on_delete=models.CASCADE) image = models.ImageField(upload_to="profile") created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) def __str__(self): return self.user.username def save(self, *args, **kwargs): if not self.id: uploaded_image = Image.open(self.image) rgb_image = uploaded_image.convert("RGB") output = BytesIO() image_resized = rgb_image.resize((300, 300)) image_resized.save(output, format="JPEG", quality=100) output.seek(0) self.image = InMemoryUploadedFile( output, "ImageField", "{}.jpg".format(self.image.name.split('.')[0]), "image/jpeg", sys.getsizeof(output), None ) super().save(*args, **kwargs) forms.py # forms.py from PIL import Image from django import forms from django.forms.utils import ErrorList from django.utils.translation import ugettext as _ from .models import ( ProfileImage, ) class ProfileImageForm(forms.ModelForm): class Meta: model = ProfileImage fields = ["image"] def clean(self): image = self.cleaned_data.get("image") if image: image = Image.open(image) width, height = image.size image_format = image.format if image_format not in ("PNG", "JPEG", "MPO"): msg = _("Unsupported image type. Please upload a *png or *jpg image.") self._errors["image"] = ErrorList([msg]) del image if width < 300 or height … -
Django search list in a list with foreign key
i'm beginning in django (and coding too) and i can't do something which i guess is super easy . I want to create a simple project management . I created 2 models : Project and Step . And in step there are a foreign key for 1 project. class Project(models.Model): title = models.CharField(max_length=100) def __str__(self): return self.title class Step(models.Model): title = models.CharField(max_length=100) project= models.ForeignKey('Project', on_delete=models.CASCADE, null=True) I succed to create a step in a project , to do a list to see all step for 1 project but now in my home page , i want to list all projects and 4 steps in each project for example : Project 1 (Step 1, Step 2, Step 3 ,Step 4) Project 2 (Step 1, Step 2, Step 3, Step 4) I'm using the ListView , but i don't know what to do , because it's in my step there are the id of project . So how I sort steps by project ? class ProjectList(ListView): model = Project template_name ='project/index.html' Do i need to create a queryset if so what i should write ? queryset = setp.objects.filter(project_id='?') I'm thinking maybe i did something wrong with the foreign key , and i … -
CSRF Failed: CSRF cookie not set
I am running a django website . Here is my code : views.py: @permission_classes((IsAdminUser,)) class ProfileView(viewsets.ModelViewSet): queryset=Profile.objects.all() serializer_class=ProfileSerializer @csrf_exempt def list(self,request): return Response({'message':'Append Profile ID to the API to view Profile of Particular User'}) def get_serializer_class(self): serializer_class = self.serializer_class if self.request.method == 'PUT' or self.request.method == 'PATCH': serializer_class = ProfilesSerializer return serializer_class @permission_classes((IsAdminUser,)) class LoginView(viewsets.ModelViewSet): queryset = Token.objects.all() serializer_class = LoginSerializer http_method_names = ['get', 'head'] urls.py: router=routers.DefaultRouter() router.register('profiles',views.ProfileView) router.register('login', views.LoginView) urlpatterns = [ path('home/',include(router.urls)), ] I need to get response in JSON . If i enter the url in postman , i am getting the error like this `"CSRF Failed: CSRF cookie not set." Can someone help me to fix this error? -
Forbidden(403) when trying to POST in Django Rest Framework
When I try to POST data, I get this error: Forbidden (403) CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties. If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for “same-origin” requests. can someone please explain why I am getting this error? Cookies are not blocked in my browser neither I have set any csrf properties in my code. My views.py : @api_view(['POST']) def post_date(request): if request.method == 'POST': serializer = predserializer(data=request.data) return Response(serializer.data, status=status.HTTP_201_CREATED) -
django.contrib.auth.views LoginView and LogoutView not working
I am using latest version of django and I want to create a login-logout page using builtin system. But this is giving error when I try to run the server. Below is the urls.py code. from django.contrib import admin from django.urls import path from django.conf.urls import url, include from django.contrib.auth import views urlpatterns = [ path('admin/', admin.site.urls), path('',include('blog_app.urls')), path('accounts/login/', views.LoginView.as_view(template_name='registration/login.html')), path('accounts/logout/',views.LogoutView.as_view(),name='logout',kwargs={'next_page':'/'}), ] Below is the login.html code {% extends 'blog_app/base.html' %} {%block body_block%} <div class="jumbotron"> <h2>PLEASE LOGIN:</h2> {% if forms.errors %} <p>Username and Password didn't match. Please try again!</p> {%endif%} <form method="POST" action="{%url 'login' %}"> {%csrf_token%} {{form.as_p}} <input type="submit" class='btn btn-primary' value="Login"> <input type="hidden" name="next" value="{{ next }}"> </form> </div> {%endblock%} -
Is authenticated data showing on webpage when not logged in Django/vue
I have an app with Django and Nuxt js that uses express sessions and redis to store session tokens. I'm trying to add a page with data from my backend that will only be displayed if user is authenticated. For some reason it's not working. The data is displayed when I'm logged out even after multiple refreshes. Here's my code. Django/Views.py class OrdersViewSet(mixins.ListModelMixin, viewsets.GenericViewSet, mixins.RetrieveModelMixin ): queryset = Orders.objects.all().order_by('-time_stamp') serializer_class = OrdersSerializer permission_classes= [permissions.IsAuthenticated] webpage.hmtl <template> <div class="course-list-row"> <table> <thead id="header-fixed"> <th scope="col">Time Stamp</th> </thead> </table> <tbody> <tr v-for="row in orders" :key="row.id"> <td style="width:5px">{{ row.time_stamp }}</td> <td style="width:5px">{{ row.event_name }}</td> </tr> </tbody> </div> </template> <script> export default { async asyncData({ app }) { try { const res = await app.$axios.get("api/orders/"); return { orders: res.data.results, error: false }; } catch (e) { console.log("error", e); return { orders: [], error: true }; } } }; </script> store.js export default { state: () => ({ loggedIn: false, user: null }), actions: { async nuxtServerInit ({ commit }, { req, app }) { console.log('nuxtServerInit', req.session.authToken) if (req.session.authToken) { const data = await app.$axios.$get('/api/auth/me/') commit('SET_USER', data) } else { commit('SET_USER', null) } }, async login ({ commit }, creds) { await this.$axios.$post('/auth/login/', creds) const data … -
Django import export in admin for auth model user
I want to add import export function for the table django.contrib.auth.models User in admin panel so i can add available user list in database. for this i'm trying this code- from django.contrib import admin from django.contrib.auth.models import User from import_export.admin import ImportExportModelAdmin from import_export import resources admin.site.unregister(User) @admin.site.register(User) class UserAdmin(ImportExportModelAdmin): pass but im getting error like class UserAdmin(ImportExportModelAdmin): TypeError: 'NoneType' object is not callable how can i add emport export function to User table -
is there any Switch which can disable/enable for any changes in django model objects?
Is there anything like switch/flag available in Django models which can enable/disable for any changes. by enabling this switch, you can not change/delete any model object even in referenced models (connected with foreign key) not even from Django-shell. -
State matching query does not exist
I am getting error when trying to save the facebook data in database. models.py city = models.ForeignKey( City, null=True, blank=True, related_name='user_city', on_delete=models.CASCADE) state = models.ForeignKey(State, null=True, blank=True, on_delete=models.CASCADE) views.py if profile.get('location'): city = City.objects.filter(name__iexact=location.strip()) if city: user.current_city = city[0] else: city = City.objects.create(name=location, status='Disabled', slug=slugify(location), state=State.objects.get(id=16)) user.current_city = city -
Seeing only one endpoint in browsable API instead of two
How come I can only see one of my URLs instead of both in the django rest browsable API? urls: urlpatterns = [ path("admin/", admin.site.urls), path("api-auth/", include("rest_framework.urls")), path("", include("accounts.urls")), path("", include("properties.urls")), ] I expected to see accounts and properties -
How can I populate value of a hidden field in Django from the value of a range slider
So I am building an app that users are able to use a range slider to update a database with a new integer value. I have the slider which provides me with the integer value that I would like to return to the view, but I don't know how to return this value from the template. https://docs.djangoproject.com/en/3.0/ref/forms/widgets/ I looked at the documentation but I couldn't find anything regarding range inputs. # forms.py from django import forms class UpdateForm(forms.Form): update = forms.IntegerField(widget=forms.HiddenInput(**something like:value='slider-input**}})) # views.py def home_view(request): form = UpdateForm() return render(request, 'main/index.html', {'form': form}) # index.html ... <form id="update-form" method="post"> {% csrf_token %} {{ form }} <div id="slider"> <input class="slider-widget" min="0" max="25" step="1" value="0" type="range"> </div> <div class="options"> <a href="{% url 'main-home' %}"> <img src="{% static 'main/media/cancel.png' %}" alt="cancel"> </a> <button type="submit"> <img src="{% static 'main/media/confirm.png' %}" alt="confirm"> </button> </div> </form> ... -
django sending email using sendgrid api
I have this django method which uses sendgrid to send emails to staff when his manager approves his/her leave. I have been testing it on Gmail email address and one other email domain but it doesn't seem to send email to staff who have Gmail accounts and one other email domain. However, it is sending emails to other email addresses on a different domain. I am not sure why it is behaving that way. def manager_send_email_to_staff(request, staff_id): to_emails = [staff_id.user.email] if staff_id.Manager_Authorization_Status == 'Approved': send_mail("VFSC Leave Application Approved by" + " " + staff_id.Authorized_by_Manager, "Your annual leave application have been {}".format( staff_id.Manager_Authorization_Status) + " " + "by your Manager {}".format( staff_id.Authorized_by_Manager) + " " + "and has now been forward to the " "Director " "for the final authorization.\nWe will " "inform you via email once the Director " "Authorized your Annual leave", "VFSC Annual Leave <eLeavesystem@admin.com>", to_emails, fail_silently=False) -
Django queryset TruncMonth output format issue
I'm using Django ORM queryset for chart, and having difficulty with changing the format of output 'source': ActivityLog.objects.filter(requestType='add',doDate__lte=datetime.datetime.today(), doDate__gt=datetime.datetime.today()-datetime.timedelta(days=365)).\ values(작업월=TruncMonth('doDate')).annotate(요청건수=Count('requestType'), IP개수=Sum('ipCnt'))}, When I use 'TruncMonth' , output is like this -> 2019-10-01T00:00:00 But I want to use only 2019-10 ( YYYY-MM )... Is there any good solution for me? Thanks in advance. -
permission issues when installing django/creating virtualenv on MAC
This is the response issue when i try to install it .. ''' Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/virtualenv.pyc' Consider using the --user option or check the permissions. ''' Was wondering how I could fix this and make it automatic so that i don't get permission issues. -
Uncompyle6 convert pyc to py file python3 not working
I have installed uncompyle6 package from github. https://github.com/rocky/python-uncompyle6 When I try to decompile .pyc file into .py file - uncompyle6 urls.pyc I am getting the following error message. Traceback (most recent call last): File "/usr/local/bin/uncompyle6", line 6, in from pkg_resources import load_entry_point File "/usr/lib/python3/dist-packages/pkg_resources/init.py", line 3088, in @_call_aside File "/usr/lib/python3/dist-packages/pkg_resources/init.py", line 3072, in _call_aside f(*args, **kwargs) File "/usr/lib/python3/dist-packages/pkg_resources/init.py", line 3101, in _initialize_master_working_set working_set = WorkingSet._build_master() File "/usr/lib/python3/dist-packages/pkg_resources/init.py", line 574, in _build_master ws.require(requires) File "/usr/lib/python3/dist-packages/pkg_resources/init.py", line 892, in require needed = self.resolve(parse_requirements(requirements)) File "/usr/lib/python3/dist-packages/pkg_resources/init.py", line 778, in resolve raise DistributionNotFound(req, requirers) pkg_resources.DistributionNotFound: The 'uncompyle6==3.6.1' distribution was not found and is required by the application I am searching for that error message but no luck till now. -
Cannot deploy to Heroku - Error while running '$ python manage.py collectstatic --noinput'
I have in the past successfully deployed a Django-Webapp to Heroku, but this time I cannot do it. I've tried following the suggestion "remote: $ heroku config:set DISABLE_COLLECTSTATIC=1" on my terminal. On my settings.py I've tried to follow third party tutorials as well as Heroku's documentation. At this point I'm totally clueless on what should I do. Successfully installed Django-3.0.1 asgiref-3.2.3 attrs-19.3.0 beautifulsoup4-4.8.2 bootstrap4-0.1.0 certifi-2019.11.28 chardet-3.0.4 dj-database-url-0.5.0 django-bootstrap4-1.1.1 django-crispy-forms-1.8.1 django-forms-bootstrap-3.1.0 django-heroku-0.3.1 gunicorn-20.0.4 idna-2.6 importlib-metadata-1.3.0 jsonschema-3.2.0 more-itertools-8.0.2 psycopg2-2.7.3.2 pyrsistent-0.15.6 python-decouple-3.1 pytz-2019.3 requests-2.18.4 requests-unixsocket-0.1.5 six-1.13.0 soupsieve-1.9.5 sqlparse-0.3.0 urllib3-1.22 whitenoise-5.0.1 zipp-0.6.0 remote: remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "manage.py", line 21, in <module> remote: main() remote: File "manage.py", line 17, in main remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 345, in execute remote: settings.INSTALLED_APPS remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 76, in __getattr__ remote: self._setup(name) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 63, in _setup remote: self._wrapped = Settings(settings_module) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 142, in __init__ remote: mod = importlib.import_module(self.SETTINGS_MODULE) remote: File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module remote: return _bootstrap._gcd_import(name[level:], package, level) remote: File "<frozen importlib._bootstrap>", line 994, in _gcd_import remote: File "<frozen importlib._bootstrap>", line 971, in _find_and_load remote: File "<frozen … -
Linking two model in reciprocal way
Hello I'm trying to create a LMS (learning management system) system for my school. In this system I'm trying to connect between origen_classroom model and the students and teacher model in a way that updating one of the models will update the others. I try to use signals but it doesnt work on this model (It's working on the user model) attached is my code: from django.db import models from django.contrib.auth.models import AbstractUser from django.dispatch import receiver from django.db.models.signals import post_save from .utils import upload_location, phone_regex from materials.models import Subject # Add fields to user module and uplaod image to the media location class User(AbstractUser): USER_TYPE_CHOICES = ( (1, 'student'), (2, 'teacher'), ) user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES, blank=True, null=True ) # user type date_of_birth = models.DateField(blank=True, null=True) phone_number = models.CharField(validators=[phone_regex], max_length=11, blank=True ) # validators should be a list profile_image = models.ImageField(upload_to=upload_location, blank=True, default='test.png', height_field='height_field', width_field='width_field', ) height_field = models.IntegerField(default=0) width_field = models.IntegerField(default=0) class Meta: verbose_name_plural = "Users" def __str__(self): return self.username # main student module class Student(models.Model): user = models.OneToOneField( User, related_name='student', on_delete=models.CASCADE) origen_class = models.ForeignKey( 'OrigenClass', on_delete=models.SET_NULL, blank=True, null=True) def __str__(self): return self.user.username # main teacher module class Teacher(models.Model): user = models.OneToOneField( User, related_name='teacher', on_delete=models.CASCADE) head_class = models.OneToOneField('OrigenClass', on_delete=models.SET_NULL, … -
Django3.0.1: after use ForeignKey then show this problem - This field cannot be null
Django3.0.1: after use ForeignKey then show this problem - This field cannot be null. I'm using Django 3.0.1 and MySQL database. I've attached the code below - in models.py, views.py, forms.py models.py: from django.conf import settings from django.db import models # Create your models here. User = settings.AUTH_USER_MODEL class BlogPost(models.Model): user = models.ForeignKey(User, default=1, blank=True, null=True, on_delete=models.SET_NULL) title = models.CharField(max_length=120) slug = models.SlugField(unique=True) content = models.TextField(null=True, blank=True) views.py: from django.contrib.auth.decorators import login_required from django.contrib.admin.views.decorators import staff_member_required from django.http import Http404 from django.shortcuts import render, get_object_or_404 from .models import BlogPost from .forms import BlogPostForm, BlogPostModelForm # Create your views here. # @login_required @staff_member_required def blog_post_create_view(request): # create objects - but how # ? use a form form = BlogPostModelForm(request.POST or None) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() form = BlogPostModelForm() template_name = 'blog/create.html' context = { 'form': form, } return render(request, template_name, context) forms.py: from django import forms from .models import BlogPost class BlogPostForm(forms.Form): title = forms.CharField(max_length=120) slug = forms.SlugField() content = forms.CharField(widget=forms.Textarea) class BlogPostModelForm(forms.ModelForm): class Meta: model = BlogPost fields = ['title', 'slug', 'content'] def clean_title(self, *args, **kwargs): title = self.cleaned_data.get('title') post_title = BlogPost.objects.filter(title=title) if post_title.exists(): raise forms.ValidationError("This title has already been used. Please try again.") return … -
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 '('kkdsjfsdifisdfj@gmail.com',)' 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?