Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
HTMX hx-target moves content down instead of replacing it in designated id
I am having the problem where my hx-target doesn't seem to be replacing the content where the target I point to. I'm using a a base html file that has a div with an id of requestcontent in it. All of my links, form actions and hx actions that I'm using point to this div for replacement. My initial access from an item on the menu sidebar works fine and gives results as shown here: Even when I click on the "Add bill" button the page renders correctly: However if I press close or save on this page when I return to the original page the top of the add page is still present: This is true from both my add and delete pages. The initial page that starts out the entire process is in billlist.html <div class="container shadow min-vh-100 py-2"> {% include 'acctsite/partials/messages.html' %} <h2>Accounts Payable / Bills Listing</h2> <div class="row" align="right"> <div class="col-10"></div> <div class="col-2 pb-1"> <button class="btn btn-primary btn-sm" hx-trigger="click" hx-get="{% url 'expadd' %}" hx-target="#requestcontent"> Add bill </button> </div> </div> <div class="row"> <div class="col h5">Date</div> <div class="col h5">Vendor</div> <div class="col h5">Description</div> <div class="col h5">Amount</div> <div class="col h5">Paid Info</div> <div class="col-1"></div> <div class="col-1"></div> <div class="col-1"></div> </div> <div class="row"> … -
How to Change django-autocomplete-light input box styling?
I have gotten the autocomplete to work with my Database and my front end, but the input widget looks slightly off. Is there a way to change the styling for the input? Also, is there a way to remove the initial dropdown, so after you click once, you can start typing and suggestions will appear? I am using the ListSelect2 Widget. The Select2Multiple looks like more of what I need but I want input to be only one. Current Widget Pre-Input Current Widget During Input Current Widget After Selection Desired Look (Select2Multiple Widget) I would appreciate any suggestions! -
Is there a way in Django where the superadmin can create normal users and the users gets an email with the credentials that was created for them?
I am having troubles about how to implement a scenario I am working on. I'm new to web dev so please pardon my naivety. I am using the default Django admin panel, where I have logged in with a super admin I created. The app doesn't have a sign up view so only the admin will be able to create new users. The normal users will them receive an email with their credential. So that they can login with through the LoginAPIView. views.py class LoginView(APIView): serializer_class = LoginSerializer def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) return Response(serializer.data, status=status.HTTP_200_OK) serializers.py class LoginSerializer(serializers.ModelSerializer): email = serializers.EmailField(max_length=255) password = serializers.CharField(min_length=8, write_only=True) class Meta: model = User fields = ["email", "password"] def validate(self, attrs): email = attrs.get("email") password = attrs.get("password") user = auth.authenticate(username=email, password=password) if not user: raise AuthenticationFailed("Invalid credentials") if not user.is_active: raise AuthenticationFailed("Account is not active, please contain admin") return {"email": user.email} models.py class UserManager(BaseUserManager): def create_user(self, email, password=None, **kwargs): if not email or not password: raise ValueError("Users must have both email and password") email = self.normalize_email(email).lower() user = self.model(email=email, **kwargs) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): if not password: raise ValueError("Password is required") user = self.create_user(email, password) user.is_superuser … -
Django - I can no longer save form with dynamic formset
I would like your help with a problem that I can't solve or find a solution on the internet. I have a user registration form that was working correctly before. But feel the need to insert a dynamic formset. However, now with the formset when filling out and sending the form, no data is saved in the database and instead of being redirected to a list of users, I am redirected to the form again already filled with the data that failed to be sent and without showing any kind of error. -=-=-=-=-=-=--=-=-==-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- Olá desenvolvedores, Gostaria da ajuda de vocês para um problema que não consigo resolver ou não encontro solução na internet. Eu tenho um formulário de registro de usuário que estava funcionando corretamente antes. Mas sinto a necessidade de inserir um formset dinâmico. Porém, agora com o formset ao preencher e enviar o formulário, nenhum dado é salvo no banco de dados e ao invés de ser redirecionado para uma lista de usuários, sou redirecionado novamente para o formulário já preenchido com os dados que não conseguiram enviar e sem apresentar nenhum tipo de erro. -=-=-=-=-=-=--=-=-==-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- models.py ` class Contato(models.Model): tipo = ( ('Residencial', 'Residencial'), ('Comercial', 'Comercial'), ('Celular', … -
Django forms: cannot access local variable 'form' where it is not associated with a value
Condition: I have a model, created an empty table in the database, and I'm trying to create an html form that will fill in the fields of the corresponding columns of the table. And here's what my app looks like: models.py from django.db import models class Cities(models.Model): city = models.CharField(max_length=100) def __str__(self): return self.state class Routes(models.Model): route_name = models.CharField(max_length=50, default='Route') lvl = models.IntegerField(default=0) about = models.TextField(max_length=1500) total_distance = models.IntegerField(default=0) city = models.ForeignKey(Cities, on_delete=models.CASCADE) forms.py from django.forms import ModelForm from .models import Routes class RouteForm(ModelForm): class Meta: model = Routes fields = '__all__' views.py from django.shortcuts import get_object_or_404, render from django.http import HttpResponse from routes_form.forms import RouteForm def getAbout(request): if request.method == 'POST': form = RouteForm(request.POST) if form.is_valid(): form.save() return render(request, 'routes_form/form_page.html', {'form': form}) form.html <form method="post"> {% csrf_token %} <legend> <h2>About</h2> </legend> {{ form }} <input type="text" placeholder="Write more about the route: about waypoints, points of interest and warnings."> <input type="submit" value="Send route"> </form> I have already tried to do everything as indicated in the Django Forms documentation. But still something is wrong. Even at the moment of starting the server, it writes an error: cannot access local variable 'form' where it is not associated with a value -
NameError: name 'Message' is not defined (Django - Python3)
So, I'm creating an app in Django, and I can't seem to reference a class in the same file. My models.py: from django.db import models from django.core.validators import MinLengthValidator from users.models import User from .models import Message class Group(models.Model): group_id = models.IntegerField(unique=True) group_name = models.CharField(max_length=100, validators=[MinLengthValidator(2)]) #owner = models.ForeignKey(User) creation_date = models.DateField(auto_now=True) max_users = models.IntegerField(validators=[MinLengthValidator(2)]) members = models.ManyToManyField(User, max_length=max_users) messages = models.ManyToManyField(Message) class Message(models.Model): content = models.CharField(max_=500, validators=[MinLengthValidator(1)]) sent_date = models.DateTimeField(auto_now=True) sender = models.OneToOneField(User) I tried importing from the same module... from .models import Message ...but this results in a circular import. Does anyone know how to resolve this? -
Creating credentials file on server via Dockerfile & Google cloud secret manager
I'm using Google cloud build for CI/CD for my django app, and one requirement I have is to set my GOOGLE_APPLICATION_CREDENTIALS so I can perform authenticated actions in my Docker build. For example, I need to run RUN python manage.py collectstatic --noinput which requires access to my Google cloud storage buckets. I've generated the credentials and it works well when simply including it in my (currently private) repo as a .json file, so it gets pulled into my Docker container with the COPY . . command and setting the env variable with ENV GOOGLE_APPLICATION_CREDENTIALS=credentials.json. Ultimately, I want to grab the credential value from secret manager and create the credentials file during the build stage, so I can completely remove the credentials from the repo. I tried doing this with editing cloudbuild.yaml (referencing this doc) with various implementations of the availableSecrets config, $$SECRET syntax, and build-args in the docker build command and trying to access in Dockerfile with ARG GOOGLE_BUILD_CREDS RUN echo "$GOOGLE_BUILD_CREDS" >> credentials.json ENV GOOGLE_APPLICATION_CREDENTIALS=credentials.json with no success. If someone could advise me how to implement this in my cloudbuild.yaml and Dockerfile if its possible, or if there's another better solution altogether, would be much appreciated. This is the … -
Filter using @property field django
I would like to filter based on @property field to generate a queryset. My model as below. `class PrHW(models.Model): po_duration = models.IntegerField(null=True) provision_start_date = models.DateField(null=True, blank=True) description = models.TextField(blank=True, null=True) @property def provision_end_date(self): provision_end_date = self.provision_start_date + relativedelta(months=self.po_duration) return provision_end_date` Since "provision_end_date" is a calculated field, it is not part of PrHW.objects.all() and hence I am unable create queryset using it as a filter option (eg, generate list of PrHW objects where provision_end_date is less than today - This generates error that "provision_end_date" is not a valid field; which was expected). I tried creating custom model manager but still I am unable to access either the @property field or other fields such as "provision_start_date" in the custom manager. May be this would be straingt forward but even after several searches, unable to get the hang of it. Any help is appreciated. -
Querying multiple schemas with django tenants
I'm writing this question because I have doubts about how to implement a scenario that we had not foreseen for my django developed application. Basically what I need is a way to allow some types of users, depending on their role, could access data that is in multiple schemas. So the approach that I had thought of was to create relationships between the "tenants", which define the database schemes, and detecting which of them a certain user belongs to, to be able to query all the schemes that are related to it. In the same way, this has some drawbacks, since this solution would require a lot of additional programming and concatenating querysets or working by adding the responses of the serialized data of each queryset of the aforementioned schemas could be inefficient. Thanks in advance. -
Django Rest how to show list of comment which belongs only from related Blog and Author?
Assume Author Jhone write an Blog which title is "This blog written by author Jhone" and Author Joe write an Blog "This blog written by author Joe" . Jhone blog received 20 comments and Joe blog received 10 comments. When Jhone will be login his account he can only able to see comments those belongs from his blog post and same will be for Joe. Here I tried this query Comment.objects.all().filter(blog__author_id=request.user.id) but still now everyone can see each others blog comments from my api url. here is my code: @api_view(['POST', 'GET']) def comment_api(request): if request.method == 'POST': serializer = CommentSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) if request.method == 'GET': comment = Comment.objects.all().filter(blog__author_id=request.user.id) serializer = CommentSerializer(comment, many=True) return Response(serializer.data) serializer.py class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = '__all__' models.py class Blog(models.Model): author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) blog_title = models.CharField(max_length=200, unique=True) class Comment(models.Model): name = models.CharField(max_length=100) email = models.EmailField(max_length=100) comment = models.TextField() blog = models.ForeignKey(Blog, on_delete=models.CASCADE) -
How can i change django admin to ltr style without change language?
I use Persian language in my django project : LANGUAGE_CODE = 'fa-ir' and I want to change the direction from rtl to ltr without changing the language code. How can I do this? I tried to change this from admin template but I couldn't -
Django – Efficiently fetch recursive categoryi structure
I have a model which looks like this: class Category(models.Model): name = models.CharField(max_length=50) parent = models.ForeignKey( 'categories.Category', null=True, blank=True, on_delete=models.CASCADE, related_name='categories' ) basically, in the parent field, it references itself. If a parent is set to None, it's the root category. I use it to build a hierarchy of categories. What would be the most efficient way to: fetch all the objects through the hierarchy display them in a template? For some reason, select_related does not seem to lead to performance improvements here. I also found this: How to recursively query in django efficiently? But had a really hard time applying it to my example. Would appreciate any help. Thanks! -
'>' not supported between instances of 'type' and 'datetime.date'
I'm creating a CRUD application that displays activities available on or after today; I'm working through the filtering mechanism on displaying these activities, however I'm having a nightmare trying to only show the activities that are on/after today. I'm getting the below error when I try to use the '>=' operand, however it's giving me the following error: '>' not supported between instances of 'type' and 'datetime.date' Below is my views.py for the comparison: today= date.today() available_activities = Activity.objects.filter(available = True).values() activities = available_activities.filter(date > today).values() activities= available_activities.order_by('date','start_time') Below is a screenshot of the error traceback also, to show the data format for the data in the DB also. -
RegexValidator in Django Models not validating email correctly
I'm making a django form with an email field and using a RegexValidator and want a specific format of of the email but it seems to be not validating the field correctly email = models.EmailField( unique=True, validators=[ RegexValidator( regex=r"^[2][2][a-zA-Z]{3}\d{3}@[nith.ac.in]*", message= "Only freshers with college email addresses are authorised.") ], ) When I am entering the email ending with @nith.ac.in or @nith.acin both are getting accepted while @nith.acin should not get accepted... any sols? -
UNIQUE constraint failed: auth_user.username while trying to register the user in django
I have written following set of code in views.py of my project but when I try to register the user info as an object in the database, above mentioned error arrived views.py from django.shortcuts import render from django.http import HttpResponse from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from django.contrib import messages from django.shortcuts import redirect, render # Create your views here. def home(request): return render(request, "authentication/index.html") def signin(request): if request.method == "post": username = request.POST['username'] pass1 = request.POST['pass1'] user = authenticate(username = username, password=pass1) if user is not None: login(request, user) fname = user.first_name return render(request, 'authenticate/index.html', {'fname' : fname}) else: messages.error(request, 'Bad credentials') return redirect('home') return render(request, "authentication/signin.html") def signup(request): if request.method == "POST": # username = request.POST.get('username') username = request.POST['username'] fname = request.POST['fname'] lname = request.POST['lname'] email = request.POST['email'] pass1 = request.POST['pass1'] pass2 = request.POST['pass2'] myuser = User.objects.create_user(username, email, pass1) ## Error is coming in this line ## myuser.firstname = fname myuser.lastname = lname myuser.save() messages.success(request, 'Your account has been succesfully created.') return redirect('/signin') return render(request, "authentication/signup.html") def signout(request): pass I am trying to make user login system and following error has arrived in views.py of my app. enter image description here -
Graphene Python JSON Query Parameter
i'm trying to make a query passing a list of JSON as parameters but i have no idea how and i couldnt find anywhere else example query { verify(password="aba", rulesList=[{"rule":"minDigit", value:5}, {"rule":"noRepeted", value:0}] { ... } } and the Python Code enter image description here I've tried changing the rulesList type but i couldnt use ObjectTypes inside that list thanks for your time -
Get Old Objects, Update, and then return old objects
I have an APIView that looks like this: class GetNotifications(ListAPIView): serializer_class = NotificationSerializer def get_queryset(self): notifications = Notification.objects.select_related().filter(user=self.request.user).order_by("-created_at") Notification.objects.select_for_update().filter(is_read=False, user=self.request.user).update(is_read=True) return notifications What I'm trying to do is get all notifications that the user has. These include notifications that have been read and that have been not read yet (hence the is_read field). I'd like to return both the is_read and the not is_read notifications.Once those objects are received then an update will happen to change the not read notifications to is read. What this means is that any user who accesses this API through the site will mean that they've read their notifications so we can set is_read=True...however, my current code returns the objects after updating them. I want to return the old objects prior to updating hence me assigning notifications to the old objects before updating. I believe this is due to lazy loading on Django's part. Is there a way/better way to solve this? -
Issue With Nested Comments Using MPTT in Django and Django Rest Framework API - Result In Detail Not Found
I'm trying to create a nested comment system using MPTT but using Django Rest Framework to serialize MPTT tree. I got the nested comments to work - and these comments are added, edited, and deleted by calling Django Rest Framework API endpoints only - not using Django ORM DB calls at all. Unfortunately, there is a bug I couldn't figure out! Although the comments are added, edited, and deleted fine - but when a seventh or eighth comment is nested - suddenly the first-in comment or first-in nested comments would become [detail: Not found.] - meaning it will return an empty result or throw an unknown validation error somewhere which I couldn't figure out why. This results in when clicking on edit or delete the buggy comments becoming impossible - but the GET part is fine since these buggy comments do show up in the comment section (or should I say the list part returns fine). The image I'll attach will show that when I entered comment ggggg, the comment aaaa and bbbb will throw errors when trying to edit or delete them. If I delete comment gggg, comment hhhh will also be deleted (as CASCADE was enabled) - and … -
'Django OperationalError: no such table: users_portal' in Django
I'm creating a webapp and I am attempting to access the 'Portal' page (created by myself) in the User's section on the in-built Django Admin backend page. However, when I try to access this page, the following error is outputted onto the terminal: django.db.utils.OperationalError: no such table: users_portal This error has stopped my from accessing the 'Portal' page and therefore, has hindered me from progressing with my webapp. Any suggestions on how to get rid of this error? Would be highly grateful and open to all suggestions! I have already tried to make the migrations, and have them migrated. I have also attempted the --fake migrations and unfortunately none of them have yielded to the result I expected. -
AttributeError at /sign-up and /sign-in 'WSGIRequest' object has no attribute 'is_ajax'
I am getting this problem, any help will appreciated, Im getting an arror trying to sign-in or sign-up.Error bellow. AttributeError at /sign-up 'WSGIRequest' object has no attribute 'is_ajax' I know that function is depreciated now, but i can't seem to fix the issue. mixins.py class AjaxFormMixin(object): ''' Mixin to ajaxify django form - can be over written in view by calling form_valid method ''' def form_invalid(self, form): response = super(AjaxFormMixin, self).form_invalid(form) if self.request.is_ajax(): message = FormErrors(form) return JsonResponse({'result': 'Error', 'message': message}) return response def form_valid(self, form): response = super(AjaxFormMixin, self).form_valid(form) if self.request.is_ajax(): form.save() return JsonResponse({'result': 'Success', 'message': ""}) return response views.py def profile_view(request): ''' function view to allow users to update their profile ''' user = request.user up = user.userprofile form = UserProfileForm(instance=up) if request.is_ajax(): form = UserProfileForm(data=request.POST, instance=up) if form.is_valid(): obj = form.save() obj.has_profile = True obj.save() result = "Success" message = "Your profile has been updated" else: message = FormErrors(form) data = {'result': result, 'message': message} return JsonResponse(data) else: context = {'form': form} context['google_api_key'] = settings.GOOGLE_API_KEY context['base_country'] = settings.BASE_COUNTRY return render(request, 'users/profile.html', context) class SignUpView(AjaxFormMixin, FormView): ''' Generic FormView with our mixin for user sign-up with reCAPTURE security ''' template_name = "users/sign_up.html" form_class = UserForm success_url = "/" … -
django channel image serializing error says You cannot call this from an async context - use a thread or sync_to_async
i have a Invoice serializer which include a image serilaizer as a invoice has relation one to many with image i got this error when i enable many=True in images field in invoice serializer Exception inside application: You cannot call this from an async context - use a thread or sync_to_async. Traceback (most recent call last): File "D:\projects\TaxiTR\env\lib\site-packages\django\contrib\staticfiles\handlers.py", line 101, in __call__ return await self.application(scope, receive, send) File "D:\projects\TaxiTR\env\lib\site-packages\channels\routing.py", line 62, in __call__ return await application(scope, receive, send) File "D:\projects\TaxiTR\env\lib\site-packages\channels\security\websocket.py", line 37, in __call__ return await self.application(scope, receive, send) File "D:\projects\TaxiTR\core\middleware.py", line 57, in __call__ return await super().__call__(scope, receive, send) File "D:\projects\TaxiTR\env\lib\site-packages\channels\middleware.py", line 24, in __call__ return await self.inner(scope, receive, send) File "D:\projects\TaxiTR\env\lib\site-packages\channels\sessions.py", line 47, in __call__ return await self.inner(dict(scope, cookies=cookies), receive, send) File "D:\projects\TaxiTR\env\lib\site-packages\channels\sessions.py", line 263, in __call__ return await self.inner(wrapper.scope, receive, wrapper.send) File "D:\projects\TaxiTR\env\lib\site-packages\channels\auth.py", line 185, in __call__ return await super().__call__(scope, receive, send) File "D:\projects\TaxiTR\env\lib\site-packages\channels\middleware.py", line 24, in __call__ return await self.inner(scope, receive, send) File "D:\projects\TaxiTR\env\lib\site-packages\channels\routing.py", line 116, in __call__ return await application( File "D:\projects\TaxiTR\env\lib\site-packages\channels\consumer.py", line 94, in app return await consumer(scope, receive, send) File "D:\projects\TaxiTR\env\lib\site-packages\channels\consumer.py", line 58, in __call__ await await_many_dispatch( File "D:\projects\TaxiTR\env\lib\site-packages\channels\utils.py", line 50, in await_many_dispatch await dispatch(result) File "D:\projects\TaxiTR\env\lib\site-packages\channels\consumer.py", line 73, in dispatch await handler(message) … -
The view post.views.view didn't return an HttpResponse object. It returned None instead
I want to create a new post using PostCreateView and go to the details page of the new post in the next step, but I get this error: (The view post.views.view didn't return an HttpResponse object. It returned None instead.) views class PostDetailView(View): """see detail post""" def get(self, request, post_id, post_slug): post = Post.objects.get(pk=post_id, slug=post_slug) return render(request, "post/detail.html", {"post": post}) class PostCreateView(LoginRequiredMixin, View): form_class = PostCreateUpdateForm def get(self, request, *args, **kwargs): form = self.form_class return render(request, "post/create.html", {"form": form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): new_post = form.save(commit=False) new_post.slug = slugify(form.cleaned_data["body"][:20]) new_post.user = request.user new_post.save() messages.success(request, "you created a new post", "success") return redirect("post:post-detail", new_post.id, new_post.slug) models class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() slug = models.SlugField() img = models.ImageField(upload_to="%Y/%m/%d/") created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) urls app_name = 'post' urlpatterns = [ path('', views.BlogView.as_view(), name="home"), path('detail/<int:post_id>/<slug:post_slug>/', views.PostDetailView.as_view(), name="post-detail"), path('delete/<int:post_id>/', views.PostDeleteView.as_view(), name="post-delete"), path('update/<int:post_id>/', views.PostUpdateView.as_view(), name="post-update"), path('create/', views.PostCreateView.as_view(), name="post-create"), ] -
Django FieldError: Unsupported lookup 'kategorie' for IntegerField or join on the field not permitted
I have a Django Table with Crispy Filter and I would like to filter in Data table based on Category. But I am getting FieldError. I tried to define my filter field by this way in filters.py: kategorie = django_filters.CharFilter(label="Kategorie", field_name="ucet__cislo__kategorie__jmeno", lookup_expr='icontains') And I have following structure of models in models.py: class Data(models.Model): ucet = models.ForeignKey(Ucty, on_delete=models.CASCADE, null=True, blank=True) class Ucty(models.Model): cislo = models.IntegerField("Účet", blank=True, null=True) class Mustek(models.Model): ucet = models.ForeignKey(Ucty, on_delete=models.CASCADE) kategorie = models.ForeignKey(Kategorie, on_delete=models.CASCADE) class Kategorie(models.Model): jmeno = models.CharField("Kategorie", max_length=20, blank=True, null=True) Any idea how to correct field_name definition in filter? -
Field value is not displayed for editing in the form Django?
views.py dicfacultets = DicFacultets.objects.all() disfacultetsedit = DicFacultets.objects.get(id=id) form = FacultetsForm(request.POST, instance=disfacultetsedit) if request.method == 'GET': return render(request, 'tao/dicfacultetsedit.html', {'dicfacultets': dicfacultets, 'form': FacultetsForm(), }) else: try: if form.is_valid(): disfacultetsedit = form.save(commit=False) title = request.POST.get('title') disfacultetsedit.title = title disfacultetsedit.save() return redirect('dicfacultets') except TypeError: return render(request, 'tao/dicfacultets.html', {'dicfacultets': dicfacultets, 'error': 'error', 'form': form, }) return render(request, 'tao/dicfacultets.html', {'dicfacultets': dicfacultets, }) html {% for fac in dicfacultets %} ... # *call modal window for editing* <a href="facultetsedit/{{ fac.id }}" class="on-default edit-row" data-toggle="modal" data-target="#facultetsedit{{fac.id}}"><i class="fa fa-pencil"></i></a> # next call form method="POST" action="{% url 'facultetsedit' id=fac.id %}"> {{ form }} form in modal window when a modal window is called, the field is empty, but editing and saving work -
reverse lazy error NoReverseMatch at django DeleteView
I'm trying to return back to patient analyses list after deleting 1 analysis. But can't manage proper success url So this is my model: class PatientAnalysis(models.Model): patient = models.ForeignKey(Patient, on_delete=models.CASCADE) analysis_date = models.DateTimeField(help_text = "Разделяйте даты точками! Используйте '/' или '-'") # analysis_type = models.IntegerField(choices = ANALYSIS_CHOICES) #перевести в таблицу analysis_type = models.ForeignKey(AnalysisType, on_delete=models.CASCADE, default=1) analysis_data = models.DecimalField(max_digits=5, decimal_places=2) def __str__(self): return f"{self.patient}" def get_analysis_type(self): return f"{self.analysis_type}" def get_absolute_url(self): return reverse('journal:patient_analysis', kwargs={'hist_num_slug':self.patient.pk}) class Meta: unique_together = ('analysis_date','analysis_type',) Here's the class for list all analyses per patient class PatientAnalysisListView(ListView): model = PatientAnalysis template_name = 'journal/patient_analysis.html' context_object_name = 'analysis' def get_context_data(self, *, object_list=None, **kwargs): <...> return context def get_queryset(self): return PatientAnalysis.objects.filter(patient__hist_num=self.kwargs['hist_num_slug']).order_by('-analysis_date') And here i stuck with next code: lass PatientAnalysisDeleteView(DeleteView): # Form --> Confirm Delete Button # model_confirm_delete.html model = PatientAnalysis success_url = reverse_lazy('journal:patient_analysis', kwargs={'key': model.patient}) And getting error: `NoReverseMatch at /journal/patientanalysis_delete/49 Reverse for 'patient_analysis' with keyword arguments '{'key': <django.db.models.fields.related_descriptors.ForwardManyToOneDescriptor object at 0x7fb88b8c0d90>}' not found. 1 pattern(s) tried: ['journal/patient_analysis/(?P<hist_num_slug>[-a-zA-Z0-9_]+)\Z'] Request Method: POST Request URL: http://127.0.0.1:8000/journal/patientanalysis_delete/49 Django Version: 4.1.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'patient_analysis' with keyword arguments '{'key': <django.db.models.fields.related_descriptors.ForwardManyToOneDescriptor object at 0x7fb88b8c0d90>}' not found. 1 pattern(s) tried: ['journal/patient_analysis/(?P<hist_num_slug>[-a-zA-Z0-9_]+)\Z'] Exception Location: /home/verts/.local/lib/python3.10/site-packages/django/urls/resolvers.py, line 828, in _reverse_with_prefix Raised during: journal.views.PatientAnalysisDeleteView Python Executable: …