Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why in Django-rest-framework it gives authentication failed response
I have someViews like below: class SomeView(generics.ListAPIView): serializer_class = SomeSerializer permission_classes = [AllowAny] and in settings.py: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.AllowAny', ), 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ), 'DEFAULT_PARSER_CLASSES': ( 'rest_framework.parsers.JSONParser', 'rest_framework.parsers.MultiPartParser', 'rest_framework.parsers.FileUploadParser', 'rest_framework.parsers.FormParser', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',), 'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.NamespaceVersioning', } And When I request without any Authorization header it works fine. But When I add Bearer Authorization header it response "detail": "Given token not valid for any token type", "code": "token_not_valid", I gave permission_classes=[AllowAny]. Why? I thought there is no difference between sending or not sending tokens. Because I set permission_class=[AllowAny]. In ASP.NET there is no like this problems. In ASP.NET If I set AllowAny permission this endpoint open for everyone regardless of whether you send a Token or not. -
Dynamic Length Form handling and Data Collection in Django
I have a form in which the number of input fields keeps changing and depends on a parameter that I pass. This means that I can't go to forms.py and create a Form class because that requires me to define the input parameters beforehand. Here is how I am defining the form. <!-- Table to Display the original sentence and take the input of the translation --> <table class="table"> <thead class="thead-dark"> <tr> <th scope="col">#</th> <th scope="col">Original Sentence</th> <th scope="col">Translation</th> </tr> </thead> <form name="translated-text-form" class="form-control" action="" method="post"> {% csrf_token %} <tbody> {% for sentence in sentences %} <tr> <th scope="row">{{ forloop.counter }}</th> <td>{{ sentence.original_sentence }}</td> <td><input type="text" name="translated-{{sentence.id}}" value="{{ sentence.translated_sentence }}" /></td> </tr> {% endfor %} <tr> <td colspan="2"> <br> <p style="text-align: center;"> <input class="btn btn-secondary" type="submit" value="Save Translations"/> </p> </td> </tr> </tbody> </form> </table> This is the form output The user will add some text in the rightmost column and I want to save that text with a particular sentence.id in my Sentence model. This is what my model looks like class Sentence(models.Model): """ Model which holds the details of a sentence. A sentence is a part of a Wikipedia article which is tokenized. Fields: project_id: The ID of the … -
Django url reversing error - reverse with keyword arguments not found
The error I am getting This method is not working. It should be working without using reverse function. The URL pattern: urlpatterns = [ path('sectiondetails/<str:pk>/', views.getSectionEvents, name='sectionevents'), path('studentdetails/<str:pk>/', views.studentdetails, name='studentdetails'), path('studentpersonalevents/<str:pk>/', views.studentpersonalevents, name='studentevents') ] Html link: <li class="nav-item"> <a class="nav-link" href="{% url 'sectionevents' pk=section.id %}">Class Events</a></li> <li class="nav-item"> <a class="nav-link" href="{% url 'studentevents' pk=student.id %}">Personal Events</a></li> The error I get: Reverse for 'studentevents' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['studentpersonalevents/(?P[^/]+)/\Z'] -
Why in Django there is difference between json and formdata
I have someview like below def SomeView(request): someArrayData = request.data.getlist('something', None) And I am using Postman for testing my endpoints. When I send array with formdata request.data.getlist works. But when I send array with raw data type application/json getlist not works. Instead of getlist I must use request.data.get. But in ASP.NET there is no difference. I could send via formdata or application/json both works. -
Can I get some help, my css static file isn't loading as I expected?
I'm following a tutorial on building Django Ecommerce Website and apparently I might have messed up somewhere I cant quite figure out. The main.css file seems to be loading incorrectly. Please help. I had encountered it before but found a solution. Unfortunately it stopped loading main.css correctly This is the main.css body{ background-color: hsl(0, 0%, 98%); } h1,h2,h3,h4,h5,h6{ color:hsl(0, 0%, 30%); } .box-element{ box-shadow:hsl(0, 0%, 80%) 0 0 16px; background-color: #fff; border-radius: 4px; padding: 10px; } .thumbnail{ width: 100%; height: 200px; -webkit-box-shadow: -1px -3px 5px -2px rgba(214,214,214,1); -moz-box-shadow: -1px -3px 5px -2px rgba(214,214,214,1); box-shadow: -1px -3px 5px -2px rgba(214,214,214,1); } .product{ border-radius: 0 0 4px 4px; } .bg-dark{ background-color: #4f868c!important; } #cart-icon{ width:25px; display: inline-block; margin-left: 15px; } #cart-total{ display: block; text-align: center; color:#fff; background-color: red; width: 20px; height: 25px; border-radius: 50%; font-size: 14px; } .col-lg-4, .col-lg-6, .col-lg-8, .col-lg-12{ margin-top: 10px; } .btn{ border-radius: 0; } .row-image{ width: 100px; } .form-field{ width:250px; display: inline-block; padding: 5px; } .cart-row{ display: flex; align-items: flex-stretch; padding-bottom: 10px; margin-bottom: 10px; border-bottom: 1px solid #ececec; } .quantity{ display: inline-block; font-weight: 700; padding-right:10px; } .chg-quantity{ width: 12px; cursor: pointer; display: block; margin-top: 5px; transition:.1s; } .chg-quantity:hover{ opacity: .6; } .hidden{ display: none!important; } This is settings.py … -
starting Django project using cron
I have a Django project which I want to start every time the device reboots. I can start the Django application manually using the following 4 commands cd /home/pi/reg-sign source djenv/bin/activate cd /home/pi/reg-sign/mysite python manage.py runserver 192.168.4.1:8000 But I cannot get this working in a crontab line. So far I have; @reboot cd /home/pi/reg-sign && /home/pi/reg-sign/djenv/bin/python /home/pi/reg-sign/mysite/manage.py python runserver 192.168.4.1:8000 however this does not start the server. Any help would be much appreciated. Many thanks, -
How to fix CORS 405 on next/vercel frontend w django/heroku backend?
I've got a next app running on a Django backend hosted on Heroku. I recently converted it from pure React to Next, and deployed it on Vercel (earlier Firebase hosting).. I've tried everything I can think of but I can't resolve the CORS 405 I'm getting. I'm still don't have a good grip on CORS in general, but I've read all I could find on it.. My Django/Py skills are VERY novice.. is there something obvious I'm missing here? Or do any of you have a clue on how I should proceed to resolve this? // Headers from console/network on attempted axios get(it works locally, and has been working before I tried to deploy to Vercel): // General: // Request URL: herokuAppUrl.com // Request Method: GET // Status Code: 405 // Referrer Policy: strict-origin-when-cross-origin // Response headers: // Allow: DELETE // Connection: keep-alive // Content-Length: 19 // Content-Type: text/plain; charset=utf-8 // Date: Tue, 26 Apr 2022 15:48:53 GMT // X-Content-Type-Options: nosniff // Request headers: // Accept: application/json, text/plain, */* // Accept-Encoding: gzip, deflate, br // Accept-Language: en-GB,en-US;q=0.9,en;q=0.8 // Connection: keep-alive // Host: git.heroku.com // Origin: https://my.vercel.app // Referer: https://my.vercel.app/ // Sec-Fetch-Dest: empty // Sec-Fetch-Mode: cors // Sec-Fetch-Site: cross-site // Sec-GPC: … -
Creating a Django Model for a recipe
I am trying to create a Django model for a recipe database. I'm having trouble writing a model that will account for a variable amount of ingredients(not every recipe has the same amount of ingredients). Here is what I have so far: class Recipe(models.Model): '''A recipe class to input new recipes''' recipe = models.CharField(max_length=50) ingredient = models.ForeignKey(Ingredient, null=True, on_delete=models.SET_NULL) quantity = models.CharField(max_length=1) cuisine = models.ForeignKey(Cuisine, null=True, on_delete=models.SET_NULL) def __str__(self): return self.recipe I'm stuck trying to figure out how to associate one recipe with multiple ingredients in the database. Right now, I've only managed to create one ingredient per recipe. The foreign keys are for other created classes that describe individual ingredients and cuisines. -
How to make multi-tenant apps in django?
Info: I want to make multi-tenant app in django like facebook. facebook allow a single user create multple pages. In my case: Each page is a tenant. The user is creating a schema while the user creating a page. I am using django-tenants to make multi-tenant app in django. django-tenants Is working with subdomain (pageName.example.com). But i want to access tenant as (example.com/pageName/) and i want to allowed the user permission to Edit the page(tenant) which users are registered in public schema user table. -
Django: No module named 'base.context_processors.defaultdjango'; 'base.context_processors' is not a package
i am trying to add a context processor in django setting.py file, and this is the line i am adding TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'base.context_processors.default' # this line here is what i added 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] but it keeps showing this No module named 'base.context_processors.defaultdjango'; 'base.context_processors' is not a package error. When i comment that line out the error goes away but i keep getting this error No module named 'base.context_processors.defaultdjango'; 'base.context_processors' is not a package -
use django "include" inside a js function
I am doing a search page in which parameters are sent by ajax and then upon reception of the queryset I rebuild my cards. The whole thing is classic and working ok, here is a simplified version of the thing. Lots of lines killed or modified since it is not really the subject of the post let getobject = async (value,url) => { var res2 = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', "X-CSRFToken": getCookie("csrftoken"), }, body: JSON.stringify({ value: value, }) }) let data2 = await res2.json(); videoitems.innerHTML = '' modalbin.innerHTML = '' data2["data"].forEach(async item => { if (item.ext == '.mp4') { const dynamicreation = async () => { let dyncontent3 = await createnewcard(item) let placing = await videoitems.appendChild(dyncontent3); } const nooncares2 = await dynamicreation() } else if (item.ext == ".pdf") { const dynamicreation2 = async () => { let dyncontent4 = await createnewcard(item) let placing2 = await videoitems.appendChild(dyncontent4); } const nooncares4 = dynamicreation2() } }) } the createnewcard function var createnewcard = item => { var dyncontent = document.createElement("div"); dyncontent.innerHTML = `<div class="m-2 extralarge-modal video${item.id}"> <div data-reco="${item.id}" class="extralarge-modal bg-white rounded-lg border border-gray-200 shadow-md dark:bg-gray-800 dark:border-gray-700"> <div class="p-5"> <p class="mb-3 font-normal text-gray-700 dark:text-gray-400"> ${item.title} </p> </div> … -
Django redirect not working in my view function
From my crop crop_prediction view I am trying to redirect it to 'http://localhost:8000/Efarma/crop_detail/' page but instead of this it render the current html page ,the home page which is also the starting page of this website. Some error is showing in my console '[26/Apr/2022 22:31:29,457] - Broken pipe from ('127.0.0.1', 62868)' but I have no idea what is it. To go to crop_detail page i have to manually put it in search box. urls.py:- from django.urls import path, include from .import views urlpatterns = [ path('', views.home), path('crop_prediction/', views.crop_prediction), path('crop_detail/', views.crop_info) ] views.py:- def home(request): return render(request, 'Efarma/index.html') def crop_prediction(request): global resultJson, firebase print(request.POST) print(request.GET) if request.method == "POST": N = float(request.POST.get("nitrogen")) P = float(request.POST.get("phosphorus")) K = float(request.POST.get("potassium")) ph = float(request.POST.get("ph")) rainfall = float(request.POST.get("rainfall")) city = request.POST.get("city") if weather_fetch(city) != None: temperature, humidity = weather_fetch(city) data = np.array([[N, P, K, temperature, humidity, ph, rainfall]]) print(temperature, humidity, "--------kkk-------") my_prediction = pickle.load( open('CropRecommendation\model\model.pkl', 'rb')) final_prediction = my_prediction.predict(data) value = final_prediction[0] firebase = firebase.FirebaseApplication( 'https://e-farma-5dc42-default-rtdb.firebaseio.com/') predicted_crop_info = firebase.get(value, None) predicted_crop_info["crop"] = value resultJson = dumps(predicted_crop_info) return redirect('http://localhost:8000/Efarma/crop_detail/') else: return redirect('http://localhost:8000/Efarma/crop_detail/') def crop_info(request): print(resultJson) return render(request, "Efarma/crop_detail.html", {"result": resultJson}) error:- -
Running multiple independent docker containers for web services
I'm trying to run a few services on my server, by using separate docker image for each service: nginx - with a configuration for all available services below and access to the files on the server - should be always running Wordpress - for hosting a Wordpress web page (and probably PHP?) - will be almost always running on the server Django - for hosting a Django web page - will be sometimes running only Flask RESTful API - maybe in the future will be added I'm using docker-compose to configure nginx and django app, but I cannot run only nginx container without django (I've tried to use links and depends_on in docker-compose.yml). So long story short - I want to be able to add, run and stop containers for web services independently. -
In Django, is there a way you can limit a user to registering for an event only once?
I'm a newbie to Django, trying to build site to allow people to register for football matches. At the moment, a user can register multiple times for the same match, which is obviously not ideal! Is there a way that I can identify if the currently logged in user has already registered, and then replace the register button with a message telling them that they have already registered? I guess I need some kind of Boolean value in my EventDetail view, and then I can make a conditional statement in the template, but I'm unsure as to how to implement this. I hope this question is clear, it's my very first post! views.py: class EventDetail(View): def get(self, request, id, *args, **kwargs): event = get_object_or_404(Event, pk=id) registrations = Registration.objects.filter(event=event) total_participants = 0 for person in registrations: total_participants += 1 if person.guest: total_participants += 1 remaining_spaces = event.max_participants - total_participants template = "event_detail.html" context = { "event": event, "total_participants": total_participants, "registrations": registrations, "remaining_spaces": remaining_spaces, } return render(request, template, context) template {% extends "base.html" %} {% block content %} <p>{{ event.title }}</p> <p>{{ total_participants }} / {{ event.max_participants }} ({{ remaining_spaces }} spot{{ remaining_spaces|pluralize }} remaining!)</p> {% if total_participants < event.max_participants %} <a … -
Django - How to pass current url parameters if any to a new url after pressing a button
My current page has a filter that the user can fill if wanted. In the same page there is a button that redirects the user to a new url that downloads a file. My question is: How i can pass the first page url parameters and pass them to the new url/view? If i add them in my url and they are not filled then i have an error. -
django.templates.exceptions.TemplateDoesNotExist
Even in the settings.py, I have added the INSTALLED_APPS section but still, it is not working. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', # this is for the authentication 'django.contrib.contenttypes', # this tells about the MIME type 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # it help us to host the static files 'HelloWorld', ]` TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates') ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
How to use swagger_auto_schema decorator in django if the class based view does not have any serializer_class?
I have a class based view as: class DetailView(GenericAPIView): @swagger_auto_schema(responses={201: 'Created'}) @authorize(CustomPermission) def post(self, *args, **kwargs) -> Response: // code..... return Response(status=HTTPStatus.CREATED) First: The use of swagger_auto_schema without any serializer is throwing error as: AssertionError: DetailView should either include a serializer_class attribute, or override the get_serializer_class() method. And I don't want to use serializer for this endpoint as I don't need that. But the swagger_auto_schema keeps on throwing this error. I want to know whether there is any way to avoid the use of serializer and get the swagger documentation of this endpoint. Second: I also want to add authorisation of this endpoint in the doc. I know there is a security field in swagger_auto_schema, but don't know how to make it to use for my custom permission class ie CustomPermission Thanks. -
when I type python manage.py runserver it gives me this error __init__() takes 1 positional argument but 4 were given
I am working on a django project having django 2.1 version. now I want to run it successfully on local server. but when I type python manage.py runserver, it gives me an error log which is given below. can anyone can guide me how to run it successfully? what part of the code should I look for to fix it? Exception ignored in thread started by: <function check_errors.<locals>.wrapper at 0x0000013BF20405E0> Traceback (most recent call last): File "C:\Users\Dell\Documents\Satkardeep Django\wowtasks.com_django\venv\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\Dell\Documents\Satkardeep Django\wowtasks.com_django\venv\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\Dell\Documents\Satkardeep Django\wowtasks.com_django\venv\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\Users\Dell\Documents\Satkardeep Django\wowtasks.com_django\venv\lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Users\Dell\Documents\Satkardeep Django\wowtasks.com_django\venv\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\Dell\Documents\Satkardeep Django\wowtasks.com_django\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Dell\Documents\Satkardeep Django\wowtasks.com_django\venv\lib\site-packages\django\apps\registry.py", line 120, in populate app_config.ready() File "C:\Users\Dell\Documents\Satkardeep Django\wowtasks.com_django\venv\lib\site-packages\django\contrib\admin\apps.py", line 24, in ready self.module.autodiscover() File "C:\Users\Dell\Documents\Satkardeep Django\wowtasks.com_django\venv\lib\site-packages\django\contrib\admin\__init__.py", line 26, in autodiscover autodiscover_modules('admin', register_to=site) File "C:\Users\Dell\Documents\Satkardeep Django\wowtasks.com_django\venv\lib\site-packages\django\utils\module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked … -
Why DAO is not used in most python web application like flask, django and sanic?
I've worked in lots of python web project. I also used flask, django and sanic to develop web applications and restful api services. Recently I heard DAO from my friend who writes both java and python code. Obviously DAO has its advantages but why I see no use of DAO (but most use ORM directly) in my past python web projects and similar projects in github? -
Dynamic URL's with multible layers
Im making a website using Django, where im making dynamic URLs. However i'm fairly new to programming and haven't been able to find out how to make dynamic URLs with more than 1 parametre. I'm making a site called "kartotek", which are user specific defined by the varible "kl_id", and therefore has a dynamic URL with following path: path('kartotek/<str:kl_id>/', views.kartotek, name="kartotek"), On this page, is there a button with which you choose a patient and come to another URL called "reg" with the following path: path('reg/<str:kl_id>/<str:pt_id>/', views.reg, name="reg"), I have the following code in views.py: def kartotek(request, kl_id): kliniknavn = Klinik.objects.get(navn=kl_id) E_patient = kliniknavn.patient_set.all() context = { 'kliniknavn':kliniknavn, 'E_patient':E_patient} return render(request,'DentHelp/kartotek.html', context ) def reg(request ,kl_id , pt_id): kliniknavn = Klinik.objects.get(navn=kl_id) ptid = Patient.objects.get(id_nr=pt_id) context = {'ptid':ptid, 'kliniknavn':kliniknavn} return render(request,'DentHelp/reg.html', context) I think the problem is the template code, which I'm kinda confused how to make, I was trying this: {% for patient in E_patient %} <a href="{% url 'reg' klinik.navn, patient.id_nr %}" class="btn btn-primary">Vælg patient</a> {% endfor %} Any have an advise? -
Only view detailpage if user is none
I have two models, an user model and a key model. Where the key model is a foreignkey in the user model. I want to make it so the detailpage of each key is only accessible if the particular key is not connected to any user. I have made a test_func with the UserPassesTestMixin but I am not able to write the requirement correctly. This is my view class KeyView(LoginRequiredMixin, UserPassesTestMixin, DetailView): model = Key template_name = 'base/key.html' def test_func(self): user = self.request.user if user.is_teacher == True and Key.objects.filter(user__isnull=True): return True return False -
Auto generate and save data to SlugField
Hello I have a function to auto generate data for my SlugField but i dont know how to implement a save method to execute it. Ive tried calling the function from the save method but it raises an error of 'instance not defined'. Any suggestions will help. Thanks. def ran_str_gen(size=6, chars=string.ascii_letters + string.digits): return ''.join(secrets.choice(chars) for s in range(size)) def slug_gen(instance, new_slug=None): if new_slug is not None: slug=new_slug else: slug = slugify(instance.title) op = instance.__class__ qs_exists = op.objects.filter(slug=slug).exists() if not qs_exists: new_slug = '{slug}-{ranstr}'.format(slug=slug, ranstr=ran_str_gen()) return slug_gen(instance, new_slug=new_slug) return slug class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() slug = models.SlugField() def save(self, *args, **kwargs): slug_gen() -
Django: how to extends a view to another view without copy and paste?
i have a view that shows my navigation bar, i am adding the navgigation bar dynamically from the database, but th problem is that i have to add that same piece of code to all my views for the navigation text to show up and that is making my code so length, is there a way to automatically extends the peice of code that is getting my navigation to all the views, so when i go to another page like the about page or contact, or profile page i can still see the navigation bar. Now only when i see the navigation bar is when i go to the index.html views.py def index(request): designcatlist = DesignCategory.objects.all() prglangcatlist = ProgrammingLanguagesCategory.objects.all() howtocatlist = HowToCategory.objects.all() context = { ... } def about_page(request): designcatlist = DesignCategory.objects.all() prglangcatlist = ProgrammingLanguagesCategory.objects.all() howtocatlist = HowToCategory.objects.all() context = { ... } def contact_page(request): designcatlist = DesignCategory.objects.all() prglangcatlist = ProgrammingLanguagesCategory.objects.all() howtocatlist = HowToCategory.objects.all() context = { ... } def profile_page(request): designcatlist = DesignCategory.objects.all() prglangcatlist = ProgrammingLanguagesCategory.objects.all() howtocatlist = HowToCategory.objects.all() context = { ... } NOTE as you can see in the code above, i need to add the same piece of code for the naviation to show up on … -
How to redirect users to a mobile app in Django view?
I have a Django web application and I'm trying to redirect users to my mobile app in one of the views. def magic_link(request, token): return redirect(f"{settings.FRONTEND_URL}/magic_link/{token}") This redirect link is like: appname://magic_link/token. However, I'm getting the following error. DisallowedRedirect at /magic_link/{token}/ Unsafe redirect to URL with protocol 'appname' How can I fix this issue and redirect users to the mobile app in Django view? -
Reverse for 'password_reset_confirm' not found
I have django.urls.exceptions.NoReverseMatch: Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. error after I put in email address into password_reset.html and click send button. Why is it looking for password_reset_confirmat this point in the first place? password_reset.html {% extends "base.html" %} {% block content %} <form method="post"> {% csrf_token %} <h1>Forgot your password?</h1> <p>Enter your email address below, and we'll email instructions for setting a new one.</p> {{ form.as_p }} <button name="submit" class="btn">Send me instructions</button> </form> {% endblock content %} urls.py from django.urls import path, reverse_lazy from django.contrib.auth import views as auth_views from .forms import UserLoginForm from . import views app_name = "users" urlpatterns = [ path('login/', auth_views.LoginView.as_view( template_name='users/login.html', authentication_form=UserLoginForm), name="login"), path('logout/', auth_views.LogoutView.as_view(next_page='index'), name="logout"), path('register/', views.register, name="register"), path('password_reset_done/', auth_views.PasswordResetDoneView.as_view( template_name="users/password_reset_done.html"), name="password_reset_done"), path('reset_password/', auth_views.PasswordResetView.as_view( template_name="users/password_reset.html", success_url=reverse_lazy('users:password_reset_done')), name="reset_password"), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view( template_name="users/reset_password_complete.html"), name="password_reset_complete"), path('reset/<uidb64>/<token>', auth_views.PasswordResetConfirmView.as_view( success_url=reverse_lazy('users:password_reset_complete')), name="password_reset_confirm"), path('activate/<uidb64>/<token>', views.activate, name="activate"), ]