Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make use of Django's security features (i.e. CSRF) with TokenAuthentication in Django Rest Framework
I am currently building my app with TokenAuthentication (can I use SessionAuthentication instead for a seperate SPA, I didn't fully understand that part of the documentation, but it sounds like SessionAuthentication should only be used for XHR coming from websites, where the frontend is served by Django). I have heard that there are several security issues with just storing the token in a cookie and calling it a day. So my goal is to have persistent sessions (my users don't have to login each time they visit my site) and to protect myself against attacks (I am thinking of CSRF, XXS and CORS, am I missing some?). To solve the first problem, I had the idea of storing the token in a secure Http-Only cookie (and sending it therefore automatically with every request to the backend). I already found a solution to this here: Django-rest-auth use cookie instead of Authorization header Now what I'm wondering is: Am I using the correct approach, is there some easy way that I'm missing/haven't heard about? How would I go about securing my site against CSRF and XXS when using TokenAuthentication? I've read the official documentation about this, but not getting much sense out … -
how to use SQL connection string class in python
i want to create a class which maintain sql connection instead of creating sql connection everytime. models.py in models.py i declare sql connection in sqlconn method whenever i call this i want to establish sql connection in views.py from django.db import models import pyodbc def sqlconn(request): constr = "DRIVER={SQL Server};SERVER=localhose;DATABASE=testdb;UID=user;PWD=password" conn = pyodbc.connect(constr) return conn Views.py in this views.py i'm retrieving employee data from database instead of writing sqlconnection string in every views.py method. I want to call sqlconn method from models and i want to do further process like getdata, insertdata, deletedata, updatedate from django.shortcuts import render from .models import sqlconn import pyodbc def getEmpData(request): conn = sqlconn cursor = conn.cursor() #cursor.execute("select * from Employee") cursor.execute("exec sp_demotable") result = cursor.fetchall() return render(request, 'getempdata.html', {'result':result}) i tried above code but its not working its showing error, any help thanks in advance Note: what is the best practices for python any articles are videos tutorials provide its great help for me, because i'm new to python but i've good knowledge in .NET Programming -
trying to applying DRY principle to model methods in django
I have these two methods that are identical except in name and one variable, and it really bugs me, but no matter what I do, I can't figure out how make it so that I just pass a variable into a method in django. These are the two methods, I can post the model if it's needed but I'm fairly sure all the info that is needed is in here, but for clarity, the two model fields are 'launch', 'staff_trials' and 'published' all three are just dates, all other variables are created in the method: @property def progress_launch(self): timeline = self.launch - self.published.date() current = self.launch - datetime.now().date() if timeline < current: percentage == 100 else: percentage = 100 - round((current/timeline) * 100) min_bar = 1 max_bar = 100 if percentage is not None: if percentage < min_bar: return min_bar elif percentage > max_bar: return percentage else: percentage = max_bar return percentage @property def progress_trials(self): timeline = self.staff_trials - self.published.date() current = self.staff_trials - datetime.now().date() if timeline < current: percentage == 100 else: percentage = 100 - round((current/timeline) * 100) min_bar = 1 max_bar = 100 if percentage is not None: if percentage < min_bar: return min_bar elif percentage > … -
Modal Formbuilder for wagtail?
Hello im new to wagtail and its been really awesome so far. However im facing an issue trying to create a modal version of the formbuilder. My intentions is to create an action button within the base.html of which the user can click at any point in time and enter a modal pop up form to leave a feed back . Is there a way of accomplishing this? -
Django ORM join without FK on aggregated table
I am trying to write an ORM query to join a table with itself after aggregation (Hence select_related etc won't work). The simple SQL query is with table transaction with fields (account_id, amount, booking_date, reference, ...) select * from transaction t join (select account_id, sum(amount) as total_amount from transaction where amount > 0 group by account_id) aggr on t.account_id = aggr.account_id where amount > 0.4 * total_amount; So far no luck. I even tried the join_to/CustomJoin from Django ORM. Joining subquery, but this didn' work. -
How to substitute data from another model into the form?
I want the data from another model that I identified by "id" to be substituted into the form and substituted in the url to go to the page with the form in which the data from the model field that I identified by "id" will be inserted form.py class AdmissionForm(forms.ModelForm): class Meta: model = Admission fields = ['date', 'name', 'admission'] class EquipmentWorkersForm(forms.ModelForm): class Meta: model = EquipmentWorkers fields = ['date', 'id_admission', 'id_type', 'id_workers', 'id_room'] views.py class AssignToWorker(View): def get(self, request, admission_id): admission = Admission.object.get(id=admission_id) form = EquipmentWorkersForm(instance=admission) return render(request, 'inventory/assignToWorker.html', context={'form': form, 'admission': admission}) def post(self, request): form = EquipmentWorkersForm(request.POST) if form.is_valid(): form.save() return redirect(equipments_list) return redirect(relocation_list) url.py path('assignToWorker/<str:admission_id>/', AssignToWorker.as_view(), name='assign_to_worker_url'), -
Tinye MCE and Django: HTMLField toolbar options (admin)
I have a Djando App running, I added a new simple Model with an order and a content field, the content is of type HTMLField, I manage to edit the field's content and format it just fine, my problem is that I need to be able to add bulleted lists in that field and I cannot find the way to tweak Tiny MCE's configuration to make it happen. I have tried to add tiny_mce.js file along with another js file with the parameters, and add a TINYMCE_DEFAULT_CONFIG section to config.py, but it's not working at all, I'm BTW new to Django and Python I'd appreciate if someone could give me a guide to be able to handle the Tiny MCE toolbar options from zero Thanks in advance! -
Django problem with creating instance of model basing on pre_delete signal
I have a model which represents the archives. Once the main advert has been deleted, it's archives version is being created to later view. I wanted to acomplish it basing on signals. I believe my code is correct but for some reason it does not launch signals. signals.py from django.db.models.signals import post_save, post_delete, pre_delete from django.dispatch import receiver from core.models import Advert, Archive @receiver(pre_delete, sender=Advert) def archive_advert(sender, instance, **kwargs): archives = Archive.objects.create(user=instance.user, title=instance.title, category=instance.category, price=instance.price, quantity=instance.quantity, description=instance.description, image=instance.image) models class Archive(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) title = models.CharField(blank=True, null=True, max_length = 100) category = models.CharField(blank=True, null=True, max_length = 3) price = models.FloatField(blank=True, null=True) quantity = models.IntegerField(blank=True, null=True) description = models.TextField(blank=True, null=True, max_length = 1000) posted = models.DateTimeField(blank=True, null=True) image = models.ImageField(blank=True, upload_to="advert_images") apps.py class CoreConfig(AppConfig): name = 'core' def ready(self): import core.signals -
How to create a form for dealing with multiple django model objects
So I have a model Post with the following definition: class Post(models.Model): post_body = models.TextField() user = models.ForeignKey( to=User, on_delete=models.CASCADE ) published = models.BooleanField( default=False ) schedule = models.DateTimeField( default=timezone.now ) I have created a form in HTML template allowing the user to select the posts he want to send to another website or social media account. Like so: <form> <table class="table table-hover"> <thead> <tr> <th scope="col">Select</th> <th scope="col">Post Body</th> <th scope="col">Published?</th> <th scope="col">Schedule (Editable)</th> </tr> </thead> <tbody> {% for post in posts %} <tr> <td> <div class="form-group"> <input type="checkbox" value="{{ post.id }}"> </div> </td> <td>{{ post.post_body }}</td> <td>{{ post.published }}</td> <td> <div class="form-group"> <input type="datetime-local" class="form-control" name="schedule" value="{{ post.schedule|date:"Y-m-d\TH:i" }}"> </div> </td> </tr> {% endfor %} </tbody> </table> <button class="btn btn-primary" type="submit">Post</button> </form> I want to create a Form in the forms.py in order to process this information (i.e. know which all posts were selected) and then perform further actions (calling other APIs in order to publish these to other sites), also since the field schedule is editable, I want to be able to save that as well. Please help as I cannot think of a possible form for this. -
Inherit models whith seperate primary key in django model
I have a abstract model which I want all of my models inherit from it: from django.db import models class Audit(models.Model): create_date = models.DateTimeField(auto_now_add=True) last_modify_date = models.DateTimeField(auto_now=True) create_by = models.CharField(null=True, max_length=50) last_modify_by = models.CharField(null=True, max_length=50) class Meta: abstract: True now fro example I have two models: from general.AuditableModel import Audit class Province(Audit): name = models.CharField(max_length=30) class Meta: db_table = 'province_v2' verbose_name_plural = _('provinces') verbose_name = _('province') class City(Audit): province_id = models.ForeignKey('address.Province', on_delete=models.CASCADE, related_name='cities') name = models.CharField(max_length=30) class Meta: db_table = 'city_v2' verbose_name_plural = _('cities') verbose_name = _('city') in my database it makes tables like this: create table province_v2 ( audit_ptr_id integer not null primary key references general_audit deferrable initially deferred, name varchar(30) not null ); create table city_v2 ( audit_ptr_id integer not null primary key references general_audit deferrable initially deferred, name varchar(30) not null, province_id_id integer not null references province_v2 deferrable initially deferred ); create index city_v2_province_id_id_12975070 on city_v2 (province_id_id); but I want my models have independent id integer primary key without abstract table, now it made general_audit table -
Django - 'WSGIRequest' object has no attribute 'get' when rendering the form
I'm working on a question management system. I have two different types of questions which make things a little more complicated. I have a page where every question is listed and I'm making the question detail page. When I access this page, I have this 'WSGIRequest' object has no attribute 'get' error. My models : import uuid from django.db import models from django.contrib.auth.models import User class Question_Num(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) num_question = models.IntegerField(default=0) question = models.TextField(max_length=1000, unique=True) reponse = models.IntegerField(default=0) class Meta: verbose_name = 'Question' verbose_name_plural = 'Questions' def __str__(self): return f'Question n°{self.num_question}' class QCM(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) num_question = models.IntegerField(default=0) question = models.TextField(max_length=1000, unique=True) choix_1 = models.CharField(max_length=200, unique=True, default='') choix_2 = models.CharField(max_length=200, unique=True, default='') choix_3 = models.CharField(max_length=200, unique=True, default='') choix_4 = models.CharField(max_length=200, unique=True, default='') class Meta: verbose_name = 'QCM' verbose_name_plural = 'QCM' def __str__(self): return f'QCM n°{self.num_question}' My forms : from django import forms from django.contrib.auth.models import User from .models import Question_Num, QCM class Modif_QCM(forms.ModelForm): num_question = forms.IntegerField( initial = QCM.num_question ) question = forms.IntegerField( initial = QCM.question ) choix_1 = forms.IntegerField( initial = QCM.choix_1 ) choix_2 = forms.IntegerField( initial = QCM.choix_2 ) choix_3 = forms.IntegerField( initial = QCM.choix_3 ) choix_4 = forms.IntegerField( initial = … -
I'm Working on a django project where i extended the auth_user table for add the operators and this will give an error
MY HTML CODE === This is my html code for adding the operator in the database {% extends 'Adminside/master.html' %} {% block content %} <div class="col-md-12"> <!-- general form elements --> <div class="card card-primary"> <div class="card-header"> <h3 class="card-title">Add Operator</h3> </div> <!-- /.card-header --> <!-- form start --> <form role="form" action="{% url 'addoperator' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="card-body"> <div class="form-group"> <label for="exampleInputEmail1">Name</label> <input type="text" class="form-control" id="exampleInputname" name="name" placeholder="Enter Your Name"> </div> <div class="form-group"> <label for="exampleInputEmail1">Email address</label> <input type="email" class="form-control" id="exampleInputEmail1" name="email" placeholder="Enter email"> </div> <div class="form-group"> <label for="exampleInputPassword1">Password</label> <input type="password" class="form-control" id="exampleInputPassword1" name="password" placeholder="Password"> </div> <div class="form-group"> <label for="exampleInputEmail1">Address</label> <input type="text" class="form-control" id="exampleInputaddress" name="address" placeholder="Enter Your Address"> </div> <div class="form-group"> <label for="exampleInputEmail1">Phone Number</label> <input type="text" class="form-control" id="exampleInputnumber" name="number" placeholder="Enter Your Phone Number"> </div> <div class="col-sm-6"> <!-- radio --> <div class="form-group clearfix"> <div class="icheck-primary d-inline"> <input type="radio" id="radioPrimary1" name="gender" value="Male" checked=""> <label for="radioPrimary1"> Male </label> </div> <div class="icheck-primary d-inline"> <input type="radio" id="radioPrimary2" value="Female" name="gender"> <label for="radioPrimary2"> Female </label> </div> <div class="icheck-primary d-inline"> <input type="radio" id="radioPrimary3" disabled=""> Gender </label> </div> </div> </div> <div class="form-group"> <label for="exampleInputFile">Image Upload</label> <div class="input-group"> <div class="custom-file"> <input type="file" name="userimage" class="form-control" required> </div> </div> </div> <div class="form-group"> <label for="exampleInputFile">Document Upload</label> <div class="input-group"> <div class="custom-file"> <input type="file" … -
Remove title of the data from Django Rest Frame
I have this models.py class Topologies(models.Model): topology = models.CharField(max_length=50) component = models.CharField(max_length=50) latency = models.FloatField() capacity = models.FloatField() time = models.CharField(blank=True, max_length=10) def __str__(self): return self.topology And this serializers.py class Last10TopoTime(serializers.ModelSerializer): class Meta: model = models.Topologies fields = ('latency', 'capacity') The output is this: [ { "latency": 19.218, "capacity": 0.048 }, { "latency": 19.218, "capacity": 0.054 }, { "latency": 19.219, "capacity": 0.054 } ] But I only want this [ { 19.218, 0.048 }, { 19.218, 0.054 }, { 19.219, 0.054 }, I don't have any articles on this can anyone suggest anyway show that I can do it. -
How to get the data from BoundField?
I would like to get the number 2 from my BoundField object, that's problematic because it is not iterable or doesnt support indexing. <BoundField value=2 errors=None> Can someone please help? -
Searching through a ManyToManyField in Django
I have a model that contains a ManyToManyField. It looks like this.. applicable_events = models.ManyToManyField(Event) I am trying to basically search using something like this: if 'Video' in prop.applicable_events.all(): print("here") But it isn't fully working as I expected. I want it to search that applicable_event (which is another model). The applicable_event model contains a field named 'name' which I am trying to search against. If I do something like this print(prop.applicable_events.all().filter(name=cur_event)) It prints <QuerySet [<Event: Video Sign In Started>]> So basically I am trying to find out if the string 'Video' is contained in that. -
Unexpected Behaviour of PasswordResetView which sends too many consecutive emails
My Django 3.0 Project is using the default Django Reset Password view, so in my url.py: path('password_reset', auth_views.PasswordResetView.as_view(), name='password_reset') There is a strange behaviour because when I request reseting the password, the view sends a lot of emails to the email address I introduced (let´s say 37 emails). This happened regardless using SendGrid or AWS SES, so something wrong is happening in the view. I investigated and I think the problem is in the PasswordResetForm class which the view uses to send emails. Such form has a get_users() method, which return matching user(s) who should receive a reset, it retrieves all the active users who provided the email. def get_users(self, email): """Given an email, return matching user(s) who should receive a reset. This allows subclasses to more easily customize the default policies that prevent inactive users and users with unusable passwords from resetting their password. """ email_field_name = UserModel.get_email_field_name() active_users = UserModel._default_manager.filter(**{ '%s__iexact' % email_field_name: email, 'is_active': True, }) return ( u for u in active_users if u.has_usable_password() and _unicode_ci_compare(email, getattr(u, email_field_name)) ) The save() method of the form sends an email to each of the users returned by get_users(). I think my problem is that I registered several users … -
change the language attrib in HTML tag based on user's language Django Wagtail
how to change the language attribute <html class="no-js" lang="en"> in HTML tag based on user's language dynamically? in .. Django & #Wagtail templates -
Django 3 - What is the method for creating list and Django detail view urls with stub or slug of name and not int of pk?
In Django 3 what is the correct method for creating list and detail view with friendly urls with either a stub or slug of name and not a int of pk? stub versus slug for list and detail view I want to be able to use list and detail view with a readable urls more friendly then number or int? I tried a variety of tutorials but they all seam to use different methods like url, path, re path, include, reverse, reverse lazy etc. I have been able to do using urls patterns something like this but is the int method r'^starwars/(?P<pk>\d+)$' I am trying to do something like this. it will be using a template inheriting from a base template for both list and detail views. ``` http://127.0.0.1:8000/ #as homepage http://127.0.0.1:8000/starwars/ #as list of series http://127.0.0.1:8000/starwars/the_mandalorian/ # page is detailed view with list of the mandalorian characters ``` Instead of http://127.0.0.1:8000/ #as homepage http://127.0.0.1:8000/starwars/ #as list of series http://127.0.0.1:8000/starwars/1/ path to templates Project_folder |_ starwars |_ templates |_ starwars |_ starwars_base.html starwars_detail.html starwars_list.html ------ Settings.py ------- I add the template directories here like this in two places # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = … -
django : url change depends on model exist
I'd like to make user access to page depends on model exist. and I use CBV. Do I have to control views? or urls? Is FBV only way to control url? How can I control user access url? hope kindly help me. i'd like to control for example:(as you know, this is invalid syntax. hope you know what i'm saying.) from django.urls import path from . import views, models app_name = "papers" urlpatterns = [ path( "memberagreement/<int:preassociation_pk>/", {% if models.MemberAgreement.association.get(pk=preassociaion_pk) is not NULL %} views.member_agreement_detail_vc.as_view(), {% else %} views.member_agreement_create_vc.as_view(), {% endif %} name="member_agreement_vc", ) ] -
Django 3.0 images: Unable to display images in template
I have model named Book in models.py file. And based on this model, a view has been created to display images as products. Which renders books(products) on shop.html template. Problem is that i am unable to get their cover images which are saved across each publishers id who is seller of those books. This is code of shop.html (in which i am trying to display image). <div class="container mt-4"> <div class="row"> {% for b in books|slice:":10" %} <div class="col-lg-2 col-md-3 col-sm-4"> <div class="book-card"> <div class="book-card__book-front"> <img src={{MEDIA_URL}}{{b.cover.url}} alt="book-image"> </div> </div> <div class="book-card__title"> {{ b.title }} </div> </div> </div> </div> {% endfor %} </div> </div> This is the model in which i am putting covers of books against publisher's ids (names) def book_cover_path(instance, filename): return os.path.join( "covers", instance.publisher.user.username, str( instance.pk) + '.' + filename.split('.')[-1] ) class Book(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField('Title', max_length=255) authors = models.ManyToManyField(Author, related_name='books_written') publisher = models.ForeignKey(Publisher, on_delete=models.DO_NOTHING, related_name='books_published') price = models.DecimalField('Price', decimal_places=2, max_digits=10) description = models.TextField('Description') upload_timestamp = models.DateTimeField('Uploading DateTime', auto_now_add=True) categories = models.ManyToManyField(Category, related_name='book_category') cover = models.ImageField(upload_to=book_cover_path, null=True,blank=True) class Meta: unique_together = ('title', 'publisher') get_latest_by = '-upload_timestamp' This is view in views.py def shop(req): bookz = Book.objects.order_by('title') var = {'books': bookz, 'range': 10} … -
ModelChoiceFilter is throwing error in Django
I have following Filter class. class CallSummaryFilterSet(filters.FilterSet): ringing_mobile_number = filters.ModelChoiceFilter(queryset=CallSummary.objects.all(),method='filter_mobile_number') class Meta: model = CallSummary fields = ('caller', 'callee') def filter_mobile_number(self, queryset, name, value): queryset = queryset.filter(Q(caller=value) | Q(callee=value)) return queryset Request Format :- http://127.0.0.1:8000/call-summaries/?ringing_mobile_number=1234567890 it's throwing following error. {'ringing_mobile_number': [ErrorDetail(string='Select a valid choice. That choice is not one of the available choices.', code='invalid_choice')]} -
applying google-oauth2 in django
i am trying to use google auth2 and is struck at the type of request the function is demanding in django i.e try: # Specify the CLIENT_ID of the app that accesses the backend: idinfo = id_token.verify_oauth2_token(token, requests.Request(), CLIENT_ID) # Or, if multiple clients access the backend server: # idinfo = id_token.verify_oauth2_token(token, requests.Request()) # if idinfo['aud'] not in [CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]: # raise ValueError('Could not verify audience.') if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']: raise ValueError('Wrong issuer.') # If auth request is from a G Suite domain: # if idinfo['hd'] != GSUITE_DOMAIN_NAME: # raise ValueError('Wrong hosted domain.') # ID token is valid. Get the user's Google Account ID from the decoded token. userid = idinfo['sub'] this is from the https://developers.google.com/identity/sign-in/web/backend-auth where request is from the following function var xhr = new XMLHttpRequest(); xhr.open('POST', 'https://yourbackend.example.com/tokensignin'); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function() { console.log('Signed in as: ' + xhr.responseText); }; xhr.send('idtoken=' + id_token); shall i pass it directly or just the token value -
Accessing a property coming from manytomany field
This is my models.py: class Role(models.Model): type= models.CharField(max_length=30) class Profile(models.Model): role = models.ManyToManyField(Role, blank=True) def is_composer(self): return self.role['Composer'] This is my view.py: from .models import Profile, Role def profiles_filtered(request, type): model = Profile if type == 'composers': queryset = Profile.objects.filter(is_composer = True) My urls.py: urlpatterns = [ path('profiles/<str:type>/', views.profiles_filtered, name="profiles"), ] And my template: <li><a href="{% url 'profiles' 'composers' %}"> Composers</a></li> When I click on the link, I get to /profiles/composers/, which should list all the profiles containing the role 'Composer'. I get a FieldError at /profiles/composers/ Cannot resolve keyword 'is_composer' into field. The Role type contains many roles, one of which is 'Composer'. How can I list only the profiles which contain a 'Composer' role? -
django Error: AttributeError: 'ModelFormOptions' object has no attribute 'private_fields'
I have two tables 1. intake request (this table has a field that should be shown as drop down values from the 2nd table) 2. drop down list (this table contains the list of values for all sorts of fields. Which is what I want to show as drop down in various forms) List Category List Of Value Choices technology_used spark technology_used oracle country USA country Canada So for a technology_used in intake request I need to show only spark and oracle in drop down For country field in intake request I need to show only USA and Canada **models.py** class DropDownList(models.Model): list_category = models.CharField(max_length=20) list_value = models.CharField(max_length=50) def __str__(self): return self.list_value class Meta: managed = True db_table = 'domain_DropDownList' class DatastoreIntakeRequest(models.Model): user = models.ForeignKey(User, default=1, on_delete=models.CASCADE) technology_used = models.ForeignKey(DropDownList, default=1, on_delete=models.SET_NULL, null=True) def __str__(self): return self.therapeutic_area def get_absolute_url(self): return reverse('domain:intake_detail', kwargs={'pk': self.pk}) #excluding country class here **forms.py** class DatastoreIntakeRequestForm(forms.ModelForm): class Meta: model = DatastoreIntakeRequest fields = ['technology_used',] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['technology_used'].queryset = DropDownList.objects.none() if 'technology_used' in self.data: try: list_cat = 'technology_used' self.fields['technology_used'].queryset = DropDownList.objects.filter(list_category=list_cat).order_by('list_value') except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty City queryset **views.py** class DatastoreIntakeRequestCreateView(CreateView): form_class = … -
Why do I get TemplateDoesNotExist for only 1 template?
I have a form I would like to display on a html template named query_page.html but I keep getting the TemplateDoesNot exist error even though I have the template. I don't think it is related to my settings.py as my 10 other templates work perfectly. I think it might be related to how I am mapping in urls.py class QueryView(FormView): form_class = QueryForm template_name = 'query_page.html' def form_valid(self, form): print(form.cleaned_data) return super().form_valid(form) urlpatterns = [ path('', views.index, name='index'), path('patient_new/', views.patient_new, name='patient_new'), path('location_new/', views.location_new, name='location_new'), path('location_list/', views.location_temps, name='location_list'), re_path('patient/(?P<pk>\d+)$', views.PatientDetailView.as_view(), name='patient_detail'), re_path('location/(?P<pk>\d+)$', views.LocationDetailView.as_view(), name='location_detail'), re_path('patient/(?P<pk>\d+)/edit/$', views.PatientUpdateView.as_view(), name='patient_edit'), re_path('my_form/$', require_POST(views.MyFormView.as_view()), name='my_form_view_url'), re_path('patient/(?P<pk>\d+)/remove/$', views.PatientDeleteView.as_view(), name='patient_remove'), #re_path('patient/(?P<pk>\d+)/query/$', views.profile_search, name='query'), re_path('patient/(?P<pk>\d+)/query/$', views.QueryView.as_view(), name='query'), re_path('location/(?P<pk>\d+)/edit/$', views.LocationUpdateView.as_view(), name='location_edit'), re_path('location/(?P<pk>\d+)/remove/$', views.LocationDeleteView.as_view(), name='location_remove'), ] it is this line: re_path('patient/(?P<pk>\d+)/query/$', views.QueryView.as_view(), name='query') Link to the form: <p><a class="btn btn-primary" href="{% url 'query' pk=patient.pk %}">Query</a></p>