Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF spectacular creates tags, can't figure out where to remove(
class EquipmentViewSet(ReadOnlyModelViewSet): queryset = Equipment.objects.all() serializer_class = EquipmentSerializer @extend_schema( summary='Получение списка всех объектов класса "Оборудование"', tags=['Equipment'], description=""" Получение списка всех оборудования. В ответе будет получен полный список объектов класса "Оборудование". """, request=EquipmentSerializer, responses=equipment_status_codes ) def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) In the swager, in addition to tags=['Equipment'], tag = v1 is created where /api/v1/equipment/{id}/ is located. I tried everything, I want to cry, extend_schema_view doesn't help in any way -
How to get rid of this extra gap in my Django website?
I deployed this website, which can be seen by pasting the URL in the browser. RFP Website If you see the homepage, you can see that on the right, it seems to scroll infinitely and I am getting a huge gap, which is not in other pages. How to get rid of this? -
How can I properly Query data from a django model without
im trying to create a simple django app for buying and selling shares but im having trouble querying my data properly specifically the amount of available shares. These are my models: from django.db import models from accounts.models import CustomUser class Share(models.Model): name = models.CharField(max_length=100) price = models.DecimalField(max_digits=10, decimal_places=2) quantity_available = models.PositiveIntegerField() def __str__(self): return self.name class Transaction(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) share = models.ForeignKey(Share, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() total_price = models.DecimalField(max_digits=10, decimal_places=2) transaction_date = models.DateTimeField(auto_now_add=True) is_purchase = models.BooleanField() then these are my views: from django.shortcuts import render, redirect from .models import Share, Transaction from .forms import BuyShareForm, SellShareForm def buy_share(request): share = Share.objects.filter(quantity_available__gt=100) form = BuyShareForm(request.POST or None) if request.method == 'POST' and form.is_valid(): quantity = form.cleaned_data['quantity'] if quantity <= share.quantity_available: transaction = Transaction(user=request.user, share=share, quantity=quantity, total_price=quantity * share.price, is_purchase=True) transaction.save() share.quantity_available -= quantity share.save() return redirect('shares:buy-success') else: form.add_error('quantity', 'Insufficient shares available') context = { 'share': share, 'form': form, } return render(request, 'shares/buy_share.html', context) def sell_share(request): share = Share.objects.all() form = SellShareForm(request.POST or None) if request.method == 'POST' and form.is_valid(): quantity = form.cleaned_data['quantity'] transaction = Transaction(user=request.user, share=share, quantity=quantity, total_price=quantity * share.price, is_purchase=False) transaction.save() share.quantity_available += quantity share.save() return redirect('shares:sell_success') return render(request, 'shares:sell_share.html', {'form': form}) when i try to get the … -
Cannot redirect with forwardauth Traefik middleware
How to actually switch(redirect) to another page (login page) with Traefik ForwardAuth ? I'm using the following docker labels: 'traefik.http.routers.my-route.rule=Host("main.int")' 'traefik.http.routers.my-route.entrypoints=https443' 'traefik.http.routers.my-route.tls=true' 'traefik.http.routers.my-route.middlewares=my-test-auth@docker 'traefik.http.middlewares.my-test-auth.forwardauth.address=https://auth.page.int/login/' 'traefik.http.middlewares.my-test-auth.forwardauth.tls.insecureSkipVerify=true' Traefik logs shows that is accessing the auth.page.int/login page: GET /accounts/login/ HTTP/2.0" 200 3459 but browser stays on the main page. BTW redirect works with RedirectRegex middleware for the same example. Documentation: https://doc.traefik.io/traefik/middlewares/overview/ -
React axios get parameter is undefined
I want to get some data from an api with a parameter current user's username. useEffect(()=>{ console.log(currentUser[0]?.id.toString()) if (currentUser) { console.log(currentUser[0]?.id.toString()) axios.get(`http://127.0.0.1:8000/get_chat2/?user1=${currentUser[0]?.id.toString()}&user2=`).then(res=>{ setUsers(res.data) console.log(res.data) }) },[currentUser]) When I print currentUser[0]?.id.toString() I get user's id but when I send the request it is undefined. I tried doing it a string but it still is undefined. Also when instead of id I use the username it isn't undefined. -
How to debug a 502 error for a Docker compose app?
An application that I'm maintaining (I'm not the one who created it, so my knowledge of it is limited) is deployed via Docker compose and consists of the following containers: name what is status servey_prod_bot a Telegram bot works ... helper services for bot, of no interest in this context servey_prod_stat reports new data works servey_prod_app admin web app not accessible (see below) servey_prod_nginx well, Nginx works servey_prod_db db works Recently, I was asked to modify the _stat component, and, long story short, that forced me to rebuild the whole thing and restart the containers, and some code changes might get applied. The _bot and the _stat seem to work nicely, the _app is also up, but now an attempt to get it via browser fails with 502. What I have done to debug this already: the _app (it's a Django app): I've checked docker logs and shows that it successfully started gunicorn, listens to http://0.0.0.0:9090 and has 3 workers (on restart workers exited and the app is shut down, then restarted successfully; no migrations involved); I've also checked nc -zv localhost 9090 and nc -zv 0.0.0.0 9090 inside the container, both report that the port is open; finally, I've … -
Django Turn off/on pagination for one filter request
I have 2 models, 1 for Product and 1 for ProductImages with pagination set to 10. For any product, we can have associated multiple images. class Product(models.Model): title = models.CharField(max_length=200) details = models.TextField(null = True) slug = models.CharField(max_length=300, unique=True, null=True) class ProductImages(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='product_imgs') image = models.ImageField(upload_to='product_imgs/', null=True) def __str__(self): return self.image.url My ProductList view looks like, class ProductList(generics.ListCreateAPIView): queryset = models.Product.objects.all() serializer_class = serializers.ProductListSerializer pagination_class = pagination.PageNumberPagination def get_queryset(self): qs = super().get_queryset() if self.request.method == 'GET': if 'category' in self.request.GET: category = self.request.GET['category'] category = models.ProductCategory.objects.get(id=category) qs = qs.filter(category=category) if 'owner' in self.request.GET: print('get_queryset Owner') owner = self.request.GET['owner'] qs = qs.filter(owner=owner) if 'available' in self.request.GET: available = self.request.GET['available'] == 'true' qs = qs.filter(available=available) ids = [] for product in qs: # images = models.ProductImages.objects.filter(id=product.id) print('Images: %d', product.id) ids.append(product.id) for id in ids: print('Id %d', id) images = models.ProductImages.objects.filter(product__in=ids) I am trying to fetch products and images associated with those products. When I fetch products I get 10 products (as per set pagination) and I get 10 images. But problem is I want to get all (say) 25 images associated with those 10 products, i.e. I want to turn off the pagination only for filter on ProductImages … -
How To Upload and Display Images in Django 4.2.5 on Whogohost
I have developed my Django application using Django 4.2.5. And locally it is uploading and displaying images fine but on production server it is uploading but not displaying the uploaded images. I have check the url of the images on my HTML Templates while on the server using DevTools but it seems to be pointing rightly. I don't know whether this has to do with some dependencies of sort. So someone should help. See my Model Code: from imagekit.models import ProcessedImageField from django.core.exceptions import ValidationError from django.utils.deconstruct import deconstructible from imagekit.processors import ResizeToFill, Transpose #File Extension Validator @deconstructible class FileExtensionValidator: """ImageKit Validation Decorator""" def __init__(self, extensions): self.extensions = extensions def __call__(self, value): extension = value.name.split('.')[-1].lower() if extension not in self.extensions: valid_extensions = ', '.join(self.extensions) raise ValidationError(f"Invalid file extension. Only {valid_extensions} files are allowed.") image_extensions = ['jpeg', 'jpg', 'gif', 'png'] class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) role = models.CharField(max_length=20, blank=True) # 'admin', 'cashier', 'customer' full_name = models.CharField(max_length=60, blank=True) phone = models.CharField(max_length=14, blank=True) address = models.CharField(max_length=160, blank=True) is_active = models.BooleanField(default=True) image = ProcessedImageField( upload_to='profile_images', processors=[Transpose(), ResizeToFill(150, 200)], format='JPEG', options={'quality': 97}, validators=[FileExtensionValidator(image_extensions)], default='avatar.jpg' ) last_updated = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.user.username}-Profile' See the url to displaying the images: <img class="img-thumbnail" src=" {{ user.profile.image.url … -
Django session cookie is not being set in production
I have a Django application I just moved to production. I am unable to make the site display I am logged in. It works fine on my local machine and I do not see any errors in production and the username and password is correct. The problem the session cookie is not being set and my settings are correct I believe. Here are my settings related to sessions: DEBUG = False ALLOWED_HOSTS = ["localhost","102.219.85.91","founderslooking.com","app.founderslooking.com"] CORS_ALLOWED_ORIGINS = [ "http://localhost:8080", "http://127.0.0.1", "http://localhost:file", "http://app.founderslooking.com", ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True SESSION_COOKIE_SAMESITE = None SESSION_COOKIE_DOMAIN = "founderslooking.com" #SESSION_COOKIE_SECURE = False CSRF_TRUSTED_ORIGINS = ["http://localhost", "http://*.127.0.0.1", "http://app.founderslooking.com",] INTERNAL_IPS = [ "127.0.0.1", ] I am not using https because I am only testing the site until I am sure everything works, then I will switch over to https. Why is the session cookie not being set? The application is on a VPS using Ubuntu, Gunicorn, Nginx and Supervisord -
Postman request redirecting regardless of option and/or setting when run in GitHub
I'm experiencing some odd behaviour when running my postman collection through the CLI using Newman specifically when running in my GitHub Actions CI/CD environment. For my collection two requests are done to set both the CSRF token and the sessionid that are necessary for the other requests. In order to do this through the CLI I programmatically set the cookies based on the request's response headers. However the second request is redirected a few times before reaching it's end point and to get the value I need for the sessionid I specifically need the first redirected request. Postman/Newman has an option for this called --ignore-redirects which fixes this problem when running locally and even through docker. However when running it on the GitHub's CI/CD it seems that this options is ignored as the behaviour it shows is the same as not using the option at all. This then causes my post-request test script to not be able to find the sessionid and set it in the collection variable. This in turn causes all other requests to fail because of a lack of a sessionid. Is there a way around this? Or should I consider a different tool for API testing? … -
How to add a variable which pick up certain value dependent on other variable present in view.py in django
I want to make form2 variable in which we have to add condition that pick institute name from register table where institute code is equal to institute code present in form 1 variable and pass form2 in context so that it can be printed in template file. I have added code in view.py def view_eligibility_admin(request): form1 = Eligibility_Check.objects.all() form2 = {} # Initialize an empty dictionary to store institute names for item in form1: institute_code = item.Centre_code try: register_entry = Register.objects.get(institute_code=institute_code) institute_name = register_entry.institute_name form2[institute_code] = institute_name except Register.DoesNotExist: # Handle the case where the institute code doesn't exist in the Register model form2[institute_code] = "N/A" context = {'form1': form1, 'form2': form2} return render(request, 'view_eligibiity_admin.html', context) In my template.py I have used it like this. <tr> <td>{{ forloop.counter }}</td> <td>{{ i.Centre_code }} / {{ i.Serial_number }}</td> <td>{{ i.Date_of_survey }}</td> <td>{{ i.District }}</td> <td>{{ i.Voter_id }}</td> <td>{{ i.Ec }}</td> <td>{{ form2.item.institute_code }}</td> <td class="text-center"> <a class="btn btn-primary" href="{% url 'view_eligibility_pid' i.pk %}"><i class="fa fa-eye" aria-hidden="true"></i> </a> </td> </tr> {% endfor %}``` But i am getting blank value in place of institute name. -
Is it possible to get the all values of foreign key instead of id?
Is it possible to get all the values of foreign key instead of id? class WishlistSerializer(serializers.ModelSerializer): def to_representation(self, instance): rep = super(WishlistSerializer, self).to_representation(instance) rep['product'] = instance.product.name return rep -
Where can I host a Django website for free?
Guy's Is there any free hosting services available for python django application. I think AWS, Google Cloud and Azure are not completely free. Thanks in advance 😃 I had been using heroku for years but now heroku is changed their policy. -
Tastypie Django full hydrate returns an error when joining the protected Resource
I created here a small example to explain my problem for which I haven't find a solution on the web. I am using Django and Tastypie to implement a REST API. I have "MyUserResource" which is a descendant of Django's User model and this resource is protected with StaffAuthorization. Then I have "CommentsResource" which should be opened for Anonymous users as well. Now, my problem lies in the fact that during running Tastypie's full_hydrate operation within obj_create, Tastypie is trying to make a join on user table. That means that in case anonymous users are trying to fetch comments, the API returns Unauthorized error. For now I implement it to "open" MyUserResource" by using Authorization and checking within obj_create, obj_update and obj_delete if the user is staff or a superuser. But I wouldn't want that everyone is able to retrieve the list of users as well. Is it possible to protect User resource and still allow joins during hydration process? I still haven't tried to implement "my" obj_get function and there check if users are staff or superusers and for other types of user I might remove sensitive data? Here is the sample code, first Django models and then Tastypie … -
How to setup CSRF Trusted Origina domain on same server as Django docker app in plesk?
I currently have a django app installed on a Docker in Plesk. Id like to keep everything to basically localhost for any domain that I have hosted on the same server. The only thing that works is adding the actual domain https://subdomain.domain.com. Its not ideal to do this as Id like to use the Django app on multiple domains/subdomains that I have hosted on my plesk server. I tried the '*' option and it does not work either. Been breaking my head all day testing this and I cant seem to get it to work. :/ The error I receive is this in docker: django.security.csrf log Forbidden (Origin checking failed - https://subdomain.domain.com does not match any trusted origins.) Any help with experienced docker folks out there? I've tried https://localhost, https://127.0.0.1, the docker ip https://172.17.0.3 and a bunch of other options and nothing works. -
Updating celery workers code in production without distrupting currently running tasks?
I have a program that runs some tasks in the background, which can run for hours. I will have many tasks running at many different times. I cannot really kill the tasks, because the user is aspecting these tasks to finish. The basic gist of it is I have a frontend which sends a request to the backend to start a task. This task will scrape some data, and do some other stuff with that data. It could take many hours and they are important to keep running. I have thought of maybe shutting down the tasks and keeping track of where they left of from and just continueing. This could work, but I couldn't figure out how to do this and I would rather not kill the tasks at all as it may be half way through scraping the data. My current thought has been to have two queues. One with the old tasks and one with the new ones. But I don't know how I would redirect all the future tasks to the new queue. I would like to have a way to do this that is easy and I can do many times. Does anyone know any … -
GET /static/css/style.css?after HTTP/1.1 404 1820
During python web development using django, the contents of static are not applied.. Is there a way? Below is the code BASE_DIR = Path(__file__).resolve().parent.parent STATICFILES_DIR = [ BASE_DIR / 'static', os.path.join(BASE_DIR, 'static'), os.path.join(BASE_DIR, 'static/css'), os.path.join(BASE_DIR, 'static/image'), os.path.join(BASE_DIR, 'static/javascript'), ] 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', ], }, }, ] STATIC_URL = '/static/' STATIC_URL = 'static/' results are the same, and at the same time <link rel="stylesheet" href="{% static '/css/style.css' %}?after" /> and other than ?after output the same error this is errors my tree It is a situation where the codes of css were applied temporarily using the style tag of html. -
Trying to develop a spatial dashboard [closed]
I have been assigned the responsibility of developing a spatial data catalog that dynamically displays the count of available datasets within specified geographical boundaries. The datasets, comprising both vector and raster data, will be hosted and served through GeoServer. As new data is uploaded, the dataset count displayed on the catalog will automatically update to reflect the current total. I am keen to explore if anyone has undertaken a similar project and would be open to sharing insights or ideas to guide the successful execution of this initiative. I'm still research based on user-friendly, responsive, and interactive experience to users -
Django - Heroku postgres connection opens with each page refresh and does not close ever
I am using Django, heroku, websocket, AJAX, celery, postgres, consumer, asgi (uvicorn; tried Daphne also). My problem is that after just a page refresh, new postgres connection would be created, and it doesn't go away even after long inactivity. Soon with just refreshes my connections go over the top (20/20 on heroku). On local environment, no problem - connection does not add up no matter what I do. This happens only on heroku using heroku postgres (I'm using the default version). What I've tried: I've checked pg_stat_activity. The connections are related to the corresponding view code that queries certain data. for post in posts: temp_dict = defaultdict(list) recommendations_ordered = post.recommendations.all().order_by('created_at') ...and so on, including request.user. If I have 15 connections, most of them are from this -- same query. One from request.user. All idle. These don't exist when I run pg_stat_activity on local postgres. I've set my database settings as: if ENVIRONMENT == 'development': DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'redacted', 'USER': 'redacted', 'PASSWORD': 'redacted', 'HOST': 'localhost', 'PORT': '5432', } } else: DATABASES = { 'default': dj_database_url.config(default=os.environ.get('DATABASE_URL')) } DATABASES['default']['CONN_MAX_AGE'] = 0 DATABASES['default']['ATOMIC_REQUESTS'] = True I've added close.connection to the aforementioned view as well as tasks. Here's my procfile. … -
Django-Python = No data available in table [closed]
Why data is not showing up on my webpage/datatable?! The data is loading correctly in django-admin, but it´s not loading on the webpgage. Why data is not showing up on my webpage/datatable?! The data is loading correctly in django-admin, but it´s not loading on the webpgage. **ADMIN** from django.contrib import admin from App.models import Employee class EmployeeAdmin(admin.ModelAdmin): list_display = ['name', 'matricula', 'cargo', 'empresa'] list_filter = ['cargo', 'empresa'] list_display_links = ['name', 'matricula'] search_fields = ['name', 'empresa'] list_per_page = 50 admin.site.register(Employee, EmployeeAdmin) **MODELS** from django.db import models class Employee(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=100) matricula = models.CharField(max_length=15, blank=True) cargo = models.CharField(max_length=40) empresa = models.CharField(max_length=50) contrato = models.CharField(max_length=15) prefixo = models.CharField(max_length=10) dependencia = models.CharField(max_length=40) andar = models.CharField(max_length=5) bloco = models.CharField(max_length=5) edificio = models.CharField(max_length=30) cracha = models.CharField(max_length=10) def __str__(self): return self.name **VIEWS** from django.shortcuts import render from .models import Employee from django.http import HttpResponseRedirect from django.contrib import messages def home(request): employee_list = Employee.objects.all() return render(request, 'home.html', {"employees":employee_list}) def add_employee(request): if request.method=="POST": if request.POST.get('name') \ and request.POST.get('matricula') \ and request.POST.get('cargo') \ and request.POST.get('empresa') \ and request.POST.get('contrato') \ and request.POST.get('prefixo') \ and request.POST.get('dependencia') \ and request.POST.get('andar') \ and request.POST.get('bloco') \ and request.POST.get('edificio') \ or request.POST.get('cracha'): employee = Employee() employee.name = request.POST.get('name') employee.matricula = request.POST.get('matricula') employee.cargo … -
How to update context in Django-CMS
I am trying add my apps' queryset of my ListView in context of my apphook, but i could not get the queryset. I have created two models my ServicePLuginModel and Service model. class ServicePluginModel(CMSPlugin): title = models.CharField(_('title'), blank=True, help_text='Service Widget', max_length=64, ) class Service(CMSPlugin): # Attributes - Mandatory title = models.CharField(_('title'), max_length=200, blank=False) I have formed a ListView: class ServiceListView(ListView): model = Service queryset = Service.objects.all() def get_context_data(self, **kwargs): context = super(ServiceListView).get_context_data(**kwargs) queryset = Service.objects.all() context["now"] = timezone.now() context.update({'object_list': queryset}) context.update(kwargs) return super().get_context_data(**context) def render_to_response(self, context, **response_kwargs): # Shim to affect the CMS Toolbar only if self.request.toolbar and self.request.toolbar.edit_mode: menu = self.request.toolbar.get_or_create_menu('service-list-menu', 'Services') menu.add_break() return super(ServiceListView, self).render_to_response(context, **response_kwargs) urls.py app_name = 'services' urlpatterns = [ re_path('/', ServiceListView.as_view(), name='service-list'), re_path(r'^(?P<slug>[\w-]+)/?$', ServiceDetailView.as_view(), name='service_detail'), ] my cms_plugins.py @plugin_pool.register_plugin # register the plugin class ServicePluginPublisher(CMSPluginBase): model = ServicePluginModel # model where plugin data are saved module = _("Services") name = _("Service Plugin") # name of the plugin in the interface cache = False render_template = "services/service_list.html" def render(self, context, instance, placeholder): context.update({'instance': instance }) return context cms_apps.py: @apphook_pool.register # register the application class Servicesapphook(CMSApp): app_name = "services" name = "Services Application" def get_urls(self, page=None, language=None, **kwargs): return ["eldemmedya.apps.services.urls"] and my service_list.html: {% for service … -
Sending Mails from Django
So, I am trying to send email from Django. And I am getting errors. I have exhausted ChatGPT, Google. And finally I am here for help. I have followed so many tutorials but no matter what I do I get this error. [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond I have checked all my account details, password, other details 100's of time and all them should be what it is supposed to be. Here is my settings.py EMAIL_BACKEND= 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST= 'smtp.gmail.com' EMAIL_USE_TLS= True EMAIL_PORT= 587 EMAIL_HOST_USER= 'email@gmail.com' EMAIL_HOST_PASSWORD= 'app password generated by google' Here is the views.py from django.core.mail import send_mail from django.http import HttpResponse def simple_mail(request): send_mail( subject = 'test email 1', message = 'this is a test email', from_email = 'email@gmail.com', recipient_list = ['abc@gmail.com'], fail_silently=False, ) return HttpResponse('OK') The quota of free mails is not ended, well because I did not send any. Also, I am testing with localhost and internet is working. -
How to display the sum of all expenses in a chart
So I have a project of building a web app that tracks expenses and I am at a point where I have incorporated a chart but I also want to display the total sum of all expenses (which is dynamic) along side the chart but I am having a hard time figuring out how I should do it because I am kind of a beginner at this. Here is my js file for the chart: const renderChart = (data, labels) => { var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'doughnut', data: { labels: labels, datasets: [{ label: 'Monthly Expenses', data: data, }], }, options: { borderWidth: 10, borderRadius: 2, hoverBorderWidth: 0, plugins: { legend: { display: false }, }, }, }); } const getChartData=() => { console.log("fetching") fetch('expense_category_summary') .then((res)=>res.json()) .then((results)=>{ console.log("results", results); const category_data = results.expense_category_data; const [labels, data] = [ Object.keys(category_data), Object.values(category_data), ]; renderChart(data, labels); }); }; document.onload = getChartData(); Please help, Thank you in advance. -
How can i make many-to-many selected fields clickable as links in django admin panel
I'm working on a Django project, and I have an admin panel where I manage projects. In this project admin, I have a matched_pros field, which is a ManyToManyField related to the "main.User" model. I would like to make the selected fields in the matched_pros widget clickable, so that when I click on a user, it takes me to the user change page in the admin panel. matched_pros = models.ManyToManyField( "main.User", blank=True, related_name="matched_projects" ) exemple: many to many widget like in the picture when i click on client alger- c51 block it will take me to admin/main/pro/51/change I've attempted to add JavaScript code to make the users clickable, but I'm encountering issues with the code not functioning as expected, and i don't wanna complicate it using javascript and adding another file to the codebase -
NoReverseMatch at /reset-password-confirm/
Im trying to implement Reset Password View by using View class. Actually I faced with an error that is annoying. I have 3 Views for implementing: UserResetPasswordView Here User enters email and a request sends to his/her email UserResetPasswordRequestSentView Here shows a message that email has sent UserResetPasswordConfirm after 2 views above, this view let's the user change password. after redirecting user to UserResetPasswordRequestSentView, an email will be send to the user's email to access the user to change his/her password. so user will be redirect to UserResetPasswordConfirm that contains inputs for setting new password. This is my urls.py script: urlpatterns = [ path( route='reset-password', view=views.UserResetPasswordView.as_view(), name='reset', ), path( route='reset-password-request-sent', view=views.UserResetPasswordRequestSentView.as_view(), name='reset_sent', ), path( route='reset-password-confirm/<uidb64>/<token>', view=views.UserResetPasswordConfirm.as_view(), name='reset_confirm', ), ] this is UserResetPasswordView view: class UserResetPasswordView(View): def get(self, request: HttpRequest) -> HttpResponse: reset_password_form: ResetPasswordForm = ResetPasswordForm() return render( request=request, template_name='reset/reset.html', context={ 'reset_password_form': reset_password_form, }, ) def post(self, request: HttpRequest) -> Union[HttpResponseRedirect, HttpResponsePermanentRedirect, HttpResponse]: reset_password_form: ResetPasswordForm = ResetPasswordForm(request.POST or None) if (reset_password_form.is_valid()): cd = reset_password_form.cleaned_data user = get_user_model().objects.filter(Q(email=cd['email'])).first() if (user): subject = 'درخواست بازنشانی رمز ورود' message = render_to_string( template_name='email/template_reset_password.html', context={ 'user': user, 'domain': get_current_site(request=request).domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), 'protocol': 'https' if request.is_secure() else 'http', } ) send_mail( subject, message, 'settings.EMAIL_HOST_USER', [cd['email']], …