Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ValueError: could not convert string to float: '$2,464.34'
I am trying to convert the data to float in order make it as numerical format in excel to sort the data i am getting error.wherever the float in mentioned i did it now but previously there was no float . def get_output_value(self, key, value, neutral=None): display = value if value is None and not neutral.person.is_active: return '-', '-' if value is None: return float(f"${Decimal('.00')}"), float(f"${Decimal('.00')}") if isinstance(value, Decimal): return float(f"${intcomma(value.quantize(Decimal('.00')))}"), float(f"${intcomma(display.quantize(Decimal('.00')))}") return float(value), display -
How to accept variable as encoded/decoded format in django through the url?
I would like to pass a variable through url and sometimes I want to receive the url as it it. If the variable is in encoded format then I want to receive it as encoded format. I used the path("myurl/<slug:post_name>",post.post_details.as_view()), When I recieve post_name = %E5%B9%B4%E6%9C%AB%E8%AA%BF%E6%95%B4%E, this is automatically getting decoded and I am getting chinese/japanese character depending on the post_name. The problem is some of the post_name is stored in the encoded format and I want to receive the string as it is. How can I achieve this ? Thank you. I tried the path converters from here Like path("myurl/<slug:post_name>",post.post_details.as_view()), and path("myurl/<str:post_name>",post.post_details.as_view()), but None of this worked. -
How to keep django-q run on ubuntu nginx server
I use ubuntu with nginx & gunicorn and try to run django-q How can I keep django-q run when shutdown terminal please -
How to use the same ModelForm form different admin classes with different models
I'm trying to create a common form with a date range validation that will be used in 20 admin classes with different model So I'm creating this mixin for each of them to use class DateControllerMixin(): def get_queryset(self, request): qs = dateControlQuerySet(super().get_queryset(request), self.parameter_name, request) return qs def get_form(self, request, obj=None, change= None,**kwargs): print(self.parameter_name) if request.user.groups.filter(name='slaughterhouse_date_controlled').exists(): form = DateControlledForm form.model_class = self.model form.parameter_name = self.parameter_name return form return super().get_form(request, obj, change, **kwargs) And this is the form but I can't find a way to make the form without specifying the model class in the Meta or use class attributes class DateControlledForm(forms.ModelForm): def __init__( self, *args, **kwargs ): self._meta.model = self.model_class super(DateControlledForm, self).__init__(*args, **kwargs) class Meta: # model = self.model_class fields='__all__' widgets = { 'the_date': AdminDateWidget(), } def clean(self, **kwargs): print(self.paramter_name) date = self.cleaned_data.get('the_date') today = datetime.today().date() days_limit = AppConfigurations.objects.get(parameter_name=self.parameter_name).parameter_value first_day = today - timedelta(days = int(days_limit)) if date < first_day: raise forms.ValidationError({ 'the_date': [_(f"Date cannot be before {first_day}.")]}) return self.cleaned_data I tried to edit the meta options from the init method but it didn't work -
django project not executing makemigrations command as expected in vscode editör
I have a django project. I moved my project from pyCharm editor to vscode editor. When I run the python manage.py makemigrations command, it creates a migration file for some applications under venv. I think it depends on the LANGUAGE_CODE value in settings.py but I used gettext_lazy in all my models. Even if I type the command python manage.py makemigrations app_label, it still creates migration files for projects under venv. The libraries installed with pip install under venv are my own django projects. I have always used gettext_lazy in these projects. Same projects execute makemigrations in pyCharm editor with no issues -
how do I put the oversized logo overlap the nav?
thanks for your help. I just starting to learn HTML and CSS. I have been wrestling with this oversize logo problem for a week now. How do I put the logo overlap the nav like a layer look? my html file: <nav class = "navigation-bar"> <link rel="stylesheet" href="{% static 'financeapp/style1.css' %}"> <img class = "logo" src ="{% static 'financeapp/family examiner 2.png' %}" alt="company logo" height = 150px width = 150px> <div class = "navigation-container"> <ul> <li><a href="#"> Home </a></li> <li><a href="#"> About </a></li> <li><a href="#"> Contact </a></li> <li><a href="#"> Join Us </a></li> </ul> </div> my css file: .navigation-bar { display:flex; margin: 0; padding: 0; align-items: center; text-align: center; } .logo { float: left; } .navigation-container { display: flex; justify-content: space-betwee; width: 100%; /*left side*/ } .navigation-container ul { margin: 0; padding: 0; width: 100%; /*right side*/ height: 70px; background-color: yellow; } .navigation-container li { display: inline; } .navigation-container a { padding: 10px; text-decoration: none; } thanks for your time. -
Using ORM and migrations in Django
I have good knowledge of databases (DML, DDL, PL/SQL) and would like to create a web app using the Django framework. I really like the idea of migrations and ORM in general. On the other hand, I feel overwhelmed with all the features of models and ORM querying and I'm not too fond of the idea of spending hours reading docs when I can do it with SQL in an instance. I can create tables and constraints using SQL scripts and then map them to the model using Meta options "table_name" and "managed". I assume that using ORM for simple selects, inserts, deletes and updates is perfect, but what about complicated joins? What is your opinion on this matter? Should I learn ORM, go the plain SQL way, or combine both somehow? -
how to solve error 'Command errored out with exit status 1'
I want to pip install the Django project's requirements.txt file, but I get this error during execution : ERROR: Command errored out with exit status 1: command: '/home/nikafarin-ai/MrMr/Projects/NEWS reader/git/news_reader/vir/bin/python3' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-eepbf4_k/mysqlclient/setup.py'"'"'; __file__='"'"'/tmp/pip-install-eepbf4_k/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-install-eepbf4_k/mysqlclient/pip-egg-info cwd: /tmp/pip-install-eepbf4_k/mysqlclient/ Complete output (15 lines): /bin/sh: 1: mysql_config: not found /bin/sh: 1: mariadb_config: not found /bin/sh: 1: mysql_config: not found Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-install-eepbf4_k/mysqlclient/setup.py", line 15, in <module> metadata, options = get_config() File "/tmp/pip-install-eepbf4_k/mysqlclient/setup_posix.py", line 70, in get_config libs = mysql_config("libs") File "/tmp/pip-install-eepbf4_k/mysqlclient/setup_posix.py", line 31, in mysql_config raise OSError("{} not found".format(_mysql_config_path)) OSError: mysql_config not found mysql_config --version mariadb_config --version mysql_config --libs ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. I set vs code to global mode and it recognized the modules in the requirements.txt file (except for two items) -
Excel data not sorting the type Decimal
I have a view where i export data the numerical data but when i sort the data it is not getting sorted as the excel is not considering the values as numerical data how can i convert them to numerical data in order to display the data in numerical format and make the sorting work.i have a function which gets the data here is how it looks. def get_output_value(self, key, value, neutral=None): display = value if value is None and not user.is_active: return '-', '-' if value is None: return f"${Decimal('.00')}", f"${Decimal('.00')}" if isinstance(value, Decimal): return f"${intcomma(value.quantize(Decimal('.00')))}",f"${intcomma(display.quantize(Decimal('.00')))}" return value, display -
attaching a csv file django
Hi i have generated a csv and it saves correctly in my media dir . This is how I generate the csv file : def export_to_csv_file(data, titles, file_name): csv_file_address = os.path.join(settings.MEDIA_ROOT, file_name) response = HttpResponse(content_type="text/csv") response["Content-Disposition"] = "attachment; filename={}".format(file_name) response.write("\ufeff".encode("utf8")) with open(csv_file_address, "w+") as file: writer = csv.DictWriter(file, fieldnames=titles, extrasaction="ignore") headers = {title: _(title).replace("_", " ").title() for title in titles} writer.writerow(headers) for row in data: writer.writerow(row) return response, file and this is how I use this function : data_file = export_to_csv_file( serializer.data, list(self.get_serializer().Meta.headers), file_name, ) email_html_message = render_to_string( "myhtml.html", {"host": settings.SITE_URL, "file_url": data_file[1].name}, ) email = EmailMessage( email_title, email_html_message, settings.EMAIL_FROM, ["mont@gmail.com"], ) with open(data_file[1].name, "r") as file: email.attach("attach_file", file.read(), "text/csv") email.send() when I pdb the file I find out the file type is <_io.TextIOWrapper name='D:\\02_work\\Golf\\media\\spender_liste_1669015631.216596.csv' mode='r' encoding='cp1252'> what should I do to send this csv file as an attached file? Also I have tested the with open(data_file[1].name, "w+") as file: email.attach("attach_file", file.read(), "text/csv") email.send() but this time get IndexError: list index out of range in the email.send() line -
Channels development server does not taking over my Django development server
I'm learning django(4.1) channels(4.0.0) from a YouTube video and now trying to configure ASGi. Using windows and gitbash. After configuration when I run server, instead of showing: Starting ASGI/Channels version 4.0.0 development server at http://127.0.0.1:8000 it simply shows: Starting development server at http://127.0.0.1:8000/ which instructor says it means "Channels development server does not taking over my Django development server as it should." We literally just made a project(mywebsite) and an app(chat), added channels and the app to setting, and in settings we added ASGI_APPLICATION = 'mywebsite.asgi.application' asgi.py import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mywebsite.settings') application = ProtocolTypeRouter({ 'http': get_asgi_application(), }) I have compared my code to his from the source code he provided and nothing in different. Do I have a problem from my computer settings? -
How can i allow both IP Address and URL in django field?
I want to allow both flutterdemo.hp.com and 12.135.720.12 in django field. This is what i tried. from rest_framework import serializers, viewsets from django.core.validators import URLValidator class FlutterSerializer(serializers.HyperlinkedModelSerializer): fqdn_ip = serializers.CharField(max_length = 100, validators =[URLValidator]) But it is allowing all the text and just working as CharFiled. URLField is treating "flutterdemo.hp.com" as invalid. How can i achieve this? Thanks, -
Django : Custom AdminEmailHandler resulting error when starting the server (ValueError: The translation infrastructure cannot be initialized befo ...)
So i just defined a new class inside myproject/products/helpers.py that extends the django's AdminEmailHandler class (because i want to modify it to only send to specific emails / not all of the admins). class EbookTeamEmailHandler(AdminEmailHandler): def __init__(self, include_html=False, email_backend=None): AdminEmailHandler.__init__(self) self.include_html = include_html self.email_backend = email_backend def send_mail(self, subject, message, *args, **kwargs): self.mail_team_ebook(subject, message, *args, connection=self.connection(), **kwargs) def mail_team_ebook(subject, message, fail_silently=False, connection=None, html_message=None): """List email milik member team ebook""" recipients = [ "xyz@email.com" ] mail = EmailMultiAlternatives( '%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject), message, settings.SERVER_EMAIL, to=recipients, connection=connection, ) if html_message: mail.attach_alternative(html_message, 'text/html') mail.send(fail_silently=fail_silently) and defined the handler in my settings.py: LOGGING = { 'handlers': { ... 'mail_ebook_teams': { 'level': 'ERROR', 'class': 'products.helpers.EbookTeamEmailHandler' } ... }, 'loggers': { ... 'queue_create_product_error':{ 'handlers': ['queue_mailed','console','mail_ebook_teams'], 'level': 'DEBUG' }, ... } } the problem is when i start the server, it gives me error such : Unhandled exception in thread started by <function check_errors..wrapper at 0x7f3d788da170> Traceback (most recent call last): File "/home/dyaksa/.pyenv/versions/3.6.15/lib/python3.6/logging/config.py", line 390, in resolve found = getattr(found, frag) AttributeError: module 'products' has no attribute 'helpers' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/dyaksa/Code/gm-core-api/venv/lib/python3.6/site-packages/django/utils/translation/trans_real.py", line 168, in _add_installed_apps_translations app_configs = reversed(list(apps.get_app_configs())) File "/home/dyaksa/Code/gm-core-api/venv/lib/python3.6/site-packages/django/apps/registry.py", line 138, in get_app_configs … -
Django materializecss datatable jquery
I am trying getting Uncaught ReferenceError: jQuery is not defined and Uncaught ReferenceError: $ is not defined while trying to load a Select2 dropdown with datepicker. I am using Materializecss, Datatables and jQuery with Django. How can I properly structure the base.html to ensure all required css, javascript and jquery is loaded only once? Below is my code for base.html, topsearchbar.html and dashboard.html (which is throwing the above errors) base.html <!DOCTYPE html> {% load static %} <html> <head> <!--Import Google Icon Font--> <link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!--Import materialize.css--> <link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/css/materialize.min.css" rel="stylesheet"> <link href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css" rel="stylesheet"> <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet"/> <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script> <!--Let browser know website is optimized for mobile--> <meta content="width=device-width, initial-scale=1.0" name="viewport"/> <link href="{% static 'css/dashboard.css' %}" rel="stylesheet"> <title>Title</title> </head> <body> {% include 'partials/sidenav.html' %} {% include 'partials/navbar.html' %} {% block content %} {% endblock %} <!--<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>--> <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script> <script src="https://code.jquery.com/jquery-3.6.0.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/js/materialize.min.js"> </script> <script src="https://cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js" type="text/javascript"> </script> <script> $('.button-collapse').sideNav({ menuWidth: 300, // Default is 240 edge: 'left', // Choose the horizontal origin closeOnClick: true // Closes side-nav on <a> clicks, useful for Angular/Meteor } ); // Show sideNav //$('.button-collapse').sideNav('show'); </script> <script> (function(window, document, undefined) { var factory = function($, DataTable) { "use strict"; $('.search-toggle').click(function() { if ($('.hiddensearch').css('display') == 'none') $('.hiddensearch').slideDown(); … -
set ImageField "upload_to" field of a Product based on their Category name - Django
class Product(models.Model): category=models.ForeignKey(Category, on_delete=models.CASCADE, related_name='product_category', to_field='category_name') name=models.CharField(max_length=255,) description=models.CharField(max_length=255) *************************************************** images=models.ImageField(upload_to='products/'+str(category.category_name), blank=True,null=True) *************************************************** price=models.DecimalField(decimal_places=2,max_digits=7) discount=models.DecimalField(decimal_places=2,max_digits=3, validators=[MinValueValidator(0),MaxValueValidator(0.99)]) def __str__(self): return self.name I want to save images relative to the category name and product name, therefore all products with the same name would be saved in the same file. I don't know if this is the best practice, so please if it shouldn't be like this specify the best way and how can I achieve what I want. -
Value returned by property method in django not getting stored in database. How to make this possible?
In my models.py file I have a property method which returns a value and I need to store that value in the database field. ` class bug(models.Model): ...... ....... id_of_bug = models.CharField(max_length=20, blank= False, null= False) @property def bug_id(self): bugid = "BUG{:03d}".format(self.pk) self.id_of_bug = bugid return bugid Tried to store the value in database using self method, but not working. -
Error : strptime() argument 1 must be str, not int
I am trying to substract two times and getting an error. In below total error is coming up if result[0]['outTime'] != None: type = "bothPunchDone" FMT = '%H:%M:%S' total= datetime.strptime(result[0]['outTime'], FMT) - datetime.strptime(result[0]['inTime'], FMT) I tried but not able to solve the issue. -
Cannot use serializer when ManyToManyField is empty
I am utilizing PrimaryKeyRelatedField to retrieve and write M2M data. My models.py: class Task(MP_Node): ... linked_messages = models.ManyToManyField('workdesk.Message', blank=True, related_name='supported_tasks') (MP_Node is an abstraction of models.Model from django-treebeard). My serializers.py: class TaskSerializer(serializers.ModelSerializer): ... linked_messages = serializers.PrimaryKeyRelatedField(many=True, required=False, allow_null=True, queryset=Message.objects.all()) class Meta: model = Task fields = [..., 'linked_messages'] My api.py: class TaskViewSet(ModelViewSet): queryset = Task.objects.all() serializer_class = TaskSerializer def create(self, request): serializer = self.get_serializer(data=request.data) if serializer.is_valid(raise_exception=True): print(serializer.data) With other fields, if the field is set to null=True in the models, or required=False on the serializer, I don't need to include them in the data to instantiate the serializer. However, these fields do not seem to work this way, instead returning KeyError: 'linked_messages' when serializer.data is called. As a workaround I tried adding setting allow_null, as indicated by the docs, and then manually feed it a null value: request.data['linked_messages'] = None but this returns as 404: "linked_messages":["This field may not be null."] If I set it to a blank string: "resources":["Expected a list of items but got type \"str\"."] If I set it to an empty list, serializer.data again gives me an error: `TypeError: unhashable type: 'list'` It seems to have me any way I turn. What am I not understanding … -
Django: data from Views.py not displaying in HTML page
My home.html in div where I called the { data } to display in HTML <div id= "main"> <h1> DATA SCRAPPER</h1> <h2>Header Data from html Page</h2> { data } </div> The local host shows But in terminal it is showing the scrapped data Views.py where def home(request): soup= None URL = 'https://www.abc.html' page = requests.get(URL) soup = bs(page.content, 'html.parser') print(soup.h1.text) head=soup.h1.text return render(request, 'home.html', {'data': head}) -
Django - How to filter ID to post to specific item
I am trying to update only one item and one field at a time in my DB. Whenever I update the item, it updates all but I am struggling with getting the ID (to set the ID equal to the DB ID). I am using Crispy Forms. A user will add a new issue and I am only trying to update the "issue_status" field one item at a time. Issue status is the only item being updated in the form. views.py get_issues = DevIssues.objects.get(id=pk) if request.method == 'POST' and 'updateissue' in request.POST: update_issue_form = UpdateProjectIssues(request.POST, instance=get_issues) if update_issue_form.is_valid(): content = request.POST.get('issue_status') content2 = request.POST.get('issueid') DevIssues.objects.filter(pk=content2).update(issue_status=content) return redirect('/projects') templates <form name="updateissue" class="row g-3" method="post"> {% csrf_token %} <hr> <div class="col-6"> <label style="margin-bottom: 8px;">Project ID</label> <input class="form-control" type="text" name="issueid" value="{{issue.id}}" aria-label="Available" disabled readonly> </div> <div class="col-6"> <label style="margin-bottom: 8px;">Project ID</label> <input class="form-control" type="text" value="{{issue.issue}}" aria-label="Issue" disabled readonly> </div> <div class="col-10"> <label style="margin-bottom: 8px;">Project ID</label> <input class="form-control" type="text" value="{{issue.issue_desc}}" aria-label="Available" disabled readonly> </div> <div class="col-6"> <label style="margin-bottom: 8px;">Project ID</label> <input class="form-control" type="text" value="{{issue.issue_code}}" aria-label="Available" disabled readonly> </div> <div class="col-6" name="updateissue"> {{ update_issue_form.issue_status|as_crispy_field }} </div> <div class="col-10"> <button type="submit" name="updateissue" class="btn btn-primary">Update</button> </div> </form> Whenever I set DevIssues.objects.filter(pk=17).update(issue_status=content) to a specific number, I can … -
psycopg2.errors.DuplicateTable: relation "django_celery_beat_solarschedule" already exists
While deployment django project I see the following error and not clear what is missing. We deleted previous migrations too before deploying but no change in the result: Apply all migrations: admin, auth, captcha, contenttypes, django_celery_beat, django_celery_results, hitcount, sessions, watson Running migrations: Applying django_celery_beat.0002_auto_20161118_0346...Traceback (most recent call last): File "/home/jenkins/workspace/dev-jk-project/env/lib/python3.10/site-packages/django/db/backends/utils.py", line 87, in _execute return self.cursor.execute(sql) psycopg2.errors.DuplicateTable: relation "django_celery_beat_solarschedule" already exists Please let me know if you are able to fix this? -
Get First and Last Related Object for Django Rest API
I have Django Rest API serializers based on 2 models, Book and Chapter In the Book serializer I want 2 custom fields first_chapter last_chapter Each having objects of model Chapter as you can understand from the field name first and last objects order by published_at field I tried something like below to get the last chapter class LastChapterField(serializers.RelatedField): def get_queryset(self): return core_models.Chapter.objects\ .filter(comic=M.OuterRef("pk"))\ .select_related("number")\ .order_by("-published_at")[:1] But I don't see the last chapter included in my results even though it is explicitly mentioned in fields of Book Serializer I want the complete object in returning result and I want to be able to use order by on one of these nested fields (first_chapter or last_chapter) of Chapter model object. -
Hey is it possible to call one serializer class insider another in drf? Without having any foreign key relationship
class AuthorSerializer(ModelSerializer): class Meta: model = Author fields = "__all__" class BookSerializer(ModelSerializer): class Meta: model = Book fields = "__all__" I want to get data of AuthorSerializer in BookSerializer. Is it Possible? -
CKEditor doesn't save data
I'm using CKEditor for a form. In the admin it works fine, but when using it in the ModelForm of a CreateView the editor doesn't save data. As in the official docs, with this code: class EventForm(forms.ModelForm): description = forms.CharField(widget=CKEditorWidget()) image = forms.ImageField(widget=forms.ClearableFileInput(), required=False) class Meta: model = Event fields = ['title', 'description', 'type', 'start_date', 'end_date', 'fee'] And this html: <div> <form hx-post="{{ request.path }}" enctype="multipart/form-data" class="modal-content"> {% csrf_token %} <div class="modal-header"> <h1>Create new event</h1> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> {{form.media}} {{form.as_p}} </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button> <input type="submit" value="Submit"> </div> </form> </div> It won't let me submit the form as it will keep saying that the description field is required. Trying to add the CKEditor widget field in the init method, with this code: class EventForm(forms.ModelForm): image = forms.ImageField(widget=forms.ClearableFileInput(), required=False) class Meta: model = Event fields = ['title', 'description', 'type', 'start_date', 'end_date', 'fee'] def __init__(self, *args, **kwargs): super(EventForm, self).__init__(*args, **kwargs) self.fields['start_date'].widget = forms.SelectDateWidget() self.fields['end_date'].widget = forms.SelectDateWidget() self.fields['description'].widget = CKEditorWidget() The form will be sent, and the instance created. However, the 'description' field will be empty even if I enter some content. This is my view: class CreateEvent(LoginRequiredMixin, CreateView): model = Event form_class = … -
Page not found (404) upon Heroku Deployment
I have been having difficulties getting to deploy my Heroku app with my Django and React app. The error is as follows: Page not found (404) Request Method: GET Request URL: https://true-friends-404.herokuapp.com/login/ Using the URLconf defined in truefriends.urls, Django tried these URL patterns, in this order: admin/ ^authors/$ [name='authors-list'] ^authors\.(?P<format>[a-z0-9]+)/?$ [name='authors-list'] ^authors/(?P<pk>[^/.]+)/$ [name='authors-detail'] ^authors/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='authors-detail'] ^$ [name='api-root'] ^\.(?P<format>[a-z0-9]+)/?$ [name='api-root'] ^posts/$ [name='posts-list'] ^posts\.(?P<format>[a-z0-9]+)/?$ [name='posts-list'] ^posts/(?P<pk>[^/.]+)/$ [name='posts-detail'] ^posts/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='posts-detail'] ^$ [name='api-root'] ^\.(?P<format>[a-z0-9]+)/?$ [name='api-root'] swagger/ [name='schema-swagger-ui'] api/ api/auth/ friendrequest/ [name='friend_request_list'] friendrequest/accept/<int:fr_id>/ [name='friend_request_accept'] friendrequest/reject/<int:fr_id>/ [name='friend_request_reject'] friendrequest/<int:author_id>/ [name='friend_request_to_user'] authors/<int:author_id>/ authors/<int:author_id>/ posts/<int:post_id>/ comments/<int:comment_id>/ authors/<int:author_id>/inbox/ followers/ [name='followers_list'] following/ [name='following_list'] unfollow/<int:user_id>/ [name='unfollow_by_user_id'] unfriend/<int:user_id>/ [name='unfriend_by_user_id'] withdraw/<int:user_id>/ [name='withdraw_by_user_id'] truefriends/ [name='true_friends_list'] posts/<int:post_id>/ authors/<int:author_id>/ currentauthor/ ^media/(?P<path>.*)$ The current path, login/, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. Here is the urls.py file # import ... post_router = routers.DefaultRouter() post_router.register(r'posts', PostView, 'posts') logged_in_post_router = routers.DefaultRouter() logged_in_post_router.register(r'posts', LoggedInPostView, 'my-posts') author_router = routers.DefaultRouter() author_router.register(r'authors', AuthorView, 'authors') post_like_router = routers.DefaultRouter() post_like_router.register(r'likes', PostLikeView, 'post-likes') author_like_router = routers.DefaultRouter() author_like_router.register(r'likes', AuthorLikeView, 'author-likes') post_comment_router = routers.DefaultRouter() post_comment_router.register(r'comments', PostCommentView, 'post-comments') author_comment_router = routers.DefaultRouter() author_comment_router.register(r'comments', AuthorCommentView, 'author-comments') schema_view = get_schema_view( openapi.Info( # add your swagger doc title …