Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Combining multiple Django filters
So I'm struggling with filtering my products in Django. I currently have a search bar which works and the result of submutting a query ('whey' in this case) looks like this: The thing I can't figure out is how to get the sort filter to work now ('Sorteer op:). Because when selecting an option my function in the view gets called, which looks like this: def zoekopdracht(request): if request.GET.get('search') != '': try: search = request.GET.get('search').lower() queryset = models.Product.objects.annotate(search_name=Concat('title', Value(' '), 'categorie', 'brand' , output_field=TextField())) products = queryset.filter(search_name__icontains=search) product_amount = len(products) # sorteer filter filtered = SortFilter( request.GET, queryset=products ) # paginator paginator = Paginator(filtered.qs, 12) page = request.GET.get('page') try: response = paginator.page(page) except PageNotAnInteger: response = paginator.page(1) except EmptyPage: response = paginator.page(paginator.num_pages) product_front_end = { 'final_products': response, 'filter': filtered, 'count': product_amount, } except AttributeError: print(request.GET) response = [] product_front_end = { 'final_products': response, } else: response = [] product_front_end = { 'final_products': response, } return render(request, 'zoekopdracht.html', product_front_end) Because the GET request from the search bar is empty now I lose the products. Is there a way to get the current products back to the view function? That way I can use my SortFilter on the current products. urls.py: urlpatterns … -
Redis is disconnecting in production when using in docker with Django channels
can someone explain what is this error is all about, I am new to Redis and first time I'm using it my websocket connection is rejected by server in the production environment. most of the time it is getting rejected, but one time I got the error like this future: <Task finished name='Task-2137' coro=<Connection.disconnect() done, defined at /usr/local/lib/python3.11/site-packages/redis/asyncio/connection.py:720> exception=RuntimeError('Event loop is closed')> Traceback (most recent call last): File "/usr/local/lib/python3.11/site-packages/redis/asyncio/connection.py", line 729, in disconnect self._writer.close() # type: ignore[union-attr] ^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/asyncio/streams.py", line 344, in close return self._transport.close() ^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/asyncio/selector_events.py", line 839, in close self._loop.call_soon(self._call_connection_lost, None) File "/usr/local/lib/python3.11/asyncio/base_events.py", line 761, in call_soon self._check_closed() File "/usr/local/lib/python3.11/asyncio/base_events.py", line 519, in _check_closed raise RuntimeError('Event loop is closed') in the ubuntu server my Dockerfile looks like this FROM python:3.11.1 RUN apt-get update \ && apt-get install -y --no-install-recommends \ postgresql-client \ && rm -rf /var/lib/apt/lists/* WORKDIR /usr/src/app COPY requirements.txt ./ RUN pip install -r requirements.txt COPY . . EXPOSE 8000 CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] my docker-compose.yaml looks like this version: '3' services: db: image: postgres environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=2221 - POSTGRES_DB=social-network volumes: - db-data:/var/lib/postgresql/data/ ports: - "5432" web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - … -
Has anyone come across django here ever come across a site with two members that have different dashboards. E.g footballers and coaches [closed]
A django sites with two members that can register theiself and each has their own dashboard. E. G a footballer and coach. When a footballer or coach login the system dynamically checks and redirects to the right dashboard users register their self. I can't find a tutorial or project that it has been done and most are redirected using Login redirect in settings -
How to create a custom user model with an email and/or a phone number as a login with Django REST framework?
I want to create the custom user model with the email and/or the phone number as a login. I understood how make them separately but how to combine them together? For instance, should i do the same like this but instead of the email the phone number? Managers.py : rom django.contrib.auth.base_user import BaseUserManager from django.utils.translation import ugettext_lazy as _ class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(email, password, **extra_fields) Models.py: from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.translation import ugettext_lazy as _ from .managers import CustomUserManager class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects … -
How to add object level permission on a particular field of a model in Django Rest Framework?
I have a model: class Employee(models.Model): name = models.CharField(max_length=128) nic = models.CharField(max_length=25, unique=True) def __str__(self) -> str: return self.name class Team(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField("Employee") def __str__(self) -> str: return self.name class Standup(models.Model): team = models.ForeignKey("Team", on_delete=models.CASCADE) employee = models.ForeignKey("Employee", on_delete=models.CASCADE) work_done = models.DateTimeField(auto_now=True) This is a viewset: class StandupViewSet(ModelViewSet): serializer_class = serializers.StandupSerializer queryset = Standup.objects.all() When I hit the API to post the data of standup, Standup.employee field should list only that employee who is currently logged in,so that it cannot select other employees. Admin can see all the employees: https://i.stack.imgur.com/sASrq.png Do I need to apply object level permission? How to do it? -
I am not getting my full payload in my Jac program when it is forwarded from Django
When my Django program receives a post request, it extracts the necessary information and forwards it to my Jac Application. But my Jac program is not receiving the full payload. [The payload I received in my Jac application] (https://i.stack.imgur.com/hUTCH.png)[Some of the information sent in the payload] (https://i.stack.imgur.com/SdPxF.png) I tried changing the format of the payload, but my Jac application is still not receiving the complete payload. -
ValidationError pass multi level dictionary insted of single dict
Is there a way to raise a ValidationError with nested dict of errors?. For example: raise ValidationError({ "index_errors": {"index1": { "test_con": "Error text example", "test_con2": "Error text example2" }} } I am getting 'ValidationError' object has no attribute 'error_list' -
Change flag icon position django-countries dropdown
I am using the django-countries module to create a country selector in Django, but the flag appears underneath the selection field instead of in it. Flag icon appears underneath selection field This is the code of forms.py: class TweetForm(forms.ModelForm): class Meta: model = TweetSearch fields = ['search_term', 'query_type', 'start_date', 'end_date', 'language', 'country', 'tweet_count'] widgets = {'country': CountrySelectWidget(attrs={'class': 'form-control'}), } How do I change the flag position to inside the selection field? -
WebSocket connection fails Django-channels
I am trying to create a socket-based application using Django-Channels, but I have a problem with connection to the WebSocket. To showcase my problem I created a test project. The error message from the JS Console: WebSocket connection to 'ws://127.0.0.1:8000/' failed: The error appears to happen on the line 25 of the html file, which is creating an instance of a WebSocket() Screenshot of the error Here is the code: # consumers.py import ... class ChatConsumer(AsyncJsonWebsocketConsumer): async def connect(self): self.groupname = 'dashboard' await self.channel_layer.group_add( self.groupname, self.channel_name, ) await self.accept() ... # routing.py import... websocket_urlpatterns = [ path("", ChatConsumer.as_asgi()), ] # views.py import ... def chatPage(request, *args, **kwargs): context = {} return render(request, "chatPage.html", context) # asgi.py import ... os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ChatApp.settings') application = ProtocolTypeRouter( { "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( routing.websocket_urlpatterns ) ) } ) # settings.py ... CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer" } } ... <!--chatPage.html--> ... <script> const chatSocket = new WebSocket("ws://" + window.location.host + "/"); document.querySelector("#id_message_send_input").focus(); document.querySelector("#id_message_send_input").onkeyup = function (e) { if (e.keyCode === 13) { document.querySelector("#id_message_send_button").click(); } }; document.querySelector("#id_message_send_button").onclick = function (e) { const messageInput = document.querySelector( "#id_message_send_input" ).value; chatSocket.send(JSON.stringify({ message: messageInput, username : "{{request.user.username}}"})); }; chatSocket.onmessage = function (e) { const data = JSON.parse(e.data); … -
How to get serializer data before response in DRF ListAPIView to order it by all fields?
I have two models. class Team(models.Model): user = models.ManyToManyField(User, related_name='%(class)s_user') company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='%(class)s_company') is_active = models.BooleanField(default=True) has_user = models.BooleanField(default=False) class Meta: app_label = 'accounts' class TeamTranslation(models.Model): team_name = models.CharField(max_length=100) team_description = models.TextField() team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='%(class)s_team') languages = models.ForeignKey(Languages, on_delete=models.CASCADE, related_name='%(class)s_languages') is_active = models.BooleanField(default=True) This is list view... class teamListView(generics.ListAPIView): search_fields = ['teamtranslation_team__team_name'] filter_backends = (filters.SearchFilter,) serializer_class = teamSerializer pagination_class = StandardResultsSetPagination def get_queryset(self): accessor_id = self.request.user.id queryset = Team.objects.filter(is_active=True).order_by("id") return queryset def post(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def get_serializer_context(self): lang_id = UserProfile.objects.get(user_id=self.request.user.id).languages_id return {"lang_id": lang_id} And this is serializer... class teamSerializer(serializers.ModelSerializer): team_id = serializers.IntegerField(source='id') members_count = serializers.SerializerMethodField() team_description = serializers.SerializerMethodField() team_name = serializers.SerializerMethodField() company_code = serializers.CharField(source='company.company_code') def get_team_description(self, obj): lang_id = self.context.get('lang_id') if TeamTranslation.objects.filter(team_id=obj.id, languages_id=lang_id, is_active=True): return f'{TeamTranslation.objects.get(team_id=obj.id, languages_id=lang_id, is_active=True).team_description}' return f'{""}' def get_team_name(self, obj): lang_id = self.context.get('lang_id') if TeamTranslation.objects.filter(team_id=obj.id, languages_id=lang_id, is_active=True): return f'{TeamTranslation.objects.get(team_id=obj.id, languages_id=lang_id, is_active=True).team_name}' return f'{""}' def get_members_count(self, obj): return len(obj.user.values_list('id', flat=True)) class Meta: model = Team fields = ("team_id", "team_name", "team_description", 'members_count', 'company_id', 'company_code', 'has_user') I try to order my data according to query parameter comes from request. So there is no problem when use order_by clause for Team model fields. The problem starts when try to order TeamTranslation fields. … -
When and where is `Model.blank` checked by DRF?
I have a model class SomeModel(models.Model): emails = ArrayField(models.EmailField(), default=list) And let's say I have the following Serializer of the model: class SomeModelSerializer(serializers.ModelSerializer): class Meta: model = SomeModel fields = ['emails'] The email field is not blank-able, i.e: It's required to set a value for it when submitting a Form of the model, or when saving its Serializer. Everything works as expected. So my understanding is that DRF relies on Django's internal machinery to validate whether emails is missing on the Serializer data or not. But the thing is that I can't find where (and when) this happens. I've found that DRF is not calling the Model's clean() method anymore (link)... So do you have any idea of when and where DRF checks for a field's blank value? Thanks! -
DRF with JS Framework retrieving state from URL and making request gets page not found
I'm new in Django. I worked with PERN and PEAN stack before. So, let's say I have product page which stores page state in a URL, and retrieves it when reloading, then makes request to backend, to "product/getOne". But, this works only for first time when actually gets it from link state. Then, when I reload I'm getting Page Not Found Error, and my URL looks like this. Why current path is matter if my request defined like "product/getOne" in my client? -
Django Rest Framework Image with Bad Request with Axios and Expo
I am trying to upload an image to my Django APÌ through a form in expo, but I keep getting an error 400. it is for a social feed style post with image and text. This is the model: class Post(models.Model): user = models.ForeignKey(User, related_name="post_creator", on_delete=models.CASCADE) text = models.CharField(max_length=900, blank = True, null = True) image = models.ImageField(blank = True, null = True, upload_to = post_directory_path) likes = models.ManyToManyField(User, blank = True) comments = models.ManyToManyField(Comment, blank = True) def __str__(self): return f"{self.user}: {self.text}" The serializer: class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = "__all__" Views.py: (permission_classes is commented for testing purposes) class PostList(generics.ListCreateAPIView): # permission_classes = (IsAuthenticated, ) serializer_class = PostSerializer queryset = Post.objects.all() parser_classes = (MultiPartParser, FormParser) this is my function to the post itself, in Expo: const postData = async () => { try { const formData = new FormData() formData.append('image', image) formData.append('user', 2) // 2 here is just for testing purposes formData.append('text', text) console.log(formData) const resp = await authAxios.post('posts/', formData, { headers: { "Content-Type": "multipart/form-data", }}) console.log(resp.data) setText('') setImage(null) } catch (error) { console.error(error) } } I tried a lot of stuff, but no success, I am using expo-image-picker. Thank you! -
ModuleNotFoundError: No module named 'actstream'
want to setup Mayan-EDMS framework to my laptop I read a lot of document but still I face problem to run this server on my laptop. I need someone who have a good experience and work on this platforms. -
Localhost not connecting with any port on chrome browser
apache is installed .on testing localhost(127.0.0.1) refuse to connect with any port number .Chrome Browser shows connection error. How to open a port number manually for connection with server(apache2 webserver/microsoft iis). firewall is already disabled -
SqlAlchemy AttributeError: 'category' object has no attribute 'subcategories'
I am using python (django) with sqlalchemy. I created these two paintings related to each other. def CreateDynamicSubCategories(): try: category_subcategory = Table('category_subcategory', Base.metadata, Column('category_id', Integer, ForeignKey('category.id')), Column('subcategory_id', Integer, ForeignKey('subcategory.id')), __table_args__ = {'extend_existing': True} ) except Exception as e: GetErrorDetails(e) class Category(Base): __table_args__ = {'extend_existing': True} __tablename__ = 'category' id = Column(Integer, primary_key=True) name = Column(String(250), nullable=False) subcategories = relationship("Subcategory", secondary=category_subcategory, back_populates="categories") products = relationship("Product", back_populates="category") class Subcategory(Base): __table_args__ = {'extend_existing': True} __tablename__ = 'subcategory' id = Column(Integer, primary_key=True) name = Column(String(250), nullable=False) categories = relationship("Category", secondary=category_subcategory, back_populates="subcategories") products = relationship("Product", back_populates="subcategory") The problem is that I wanted to add a new table with the following codes: Session = sessionmaker(bind=engine) session = Session() # Adding category new_category = Category(name="Electronics") session.add(new_category) session.commit() new_subcategory = Subcategory(name="Smartphones") session.add(new_subcategory) session.commit() new_category.subcategories.append(new_subcategory) session.commit() new_subcategory.categories.append(new_category) session.commit() I encounter an error like this: new_category.subcategories.append(new_subcategory) AttributeError: 'category' object has no attribute 'subcategories' What is the problem here? Can someone who knows please help? I continued to get the same mistakes even after the chatgpt help. Can someone who knows the problem say? -
Crispy form is not rendring
Trying to render the form but it renders without crispy tags. I have done installed django-crispy-forms (using pip) added 'CRISPY_TEMPLATE_PACK' to my settings added 'crispy_forms' to my applications load the crispy tag to register.html (using {% load crispy_forms_tags %}) forms.py --------- from django import forms class helomodel(forms.Form): name = forms.CharField() email = forms.EmailField() content = forms.CharField() views.py --------- from django.shortcuts import render from . forms import helomodel def register(response): form = helomodel() return render(response,'main/register.html',{'form':form}) settings.py ----------- INSTALLED_APPS = [ 'main.apps.MainConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', ] CRISPY_TEMPLATE_PACK = 'bootstrap4' Register.html -------------- {% extends 'main/base.html' %} {% load crispy_forms_tags %} {% block content %} <form method="post"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-success">Register</button> </form> {% endblock %} -
What meaning by this self.session?
I know a little about sessions in Django. Do you explain the below line? self.session = request.session common_session = self.session.get(settings.SESSION_ID) What meaning here by self.session this line? -
Django: how to filter by day/month range without setting the year
I have a course Model but want to add a available period date on it, but without concidering the Year. so I can: store 2 dates and wont concidering the years on the Course model or store 4 numbers (from_day, from_month, to_day, to_month) on the Course model First I don't know what is the best solutions (what type of data to store, date or numbers?) Second, I don't know how to filter later with checking the actual date. def get_available_courses(self): from apps.adc.models import Course, MetaEmailTemplate courses = self.account.get_courses().filter( ... ) -
why do I can not output my parsed data in django?
from django.shortcuts import render import requests from bs4 import BeautifulSoup headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'} def index(city): if city.method == 'POST': city = city.replace(" ","+") response = requests.get(f'https://www.google.com/search?q={city}&oq={city}&aqs=chrome.0.35i39l2j0l4j46j69i60.6128j1j7&sourceid=chrome&ie=UTF-8',headers=headers) soup = BeautifulSoup(response.text,'html.parser') data={ 'location': soup.select('#wob_loc')[0].getText().strip(), 'time': soup.select('#wob_dts')[0].getText().strip(), 'info': soup.select('#wob_dc')[0].getText().strip(), 'weather': soup.select('#wob_tm')[0].getText().strip(), } return(data['location']) return(data['time']) return(data['info']) return(data['weather']+"°C") else: data ={} return render(city, "main/index.html", data) I search soulutions for this error -
Test validate_unique raises ValidationError Django forms
I have a ModelForm called SignUpForm located in myproj.accounts.forms SignUpForm overrides Django's validate_unique so that the 'email' field is excluded from 'unique' validation as required by the model's unique=True (this is dealt with later in the view). Everything works as expected. I now want to test the code by raising a ValidationError when self.instance.validate_unique(exclude=exclude) is called. The problem I have is how to use mock to patch the instance.validate_unique so that a ValidationError is raised. ** SignUpForm's validate_unique(self) - myproj.accounts.forms** def validate_unique(self): exclude = self._get_validation_exclusions() exclude.add('email') try: self.instance.validate_unique(exclude=exclude) except forms.ValidationError as e: self._update_errors(e) This test works, but it does not raise the error on the method (validate_unique) and not the instance (self.instance.validate_unique). def test_validate_unique_raises_exception(self): with patch.object(SignUpForm, 'validate_unique') as mock_method: mock_method.side_effect = Exception(ValidationError) data = {"email": 'someone@somewhere.com', 'full_name': A User, "password": "A19A23CD", } form = SignUpForm(data) self.assertRaises(ValidationError) My question is how can I raise a ValidationError using mock when self.instance.validate_unique is called? -
How to count value in Python-Django website
I have the number of sales and the number of returns. I need to display the percentage of non-returned items in safetycoef. For example, there are 500 sales and 100 returns, it must be 80% in 'safetycoef'. Or 1000 sales and 240 returns, it means 76%. How to implement it? html: <div> {% for phone in object_list %} <div class="smartphone" > {% endif %} <p>{{ phone.title }} — reliabilty {{phone.safetycoef }}%</p> <p>Based on {{phone.sales }} sales and {{phone.returns }} returns </p> </div> {% endfor %} </div> -
Django step by step form with multiple ForeingKey fields
I can't make a step-by-step form for filling related models. If you want to suggest FormWizard, I can't figure it out. There are very few examples on the Internet and the examples are too simple. I'm trying to use a user session and save forms gradually class City(models.Model): obl = models.CharField(max_length=255, choices=REGIONS, default="24", verbose_name="Регион") name = models.CharField(max_length=128, verbose_name="Город") population = models.IntegerField() class Address(models.Model): city = models.ForeignKey(City, on_delete=models.PROTECT, verbose_name="Город") street = models.CharField(max_length=255, verbose_name="Улица") numb = models.CharField(max_length=64, verbose_name="Номер дома") class Project(models.Model): manager = models.ForeignKey(User, on_delete=models.PROTECT, verbose_name="Сотрудник") address = models.ForeignKey(Address, on_delete=models.PROTECT, verbose_name="Адрес") # about 30 fields accept = models.DateField(verbose_name="Принят дата", blank=True) class ProjectDetail(models.Model): project = models.OneToOneField(Project, on_delete=models.CASCADE, verbose_name="Проект") img = models.ImageField(upload_to=("%d-%m-%Y/"), verbose_name="Обложка объекта") # about 40 fields lessor = models.CharField(max_length=255, verbose_name="Контактное лицо") lessor_phone = models.PositiveBigIntegerField(verbose_name="Телефон") Forms class AddressForm(forms.ModelForm): class Meta: model = Address fields = ["city", "street", "numb"] def __init__(self, *args, **kwargs): city = kwargs.pop("city", "") super(AddressForm, self).__init__(*args, **kwargs) self.fields["city"] = forms.ModelChoiceField(queryset=City.objects.all()) class ProjectForm(forms.ModelForm): class Meta: model = Project fields = ["file", "sq", "rent_tax"] class ProjectDetailForm(forms.ModelForm): class Meta: model = ProjectDetail exclude = ['project', 'comment', 'resume', 'complite', 'created_at'] Views def step1(request): initial={'fn': request.session.get('fn', None)} print(initial) form = AddressForm(request.POST or None, initial=initial) if request.method == 'POST': if form.is_valid(): request.session['fn'] = form.cleaned_data['fn'] return HttpResponseRedirect(reverse('step2')) return … -
How to get database fields inside a form
What I need? I need to put a form on my page, where all fields from my database are shown, and you can change them and save to database. A simple editor for my database table. What I have? my HTML:enter code here <tr> <td>{{ form.name }}</td> <td>{{ form.token }}</td> <td><button class="btn btn-lg btn-success w-100">Add</button></td> </tr> my models.py from django.db import models # Create your models here. class TrafficSources(models.Model): name = models.CharField('name', max_length=250) token = models.CharField('token', max_length=250) def __str__(self): return self.name my forms.py from .models import TrafficSources from django.forms import ModelForm, TextInput class TrafficSourcesForm(ModelForm): class Meta: model = TrafficSources fields = ['name', 'token'] widgets = { 'name': TextInput(attrs={ 'class': 'form-control', 'placeholder': {{here I need the name from database table}} }), 'token': TextInput(attrs={ 'class': 'form-control', 'placeholder': {{here I need the token from database table}} }) } This is the view.py for that page def settings(request): ts = TrafficSources.objects.all() form = TrafficSourcesForm() data = { 'form': form } url = 'url for API request' # ts_token = TrafficSources.objects.filter(name='propeller') for h in ts_token: token = h.token headers = {'Authorization': 'Bearer ' + token} res = requests.get(url, headers=headers) return render(request, 'mainpage/dashboard.html', {'ts': ts, 'js': res.text, 'hd': headers, 'form' : form}) My questions: 1) I … -
django does not reassign id number to model fields
I created a django model for applicants. i made it in such a way that the admin can delete an applicant's name from the model. But whenever an applicant's name is deleted the IDs remain the same, for exmaple if i delete an applicant with ID number 4 instead of the next applicant's number to become the new 4 it remains 5. here is my code view code: `def delete(request, id): applicant = Applicants.objects.get(id=id) applicant.delete() return HttpResponseRedirect(reverse('applicants_list')) html code: <table border="1" > {% for x in myapplicants %} <tr> <td>{{ x.id }}</td> <td>{{ x.fname }}</td> <td>{{ x.lname }}</td> <td>{{ x.p_course }}</td> <td>{{ x.total_grade }}</td> <td><button><a href="delete/{{ x.id }}" >Reject Application</a></button></td> </tr> {% endfor %} </table>`