Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Display django field choices in a particular order
I am using django models and one of the charfields has a list of choices like class Ster(models.Model): STER_PRODUCTS_CATEGORY = [ ('Steam', 'Steam'), ('ETO', 'ETO'), ('Plasma', 'Plasma'), ('LTSF', 'LTSF'), ('Heat', 'Heat') ] ster_prod_name = models.CharField(max_length=100) ster_prod_category = models.CharField( max_length=100, choices=STER_PRODUCTS_CATEGORY, default='None') Whenever I add an item to any of the category, that particular category is shown first on the webpage. For ex, if i add an item to the category Heat, that category is displayed first. I am looping through the list. My views.py function looks like this ster_catprods = Ster.objects.values('ster_prod_category', 'id') ster_cats = {ster_item['ster_prod_category'] for ster_item in ster_catprods} for ster_cat in ster_cats: ster_prod = Ster.objects.filter(ster_prod_category=ster_cat) m = len(ster_prod) mSlides = m // 4 + ceil((m / 4) - (m // 4)) ster_prods.append([ster_prod, range(1, mSlides), mSlides]) My HTML Template snippet is like this <section class="container"> <h4 style="margin: 1em auto">1.STER</h4> <div class="row"> {% for p,range,mSlides in ster_prods %} <div class="col-xs-12 col-sm-6 col-md-4 col-lg-4 col-xl-4" data-aos="zoom-in-up" style="margin: 1em auto"> <h4 class="category-title my-4">{{p.0.ster_prod_category | safe}}</h4> {% for i in p %} <h6 class="product_title">{{i.ster_prod_name | safe }}</h6></a> {% endfor %} </div> {% endfor %} </div> </section> how do i get to display the categories in a particular order like the way i want? The … -
Filter django models by field and include data with null field
I have the dataset where i need to fetch some articles by companies, but also in same query i need to fetch data which have company = null. Basically fetch company = 1 or company = null I tried something like this but filter does not recognize None and just skip. # example 1 Article.objects.filter(company__in=[1, None]) I tried something like this and this works, but i need something like example above, because i have framework for filtering which takes dict as custom filters, so i need key value pairs. # example 2 Article.objects.filter(Q(company_id=1) | Q(company=None)) Is there any way i achive something like example 1 or some similar solutions? EDIT: If im stuck with example 2 is there any way i can combine those two, i have something like this Article.objects.filter(**custom_filter) custom filter is dict, for example i have currently custom_filter = { 'app': 1, 'company': 1 } -
Django package to import data from excel file
It's been around 10 months since I am working as a professional Software Engineer (Python). The significance of reusable codes is quite understandable to all of us. We can save lots of each other's time by sharing reusable codes. Frameworks and packages perhaps serve the same purpose. During a project, I had to make a feature where users can upload data from excel files but in a convenient manner. I felt the necessity of using this feature in many projects. Thus, later on, I have made it a package so that anyone can plug it into their project and get benefited. So, if anyone of you requires such a feature, you are welcome to experiment. The package is licensed under MIT and available in pypi. Your contributions to this package will always be appreciated and perhaps, will help other folks. https://github.com/prantoamt/django-parser-app -
Error : The QuerySet value for an exact lookup must be limited to one result using slicing
I am new to django and am creating a question answer app I am getting the following error: The QuerySet value for an exact lookup must be limited to one result using slicing. models.py: from django.db import models from django.contrib.auth.models import User from django.utils.text import slugify from django.contrib.auth.models import User class Log(models.Model): title = models.CharField(blank=False, max_length=500) content = models.TextField(blank=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) slug = models.SlugField(max_length=50, null=False) created_by = models.CharField(null=True, max_length=500) avatar = models.ImageField( upload_to='images', blank=True) def save(self, *args, **kwargs): self.slug = self.slug or slugify(self.title) super().save(*args, **kwargs) class Meta: verbose_name = ("Log") verbose_name_plural = ("Logs") def __str__(self): return f"{self.title}" class Solutions(models.Model): log = models.ForeignKey( Log, on_delete=models.CASCADE, blank=True, null=True) solution = models.TextField(null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) slug = models.SlugField(max_length=50, null=False, blank=True) def save(self, *args, **kwargs): self.slug = self.slug or slugify(self.title) super().save(*args, **kwargs) class Meta: verbose_name = ("Solution") verbose_name_plural = ("Solutions") def __str__(self): return f" {self.log.title} {self.solution} " class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) log = models.ForeignKey(Log, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) def __str__(self): return f"like by {self.user.username} for {self.log.title}" class Comments(models.Model): created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) log = models.ForeignKey( Solutions, on_delete=models.CASCADE, null=True, blank=True) comment = models.TextField(null=True, blank=True) created_by = models.CharField(null=True, max_length=500) class Meta: verbose_name = ("Comment") verbose_name_plural … -
Can Django Framework be used for API automation testing?
I am supposed to create a python automation framework for API testing (as part of replacing SOAP-UI and we would be using it for Functional/Regression test phases). Can I use Django/Flask for this or these are only meant for development-related stuff? I have come across the simplest way of using "request libraries" incorporated with nosetest/unittest but my client is bit sceptical regarding this and asking me to check for the above "frameworks". Any suggestions would be really helpful. -
Filtering in Django against a JsonField wich is a Json Array with dates values in it
I have a model in Django where there is a JsonField named periodicity which serialize in an Json Array like this: { "id_series": 12381, "country_name": "Central African Republic", "periodicity": [ { "period": "monthly", "start_date": "2010-10-01", "end_date": "2018-10-01" }, { "period": "weekly", "start_date": "2011-10-01", "end_date": "2018-01-01" } ] }, { ... } So my aim is to filter and find the series that have not been updated in less than a certain date. For that I need to query on the end_date of the inner Json Array. What is the best way to do a filtering? I have tried casting the end_date to a date object by doing this : from django.db.models.expressions import RawSQL Serie.objects.annotate(endDate=RawSQL("((periodicity->>'end_date')::date)", [])).filter(endDate__gte=comparisonDate) But so far it has not produced any result. I am looking into something like this https://stackoverflow.com/a/65184218/2219080. -
Sending Mail in django
I am facing a problem when trying to test sending a message from the django app . The problem is that no messages arrive on my email after sending and I don't know what is the reason, please help this is my settings : EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'myname@gmail.com' EMAIL_HOST_PASSWORD = '****************' EMAIL_USE_TLS = True EMAIL_PORT = '587' this is my views.py: def contact_us(requset): subject = requset.POST.get('subject', '') message = requset.POST.get('message', '') from_email = requset.POST.get('from_email', '') send_mail(subject, message, from_email, ['myname@gmail.com']) return render( requset , 'accounts/contact_us.html' ) this is my contact_us.html: <div class="contact_form"> <form name="contact_form" action="" method="POST"> {% csrf_token %} <p><input type="text" name="subject" class="name" placeholder="subject" required></p> <p><textarea name="message" class="message" placeholder="message" required></textare></p> <p><input type="text" name="from_email" class="email" placeholder="email" required></p> <p><input type="submit" value="sent" class="submit_btn"> </p> </form> </div> -
Displaying validation error instead of default text errors in Django UserCreationForm
I have a very simple registration form on my website. My form works, but if a username already exists or my 2 password fields don't match, after I submit the form, Django does not do anything and just focuses the field with the error. I know this is probably an easy fix, but how do I display a validation error if a requirement is not met? For example, if I submit my form with a username that already exists, how do I display an error to the user? My code is down below. Views.py: from django.http.request import RAISE_ERROR from django.shortcuts import render, redirect from django.http import HttpResponse from django.forms import inlineformset_factory from django.contrib.auth.forms import UserCreationForm from .forms import CreateUserForm from django.contrib import messages # from .forms import RegisterForm # Create your views here. def index(request,*args, **kwargs): return render(request, "index.html", {} ) def register(request,): form = CreateUserForm() if request.method == "POST": form = CreateUserForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been successfully created, {username} ') return redirect('login') context = {'form': form} return render(request, "register.html", context ) def login(request,): return render(request,"login.html") Register.html {% load crispy_forms_tags %} {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta … -
I can't get my second django view to validate the post request after the first view redirects
I'm having issue where i want the second view where it validates if a "post" request is validated, execute the set of code. Here's an example: from django.shortcuts import render, redirect from django.http import HttpResponse, Http404 from django.urls import reverse from django.template import loader from django.core.mail import send_mail, mail_admins from .forms import Register # Importing Models from .models import Users # Create your views here. # Create your views here. def register(request): if request.method == "POST": forms = Register(request.POST) if forms.is_valid(): f_name = forms.cleaned_data["first_name"] l_name = forms.cleaned_data["last_name"] em = forms.cleaned_data["email"] num = forms.cleaned_data["phone"] user = Users( first_name=f_name, last_name=l_name, email=em, phone=num ) user.save() request.session['f_name'] = f_name request.session['status'] = True request.session['email'] = em return redirect('success') else: forms = Register() forms = Register() title = "Join now" context = { 'title':title, 'forms':forms, } return render(request, 'register/register.html', context) def success(request): #This part wont validate after the post redirect? **if request.method == 'POST':** welcome = request.session['f_name'] email = request.session['email'] # User Mailing subject = f'Welcome to JSG {welcome}' message = 'Testing' from_email = 'mydev1996@gmail.com' recipient_list = [email] user_mail = send_mail( subject, message, from_email, recipient_list, fail_silently = False, ) # Admin Mailing subject = f'Welcome to JS {welcome}' message = 'Testing' admin_mail = mail_admins( subject, message, … -
Python, django: I don't know how to connect the simple basic fuction I made to the values User put
I did test the basic, simple function on the following and it worked fine. from .area import suburbs print('please select airport direction') e = input() print('please put suburb') b = input() print('please put the number of passengers') c = input() c = int(c) d = suburbs.get(b) d = int(d) def price_cal(self): if e == 'To airport': return d + (c * 10) - 10 elif e == 'From airport': return d + (c * 10) k = int(price_cal()) print(k) Actually User is supposed to select 3 choices To airport / From airport Suburb The number of passengers I would like to calculate the price showing to the webpage (html) with those values User put I tried to write some code at views.py like below but as I exptected, error came out... e = Post.instance.flight_number b = Post.instance.suburb d = suburbs.get(b) d = int(d) c = Post.instance.no_of_passenger c = int(c) class Price: def price_cal(self): if e == 'To airport': return d + (c * 10) - 10 elif e == 'From airport': return d + (c * 10) price_cal() def price_detail(self, request): price = self.price_cal() return render( request, 'basecamp/price_detail.html', { 'price': price, } ) I tried to put instance or object … -
Invalid HTTP_HOST header: '127.0.0.1:8000'. You may need to add '127.0.0.1' to ALLOWED_HOSTS
I keep on getting this error whenever I run my server locally. This is how allowed hosts is in my .env file ALLOWED_HOSTS=['*'] I have tried adding '127.0.0.1' to the .env file instead of * but nothing seems to be working.Any ideas? -
Why does creating my own custom error pages (400) leads to a Server Error with valid urls?
Hello There, I am trying to create a custom error page (404) in Django. It works well with invalid urls but with valid urls, it gives an error as: Server Error (500) views.py file: def error_404_view(request, exception): return render(request, "400.html") urls.py file, Also this is my Project's urls.py not the app's: handler404 = "members.views.handler404" settings.py file: DEBUG = False ALLOWED_HOSTS = ["*"] Any help will be much appreciated -
How do I set a condition in HTML button tags to stop my Webcam Video Stream on webpage | Python Django
The webcam video stream is displayed on another webpage, so I try to stop my webcam video stream when directed to my homepage but the webcam keeps on running. How can turn it off? here is my views.py still_on = True def gen(tryhaar): while still_on: frame = tryhaar.get_frame() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') def video_feed(request): return StreamingHttpResponse(gen(VideoCamera()), content_type='multipart/x-mixed-replace; boundary=frame') def home(request): return render(request, "main/home.html",{}) here is my html {% extends 'main/base.html' %} {% block content %} <h1>Stimulus Section</h1> <br> <img src="{% url 'video_feed' %}"> <br> <br> <h2>{{ S6 }}</h2> <br> <br> <br> <button class="btn btn-primary" onclick="location.href='{% url 'home' %}'">Home</button> {% endblock %} My idea is to set a condition in my button tag to let still_on variable to be False when the button is clicked so that the webcam stop running. How can I do that? Or is there other way it can be done? here is my tryhaar.py where VideoCamera class is defined just in case. class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture(0) def __del__(self): self.video.release() def get_frame(self): success, image = self.video.read() raw_img = image.copy() # for dataset gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) eyes_detected = eyes_detection.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5) for (x, y, w, h) in eyes_detected: cv2.rectangle(image, pt1=(x, … -
I could simply delete the migration 0001_initial.py but it is not recommended to delete , so how could I fix this one without deletion of migration
raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration home.0001_initial dependencies reference nonexistent parent node ('cms', '0024_auto_20210516_0955') -
Long loading Django Admin when trying to add Model object
I have really annoying problem with my Django app. It is already deployed to Ubuntu Server, and when I try to access any object of Model called 'Detail', it just won't load the page. The same thing happens when trying to create 'Detail' objects via Django Admin, just infinite downloading. It doesn't happen with other models, though they have the same amount of objects in there (about 181000). It also happened on my local machine before I deployed app to the server, so the problem is not with the server. I guess this happens because of amount of objects in DB table, but there must be some way to fix this problem, so I hope someone can help me with that. -
ajax call not success, the success call back could not be executed
I have used Django2 to develop a web app. I frontend, the ajax call could not work well, the network tab on chrome dev does show the 200 status code, but I did not any alert box. function myFunction() { Swal.fire ({ title: '', text: "Do you want to confirm entries?", type: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Yes', cancelButtonText: 'No' }).then ( (result) => { if (result.value) { $("#myform").submit(); //sleep(1000); $.ajax ({ url: "{% url 'bms:content_checklist_name_url' %}", type: 'GET', dataType : 'json', success: function(msg_json) { alert(msg_json.responseText) let a = ""; if (a === "Duplicate Entry. This Course Code already exists.") { Swal.fire({ title: '', text: 'Duplicate Entry. This Course Code already exists.', type: 'error', timer: 5000 }) } else { Swal.fire({ title: '', text: 'Entries have been saved.', type: 'success', timer: 5000 }) } }, failure: function(data) { alert('Got an error dude'); } }); } else { window.stop(); } } ) } backend view.py: @csrf_exempt def content_checklist_name_url(request): if request.method == 'POST': ... msg = "success" obj = {"msg": msg} context = {'msg_json': json.dumps(obj)} return render(request, 'bms/main.html',context=context) No error in the console, also not alert shows. the page quickly refreshed without showing any alert message. How could I … -
JWT Authentication using custom database table in Django
I have a working Django REST API as back-end. I was previously using JWT Token Based Authentication for accessing the api's. For that I was used default django User. Now I planned to move login authentication method using custom database table field (like username and password), I can achive user login page using custom login page API, but after login I can't authenticate the API using JWT Token. Can someone please suggest how to authenticate API using JWT Token with custome database table. table_name : userdetails, fields : username, password -
cannot import name 'PredResults' from 'predict.models'
Here is the code from my Django app named 'predict' from the models' file. from django.db import models class PredResults(models.Model): month = models.FloatField() grade = models.FloatField() score = models.FloatField() bonus_score = models.FloatField() classification = models.CharField(max_length=30) def __str__(self): return self.classification When I am running my project, it's giving me an error that: File "C:\django_project\predict\views.py", line 4, in <module> from .models import PredResults ImportError: cannot import name 'PredResults' from 'predict.models' (C:\django_project\predict\models.py) How can I fix this? -
Replace SQLite database with a MySQL Database in Django
I am currently working on my first Django project. I made a website where my team and I could upload CSV's to be run through python and I made a SQLite model that I never really used. I now have access to this website's database so we no longer have to use these CSVs downloaded from the site. I have been trying to follow along online on how to switch to an existing database. The database is managed through phpMyAdmin and uses MySql First I updated my database config: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'MadeUpName', 'USER': 'UserIDForDB', 'PASSWORD': 'MyPasswordThatGoesWithUser', 'HOST': 'db.Website.com', 'PORT': '', } } For clarification, for Name I just made up a name, User and Password are my login credentials for PHPMyAdmin, the Host is the actual host I was told I could use when connecting through code and I left port blank for defaults. I removed the old model I had built in the models.py file. When I run python manage.py inspectdb I still see the model I build and my admin/user stuff. I have tried migrating but it says no migrations. I also made sure to install mysql. I imagine I am missing … -
Why it Printing out different name? in Django
I want to Print all the result same. my code: models.py: class Product(models.Model): name = models.CharField(max_length=100) image = models.ImageField(upload_to='images') description = models.TextField(max_length=10000, blank=True, null=True) category = models.ManyToManyField(Category, related_name='category') company = models.ForeignKey(Company, related_name='company', on_delete=models.CASCADE) price = models.IntegerField() discount = models.IntegerField(default=0) views.py: excludeCompanyId = [] company = Company.objects.all().order_by('?').exclude(id__in=excludeCompanyId)[:1]#random 1 company companyName = company[0].name print(companyName) companyProduct = Product.objects.filter(company=company).order_by('?')[:10] print(companyProduct[0].company) for i in companyProduct: print(i.company) Result will be different at different time. But I want to show you one result: Tesla Apple Inc. Sony Sony Sony Sony I want to print all the result same. how do i do that? -
Python Pickle.dump UTF8
im using this codes to make chatbot in python: https://data-flair.training/blogs/python-chatbot-project/comment-page-5/ The problem is this code do not run probably when im using Arabic words. I think the problem is in pickle to dump words in utf8. Please help me to reslove this problem -
Facing issues in running django server
Hey i'm learning a python course and just came upon using django...but as i clear the command: python manage.py runserver in the terminal its giving the error C:\Users\Owner\Desktop\vs code>python manage.py runserver python: can't open file 'manage.py': [Errno 2] No such file or directory Plus it turns out there's some problem with my manage.py file(which does exist) showingImport "django.core.management" could not be resolved from sourceand the issue is in line 8 : #!/usr/bin/env python import os import sys if name == 'main': os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) Can someone pls help me out with this? -
gunicorn.socket: Failed with result 'service-start-limit-hit' , what should i do now?
As i was following the guide https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-20-04 when i used sudo journalctl -u gunicorn.socket i got the following error -- Logs begin at Mon 2021-05-31 02:03:42 UTC, end at Sat 2021-06-05 13:11:38 UTC. -- Jun 02 11:04:28 ubuntu-s-1vcpu-1gb-blr1-01 systemd[1]: Listening on gunicorn socket. Jun 02 11:06:38 ubuntu-s-1vcpu-1gb-blr1-01 systemd[1]: gunicorn.socket: Failed with result 'service-start-limit-hit'. Jun 02 11:12:10 ubuntu-s-1vcpu-1gb-blr1-01 systemd[1]: Listening on gunicorn socket. Jun 02 15:01:32 ubuntu-s-1vcpu-1gb-blr1-01 systemd[1]: gunicorn.socket: Failed with result 'service-start-limit-hit'. Jun 02 15:15:35 ubuntu-s-1vcpu-1gb-blr1-01 systemd[1]: Listening on gunicorn socket. Jun 02 15:18:37 ubuntu-s-1vcpu-1gb-blr1-01 systemd[1]: gunicorn.socket: Failed with result 'service-start-limit-hit'. -- Reboot -- Jun 02 15:20:08 ubuntu-s-1vcpu-1gb-blr1-01 systemd[1]: Listening on gunicorn socket. Jun 02 15:22:28 ubuntu-s-1vcpu-1gb-blr1-01 systemd[1]: gunicorn.socket: Failed with result 'service-start-limit-hit'. Jun 02 15:23:31 ubuntu-s-1vcpu-1gb-blr1-01 systemd[1]: Listening on gunicorn socket. Jun 02 15:43:25 ubuntu-s-1vcpu-1gb-blr1-01 systemd[1]: gunicorn.socket: Failed with result 'service-start-limit-hit'. Jun 02 15:46:44 ubuntu-s-1vcpu-1gb-blr1-01 systemd[1]: Listening on gunicorn socket. my gunicorn.socket file [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target my gunicorn.service file [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=developer Group=www-data WorkingDirectory=/home/developer/myprojectdir ExecStart=/home/developer/myprojectdir/myprojectenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ bharathwajan.wsgi:application [Install] WantedBy=multi-user.target -
FOREIGN KEY constraint failed on django custom user model
I am currently working on a Django project where I am stuck at creating a custom user model I am getting the error FOREIGN KEY constraint failed Please help me solve the error My models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, UserManager import string import random from .managers import UserManager # Create your models here. def generate_unique_code(): length = 6 while True: code = ''.join(random.choices(string.ascii_uppercase, k=length)) if User.objects.filter(user_name=code).count() == 0: break return code class User(AbstractBaseUser): email = models.EmailField(unique=True, max_length=255) full_name = models.CharField( max_length=50, default='', null=True, blank=True) user_name = models.SlugField(unique=True, default=generate_unique_code) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) address = models.CharField( max_length=255, default='', null=True, blank=True) phone_no = models.CharField( max_length=11, default='', null=True, blank=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = ['user_name', 'phone_no', 'address', 'full_name'] objects = UserManager() def __str__(self): return self.email def get_full_name(self): return self.full_name def get_username(self): return self.user_name def get_email(self): return self.email def get_address(self): return self.address def get_phone_no(self): return self.phone_no def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.staff @property def is_admin(self): return self.admin My managers.py from django.contrib.auth.models import BaseUserManager class UserManager(BaseUserManager): def create_user(self, email, user_name, full_name="", address="", phone_no="", password=None, is_staff=False, is_admin=False): if not email: raise ValueError("Users must have an email address") if not password: … -
django.urls.reverse(): URL-encoding the slash
When one supplies URL args or kwargs to a django.urls.reverse() call, Django will nicely URL-encode non-Ascii characters and URL-reserved characters. For instance, given a declaration such as path("prefix/<stuff>", view=MyView.as_view(), name="myurl") we get reverse('myurl', args=['aaa bbb']) == "/prefix/aaa%20bbb" reverse('myurl', args=['aaa%bbb']) == "/prefix/aaa%25bbb" reverse('myurl', args=['Ä']) == "/prefix/%C3%84" and so on. So far, so good. What Django will not encode, however, is the slash: reverse('myurl', args=['aaa/bbb']) will give us django.urls.exceptions.NoReverseMatch: Reverse for 'myurl' with arguments '('aaa/bbb',)' not found. 1 pattern(s) tried: ['prefix/(?P<stuff>[^/]+)$'] (The question what to encode and what not has been discussed as a Django issue. It's complicated.) I found a remark in the code that may explain why the slash is a special case: _reverse_with_prefix in django/urls/resolvers.py contains a comment that says # WSGI provides decoded URLs, without %xx escapes, and the URL # resolver operates on such URLs. First substitute arguments # without quoting to build a decoded URL and look for a match. # Then, if we have a match, redo the substitution with quoted # arguments in order to return a properly encoded URL. Given that unencoded arguments are used in the matching initially, it is no wonder that it does not work: The slash looks like the …