Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django REST query: Retrieve Users
I'm looking to retrieve all employees (User) of the current User (id is given). Employees is a ManyToMany field of User. Currently it just shows the current user. But user.employees just returns the ids of all employees. Would it be possible to make a query to retrieve all the Employees of the current User? Would be awesome if someone could steer me in the right direction. :) views.py # display all your employees class EmployeeViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer def list(self, request): queryset = User.objects.filter(pk=request.user.pk) #get current user serializer = UserSerializer(queryset, many=True) return Response(serializer.data) models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) employees = models.ManyToManyField(User, related_name='employees') -
cannot import name in django rest framework
Structure of app areas models.py from django.db import models from products.models import ProductModel class ProductionLine(models.Model): name = models.CharField(max_length = 50, unique=True) products models.py from django.db import models from areas.models import ProductionLine class ProductModel(models.Model): name= models.CharField(max_length = 255, unique=True) productionLine = models.ForeignKey(ProductionLine,on_delete=models.CASCADE) I'm trying to import ProductLine, but when i import ProductLine i have an error : File "/app/areas/models.py", line 2, in * from products.models import ProductModel* ImportError: cannot import name 'ProductModel'* And when i delete the import of ProductionLine in products.models, everything works. I don't understand -
Django Creating a Subscription Service
I've been making a subscription type service in Django 3, and I'm following a tutorial on how to do it using Django 2, but then putting it into Django 3 context. I keep getting a MultiValueDictKeyError for my stripeToken, but I can't actually see why this is. Here's my template & script for fetching it - var form = document.getElementById('payment-form'); form.addEventListener('submit', function(event) { event.preventDefault(); stripe.createToken(card).then(function(result) { if (result.error) { // Inform the user if there was an error. var errorElement = document.getElementById('card-errors'); errorElement.textContent = result.error.message; } else { // Send the token to your server. stripeTokenHandler(result.token); } }); }); var successElement = document.getElementById('stripe-token-handler'); document.querySelector('.wrapper').addEventListener('click', function() { successElement.className = 'is-hidden'; }); function stripeTokenHandler(token) { successElement.className = ''; successElement.querySelector('.token').textContent = token.id; // Insert the token ID into the form so it gets submitted to the server var form = document.getElementById('payment-form'); var hiddenInput = document.createElement('input'); hiddenInput.setAttribute('type', 'hidden'); hiddenInput.setAttribute('name', 'stripeToken'); hiddenInput.setAttribute('value', token.id); form.appendChild(hiddenInput); // Submit the form form.submit(); } The template - <form id="payment-form"> {% csrf_token %} <div id="card-element" class="MyCardElement"> <!-- Elements will create input elements here --> </div> <div id="card-errors" role="alert"></div> <button class="btn mt-5" type="submit">Submit</button> <div id="stripe-token-handler" class="is-hidden">Success! Got token: <span class="token"></span></div> </form> and if it's any use, here's the template that uses … -
How to pass javascript value to a form in django?
I need to show user uploaded image before saving the image path to database and the image file to django media folder. I am able to show the uploaded image to the user using a javascript function but now I need to pass the image to the form during POST so the image path and file get saved. I am using django modelform for saving user information like user first name to database. <form class="form" enctype="multipart/form-data" action="" method="POST"> <div class="card"> <div class="row no-gutters"> <div class="col-sm-4"> {%if form.photo != None %} <input id="profile_image_input" type="file" name="" value=""> <img id="profile_image" src="#" class="card-img" alt="profile-picture"> {% endif %} </div> <div class="col-sm-8"> <div class="card-body"> <h5 class="card-title">Welcome</h5> <p class="card-text">{{form.first_name}}</p> </div> </div> </div> </div> </form> <script type="text/javascript"> function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $('#profile_image').attr('src', e.target.result); } reader.readAsDataURL(input.files[0]); } } $("#profile_image_input").change(function(){ readURL(this); }); </script> -
Field level permissions django
I want to know what are the best ways we can assign field level permissions in Django given the user . If the role of the user is employeee. In the same form used for all the roles . I want some fields to be read only . Is there any way that could happen and how . I tried using this in forms didn't work though . def __init__(self, *args, **kwargs): user = kwargs.pop('user') super(ProgramForm, self).__init__(*args, **kwargs) if user.role =='ver': ProgramForm.fields['balise_id'].widget.attrs['readonly'] = True -
get all instances of a model while removing duplicates based on a field while also attaching the count of the same field
class Titlecomplaint(models.Model): title= models.ForeignKey("titles.title", on_delete= models.CASCADE) user= models.ForeignKey("auth.user", on_delete= models.CASCADE) content = models.TextField(max_length=250,null=True,blank=True) From the model above, I need to get only one copy of every title ordered by the amount of the same titles in the model while also getting the count of the amount. the_titles= Titlecomplaint.objects.annotate(cnt=Count("title")).values_list('title', flat=True).distinct().order_by("cnt") I'm trying the ORM above but it only returns integers while I need query objects to work on. -
How to use Django button as form input field?
I am trying to use a button in order to change the font size on my application. I have a ModelForm that saves the font size. What I cannot do is use a button as input for the font size. The buttons <form method="POST"> {% csrf_token %} <input type="submit" name="btn" value=11> <input type="submit" name="btn" value=12> </form> Normally i would do: form.save() in the view.py however I am not sure how to do this for a button... Here is the view.py def test_view(request): if request.method == 'POST': form = fontform(request.POST) if form.is_valid(): val = form.cleaned_data.get("btn") --HOW DO I SAVE BUTTON VAL HERE USING .save()????--- else: form = fontform() return render(request, 'home.html') Thank you in advance! -
Passing Values from JavaScript to Django
** I have three forms like this. ** <form id = "myForm" style="list-style-type: none;display: none;" class="form_class"> {% csrf_token %} item1: <input type="text" name="item1" style="width:10%;height:5%"> <br> item2: <input type="text" name="item2" style="width:10%;height: 5%"> <br> item2: <input type="text" name="item2" style="width:10%;height: 5%"> <br> item2: <input type="text" name="item2" style="width:10%;height: 5%"> <br> item2: <input type="text" name="item2" style="width:10%;height: 5%"> <br><br> <input id="close_form" type="reset" value="reset"> </form> Bellow code is used to click the button and it will go the javascript method <form method="post"> {% csrf_token %} <input class="bg-yellow text-white" value="RUN" name="runModel" type="submit" onclick="sendValuesToBack()"> </form> ** In the JavaScript method, I'm getting all three form's values. I want those in Django Framework to perform several operations. How to send this from Javascript to Django and get the data to the Django Framework? ** -
Should I always pass the user password for encryption?
I'm aware of how encryption works. I'm unable to get my mind around the fact that for generating a key using PBKDF2HMAC, I need the user password for encryption. For example, if a user logs in and creates a note, I want it to be encrypted. The key that is derived shouldn't be stored anywhere. So should I pass the users password every time the user creates a note for it to be encrypted or is there any other way. Note: By passing the user password, I mean from the frontend to the backend. Also, is it bad practice to store the user password as a django-session variable once it has been passed by the user? -
for loop not working for boostrap carousel
I have a for loop that displays images (media_gallery1-4) obtained from users. Each post should display four images and cycle in a bootstrap carousel. There are about 10 posts on my page. When I click the next or previous button on any of the 10 posts it only changes the image of the first post and the other 9 remain the same. How do I change my code so that the next/previous arrows change cycle through the images for that specific posts. Let me know if more context is needed. {% for post in posts %} <div class="container"> <div class="row"> <div class = "form-group col-md-6 mb-0"> <div id="carouselExampleControls" class="carousel slide"> <ol class="carousel-indicators"> <li data-target="#carouselExampleIndicators" data-slide-to="0"class="active"> </li> <li data-target="#carouselExampleIndicators" data-slide-to="1"></li> <li data-target="#carouselExampleIndicators" data-slide-to="2"></li> <li data-target="#carouselExampleIndicators" data-slide-to="3"></li> </ol> <div class="carousel-inner"> <div class="carousel-item active" id="slide1"> {% if post.media_gallery %} <img class="img" src="{{post.media_gallery.url}}"> {% else %} <div class="defualt_image"> <img src= "{% static 'main/images/boston_apartments.jpg' %}"> </div> {% endif %} </div> <div class="carousel-item active" id="slide2"> {% if post.media_gallery2 %} <img class="img" src="{{post.media_gallery2.url}}"> {% else %} <div class="defualt_image"> <img src= "{% static 'main/images/boston_apartments.jpg' %}"> </div> {% endif %} </div> <div class="carousel-item active" id="slide3"> {% if post.media_gallery %} <img class="img" src="{{post.media_gallery3.url}}"> {% else %} <div class="defualt_image"> <img src= … -
form.is_valid() returns False and the login() function doesn't work
I'm trying to login a user who was previously registered in a database, but the form.is_valid() returns False and the login() function doesn't work. I extendended the User class whit a Client class that is inheriting from User, and I think this is what is causing the issue, because I tried almost the same code before, but without the extended User class, and it perfectly worked. What am I doing wrong? My models.py: from django.db import models from django.contrib.auth.models import User class Client(User): address = models.CharField(max_length=255) state = models.CharField(max_length=255, null=True) city = models.CharField(max_length=255,null=True) phone = models.IntegerField() My forms.py: from django.contrib.auth.models import User class Auth(forms.ModelForm): class Meta: model = User #I tried here both User and Client and returns the same result (form isn't valid) fields = [ 'username', 'password', ] labels = { 'username': '', 'password': '', } widgets = { 'username': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Usuario', 'style':'margin-bottom:15px'}), 'password': forms.PasswordInput(attrs={'class':'form-control','placeholder':'Contraseña'}), } My views.py: from django.shortcuts import render from .models import Cart from .forms import Auth from django.shortcuts import redirect from django.contrib import messages from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout def main(request): productos = Cart.objects.all() users=User.objects.all() if request.method == 'POST': if request.user.is_authenticated: messages.warning(request,'Ya existe un usuario autenticado') return redirect('main') else: … -
pairs queryset in django - the way to do it and the optimal db structure?
I have a model structure like that: class Family: ... class Person: role = models.CharField(choices=['husband', 'wife']) family= ForeignKey(to=Family) investment = models.IntegerField() ... # bunch of other fields here relevant for queries I need to do a lot of queries that would involve group operations. For instance get total investment per family and separate investments for husband and wife. So the resulting table would look like: Family Husband Husb.Investment Wife Wife.Investment TotalFamilyInvestment 1 1 10000 2 20000 30000 2 3 25000 4 1000 26000 While TotalFamilyInvestment is not a problem, just a Sum over family.persons.all(), I can't figure out how effectively plug in the same queryset 'husband' and 'wife' amounts, without just looping stupidly through each 'Family' instance requesting its persons filtered by role and retrieving its investment (or other) values. Another question/solution would be just to re-do the db structure like that: class Person: role = models.CharField(choices=['husband', 'wife']) investment = models.IntegerField() ... # bunch of other fields here relevant for queries class Family: husband = models.OneToOneField(to=Person, related_name='husband_family') wife = models.OneToOneField(to=Person, related_name='wife_family') That would solve the issue above, but it would create other problems (for instance this ugly way of to 1to1 fields pointing to Person model. What would you recommend? -
django.db.utils.OperationalError: FATAL: password authentication failed for user "postgres "
When i try to use database name,username, and password from environment variable using django-environ it shows me an error likes : "django.db.utils.OperationalError: FATAL: password authentication failed for user "postgres "" My settings.py : DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": env("DATABASE_NAME"), "USER": env("DATABASE_USER"), "PASSWORD": env("DATABASE_PASSWORD"), "HOST": "localhost", "PORT": "5432", } } N.B: But it works well when i use without environment variable. errors: File "C:\Users\Dell\.virtualenvs\Blog-1bn9_xtV\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\Dell\.virtualenvs\Blog-1bn9_xtV\lib\site-packages\django\db\backends\base\base.py", line 197, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\Dell\.virtualenvs\Blog-1bn9_xtV\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\Dell\.virtualenvs\Blog-1bn9_xtV\lib\site-packages\django\db\backends\postgresql\base.py", line 185, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\Dell\.virtualenvs\Blog-1bn9_xtV\lib\site-packages\psycopg2\__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: FATAL: password authentication failed for user "postgres " -
how to become good at programming and problem solving in a month? [closed]
can anyone please list the topics of data structures and algorithms which I can go through to become good with problem-solving as I have my interview s from next month for fresher Django developer . and I am yet not good with algorithms. please help! -
what is diffrence between admin pannel and app in django
i have a dummy project,i have been told to create the admin pannel of this project, i am unable to get what is the admin pannel and what is an app in a django project. Can someone please expalin this. -
Redis timeout on celery chord callback
I think I'm having an issue with chord callbacks in celery. I have searched within SO but could not find any useful information. Let me show a bit of code and then explain the issue. I have the following celery execution: execution_chord = chord( [ tasks.run_web_scanners.si(information).set(queue='fast_queue'), tasks.run_ip_scans.si(information).set(queue='slow_queue') ], body=tasks.on_demand_scan_finished.si().set(queue='fast_queue'), immutable = True ) execution_chord.apply_async(queue='fast_queue', interval=100) Now, run_web_scanners and run_ip_scans both have chords inside them this chords are NOT called In async mode. Mainly because the idea of a thread spawning more threads is a recipe for disaster. Here is a snippet of run_web_scanners for example. @shared_task def run_web_scanners(scan_information): # Deep copy just in case web_information = copy.deepcopy(scan_information) execution_chord =chord( [ # Fast_scans header_scan_task.s(web_information).set(queue='fast_queue') ], body=web_security_scan_finished.si().set(queue='fast_queue'), immutable=True)() return The scans run just fine (These scans have a body function that indicates the success) but most of the time I get a timeout error when the callback on_demand_scan_finished is called. Any idea on what could be going on? run_web_scanners and run_ip_scans are "built" the same way as the presented chord and the body function works fine everytime. Here is the error message I get [2020-06-22 18:12:07,397: ERROR/ForkPoolWorker-3] Chord '79af732d-8590-4a1a-bc3b-c76ad8edb742' raised: timeout() ... ... /lib/python3.7/site-packages/kombu/transport/redis.py", line 382, in get raise Empty() _queue.Empty Note: … -
Django: error while trying to access ManyToMany field
I'm trying to create a twitter like application as a practice project, and following this video tutorial. I've created following models in my app. class Profile(models.Model): user = models.OneToOneField(to=User, on_delete=models.CASCADE) bio = models.CharField(max_length=160, blank=True) profile_photo = models.ImageField(blank=True, null=True) followers = models.ManyToManyField("self", through="Relationship", related_name="follow_to", symmetrical=False, blank=True) class Relationship(models.Model): user_followed = models.ForeignKey("User", related_name="followed", on_delete=models.CASCADE) followed_by = models.ForeignKey("Profile", related_name="follower", on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now=True) The migrations ran successfully. After this for testing, I created two users (user1 and user2) with their respective profiles and made user2 to follow user1. Here's the code for that- Relationship.objects.create(user_followed=user1,followed_by=user2.profile) This relationship was successfully created. I try the following code to try to get followers of user1- user1.profile.followers.all() But above code is giving following errors- Traceback (most recent call last): File "<console>", line 1, in <module> File "/Users/mayank/.pyenv/versions/dwitter/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py", line 535, in __get__ return self.related_manager_cls(instance) File "/Users/mayank/.pyenv/versions/dwitter/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py", line 821, in __init__ self.target_field_name = rel.field.m2m_reverse_field_name() File "/Users/mayank/.pyenv/versions/dwitter/lib/python3.8/site-packages/django/db/models/fields/related.py", line 1554, in _get_m2m_reverse_attr return getattr(self, cache_attr) AttributeError: 'ManyToManyField' object has no attribute '_m2m_reverse_name_cache' I tried following the method mentioned here, but it is also giving the same error. I'm not sure where have I committed a mistake. I would be thankful if someone can correct me. -
Django update the user's rate
im trying to implement rate system where user can rate (for example such person) only once, but he can change his rate. class Rate(models.Model): class Meta: unique_together = (('sender', 'person'),) choice = models.IntegerField(null=False, blank=False, choices=RATE_CHOICES) sender = models.ForeignKey(User, on_delete=models.CASCADE) person = models.ForeignKey(Person, on_delete=models.CASCADE, null=True) I found something like unique_together and it works - user can rate only once, but I have a problem with changing it. def form_valid(self, form): vote, created = Rate.objects.get_or_create( sender=self.request.user, person=self.get_object(), choice=form.cleaned_data['choice']) if not created: Rate.objects.filter(sender=self.request.user, person=self.get_object()).update(choice=form.cleaned_data['choice']) return super(PersonDetailView, self).form_valid(form) else: return super(PersonDetailView, self).form_valid(form) I tried something like above but still getting UNIQUE constraint failed: main_rate.sender_id, main_rate.person_id -
DISTINCT ON field is not available on MySQL. Which equivalent do you use?
Let's say I've got a model: class Person(models.Model): id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) I'd like, by searching the first letter of a first_name, to get a list of Person. But each one must have a different last_name. For example: searching M... in the list of: Frank Edmond Marc Thomas Matthew Ronald Matthew Smith Matthew Thomas Richard Thomas will give you Marc Thomas Matthew Ronald Matthew Smith In short, how to translate in MySQL: Person.objects.filter(first_name__startswith='M').distinct('last_name') -
Django: Sharing the same queue in different modules
Before all, I have seen this question and this other question, none of them helped. I'm working on django, and i have a thread running as a daemon, it keeps waiting for data to be put in a queue, to work on it. package1/workers.py from package1 import queue class Worker(Thread): def run(self) -> None: print("worker started") while True: print("before blocking") print(queue) meta_data = queue.get() print("data received") queue.task_done() both of the queue and the worker thread are declared in the init.py, like so: package1/init.py import os from queue import Queue queue = Queue() def prepare_workers(): from package1.workers import Worker worker = Worker(daemon=True) worker.start() if os.environ.get('RUN_MAIN', None) != 'true': # a work around to avoid the appRegistery not ready yet exception... prepare_workers() and in the models package, i'm receiving a signal to put data in the queue, like so: package1/models.py @receiver(post_save, sender=AModel) def a_model_created_signal(sender, instance, created, raw, **kwargs): if created and not raw: from package1 import queue meta_data = some_data_here print(queue) queue.put(meta_data) print('data put') this is the console output: (venv) C:\path_to_project>py manage.py runserver 0.0.0.0:80 worker started before blocking <queue.Queue object at 0x000001C7A0C80160> Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). June 23, 2020 - … -
Use DynamoDB with Django auth
I want to use Django auth with DynamoDB. Currently i couldn't find any thing related to this. There are Dynamorm and pynamoDB, but how can i use them for authentication in Django ? Or there are other ways to do authentication other than auth ? -
How i get userprofileimage in userhome template in django
How i show userprofile image in userhhome template through below code can you tell me how i get userobject .............................................................................................................................................................................................................. views.py # Create your views here. def user_home(request): # messages.success(request,'login successfully') user = Following.objects.get(user=request.user) #following_obj of user print(request.user) followed_users = user.followed.all() posts = Post.objects.filter(user__in = followed_users).order_by('-pk') | Post.objects.filter(user = request.user).order_by('-pk') liked_ = [i for i in posts if Like.objects.filter(post = i, user = request.user)] userprofile=Profile.objects.get(user=request.user) data = { 'posts':posts, "liked_post":liked_, "user":userprofile } return render(request,'userview/userhome.html' ,data) ######for userprofile def userprofile(request,username): user=User.objects.filter(username=username) if user: user=user[0] profile=Profile.objects.get(user=user) post=getPost(user) bio=profile.bio conn=profile.connection user_img=profile.userImage is_following=Following.objects.filter(user=request.user,followed =user) following_obj = Following.objects.get(user = user) follower, following = following_obj.follower.count(),following_obj.followed.count() data={ 'user_obj':user, 'bio':bio, 'conn':conn, 'follower':follower, 'following':following, 'userImg':user_img, 'posts':post, 'connection':is_following } print(data) return render(request,'userview/userpprofile.html', data) # return render(request,'userview/userProfile.html') else: return HttpResponse(" 404 No Such User exist") userhome.html <div class="card a mt-5"> <h5 class="card-header"><img src="{{user_obj.userImg.url}}" class="align-self-start img-rounde mr-2 img-circl tm-border userImage" alt="..."> <div class="card-body "> -
Passing multipart form data from python to django server with both file and data
I have a Django server and a react frontend application. I hava an endpoint that receives both data and file object. The javascript version of the api client is working fine and it looks something like this. const address = `${baseAddress}/${endpoint}`; const multipartOptions = { headers: { 'Content-Type': 'multipart/form-data', 'Content-Disposition': `attachment; filename=${filename}`, 'X-CSRFToken': getCSRFToken(), }, }; const formData = new FormData(); formData.append('file', file); const json = JSON.stringify(metadata); const blob = new Blob([json], { type: 'application/json', }); formData.append('metadata', blob); return axios.post(address, formData, multipartOptions); So as you can see I am using a blob to add metadata to my form data and passing it to the server. Printing the request.data in the server gives me something like this. <QueryDict: {'file': [<InMemoryUploadedFile: admin_12183.zip (application/zip)>], 'metadata': [<InMemoryUploadedFile: blob (application/json)>]}> So I can access both request.data.get('file') and request.data.get('metadata') on my django server. Now I have to do something similar in python. I tried using requests to get the stuff right, but I don't get two separate keys in the QueryDict. The python code looks like this. with open("file.zip", "rb") as fp: with open("metadata.json", "rb") as meta: file_headers = { **headers, 'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundaryjzAXwA7GGcenPlPk', } data = { "file": "", } files = { 'file': ("file.zip", … -
Django best practise for exactly two Child objects "OneToTwo-Relationship"
I want to have a User and a Deal Model. A Deal has exactly two Users, not more or less. What ist the best way to achieve this? I found two ways. Example 1: Deal.users as ManyToManyField class Deal(models.Model): users = models.ManyToManyField(AUTH_USER_MODEL) Pro: Logically correct because each user is equal Contra: Needs either ModelForm or a receiver function to validate "len(users)==2" Example 2: Deal.user1 and Deal.user2 each as ForeignKey class Deal(models.Model): user1 = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE) user2 = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE) Pro: Validation at database level Easier to work with in many circumstances Contra: Need to add properties or such if i want to access them equally with Deal.users instead of choosing them explicit (Deal.user1, Deal.user2) What would you consider as best practise? I would be also happy about any further ways. -
Django passing in isbn10 to url
I seem to be unable to pass in isbn10 numbers in to the Django. <a href="{% url 'books-to-detail' fic.isbn %}"> <section class="slideshow-fiction"> <img src="{{ fic.image }}" alt="" /> <p>{{ fic.title|truncatewords:4 }}</p> <!-- <p>{{ fic.description }}</p> --> <p>{{ fic.author }}</p> <!-- <p>{{ fic.isbn }}</p> --> </section> </a> Examples of the numbers are 059318808X and 0316539562. I've tried to use re_path and regex however if i get one number to pass the other does not. This is one of the paths that I've tried but 0316539562 does not pass. re_path( r"^redirect/books/(?P<isbn>[0-9]*[-| ][0-9]*[-| ][0-9]*[-| ][0-9]*[-| ][0-9]*\w)/$", redirect_books_to_detail, name="books-to-detail", ), The error here Trying this url path re_path( r"^redirect/books/(?P<isbn>[\w\+%_& ]+)/$", redirect_books_to_detail, name="books-to-detail", ), I now get an error that there is seen here