Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.db.utils.IntegrityError: NOT NULL contraint failed: appname_modelName.id
I am creating a client management system in django. I have two models called 'Client' and 'Installment'. my 'models.py' file is given below: models.py from django.db import models from django.utils import timezone from django.urls import reverse # Create your models here. class Client(models.Model): name = models.CharField(max_length = 100) dob = models.SlugField(max_length = 100) CNIC = models.SlugField(max_length = 100) property_type = models.CharField(max_length = 100) down_payment = models.IntegerField() date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.name def get_absolute_url(self): return reverse('client_details',kwargs={ 'pk' : self.pk}) class Installment(models.Model): client = models.ForeignKey(Client, blank=True, on_delete=models.CASCADE) installment_month = models.CharField(max_length = 100) installment_amount = models.IntegerField() installment_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.installment_month def get_absolute_url(self): return reverse('installment_confirmation') I am using ForeignKey in the installment model to link the Client model to it, because one client can have multiple installments. When I RUN the following two commands python manage.py makemigrations python manage.py migrate I didn't get any error. Then I RUN the server using: python manage.py runserver and it runs successfully. Then I add a new client in My app that uses client model. But when I want to add installment to the client, is takes input from the user in the fields (installment_month and installment_month), and when I click 'add installment', … -
Why isint opening a text file giving me desired output?
I have a text file that I opened in python, but the output is completely different. I think this is hex. Here's my code: python: class myClass: ... with open("token.txt", "r") as f: self.token = f.read() print(self.token) ... token.txt (inside of working directory) Here's my output("there's no error"): ÿþ1\x006\x00b\x004\x001\x005\x004\x00e\x009\x00f\x00c\x006\x00a\x00a\x00c\x00e\x006\x009\x001\x007\x00d\x00d\x004\x004\x009\x00c\x00f\x00b\x006\x002\x005\x000\x00b\x005\x002\x008\x003\x008\x005\x00a\x00 PS: I doubt this will help but I'm using django and the token is for github. -
How does the value attribute of HTML <input> tag work?
I new to programming and I am reading this django book and it says that in the template that codes for login page, the value attribute of input can redirect the user to the main page after the user log in successfully. When I want to find out more I see the HTML documentation but it says the value attribute accepts data to be submited to the server however it does not say how it causes a redirect in the URL. May I please know how does the value attribute cause a redirect to the URL? I added the Django tag but I am not sure if it’s a django question. -
DRF Custom Pagination not working properly
Recently I was working with drf pagination class,PageNumberPagination.I may or may not have encountered a weird bug . The official docs mention,to overide the page size of PageNumberPagination we have to create a Custom paginator which overides the page size configuration like shown below class StandardResultsSetPagination(PageNumberPagination): page_size = 100 page_size_query_param = 'page_size' max_page_size = 1000 class BillingRecordsView(generics.ListAPIView): queryset = Billing.objects.all() serializer_class = BillingRecordsSerializer pagination_class = LargeResultsSetPagination But when I tried to do the same the custom paginator was using the default setting as 100 Here's my snippet I used class StandardResultsSetPagination(PageNumberPagination): page_size = 10 page_size_query_param = 'page_size' max_page_size = 100 class TrendingClassesView(ListAPIView): pagination_class = StandardResultsSetPagination serializer_class = BaseClassTileSerializer queryset = BaseClass.objects.all() One moment the code the working fine but after playing around with the page size for some time the paginator just stopped working, I have to do something like below to make the page size working class StandardResultsSetPagination(PageNumberPagination): page_size = 10 page_size_query_param = 'page_size' max_page_size = 100 def get_page_size(self, request): return 10 This is my rest framework settings REST_FRAMEWORK = { 'UPLOADED_FILES_USE_URL': True, 'DEFAULT_PARSER_CLASSES': [ 'rest_framework.parsers.JSONParser', 'rest_framework.parsers.MultiPartParser', 'rest_framework.parsers.FileUploadParser', 'rest_framework.parsers.FormParser', ], "TIME_FORMAT": "%I:%M %p", "TIME_INPUT_FORMATS": ["%I:%M %p", "%H:%M"], } I guess I may be doing something wrong but I am … -
Can't load static files in Django with right setting
Can't load static files from app called 'gameMuster' even if I'm sure everything is okey with settings.py. Project structure Statics confs Installed apps -
why am i getting this error "expected string or bytes-like object"
I am creating a youtube video downloader with Django and bootstrap but when I try to get the youtube video link and redirect to the download page, I get the error "expected string or bytes-like object" below are my HTML and views.py code views.py from django.shortcuts import render from pytube import YouTube def youtubedownloader(request): return render(request, 'youtube_downloader.html') def download(request): url = request.GET.get('url') yt = YouTube(url) video = yt.streams print(video) return render(request, 'download.html') youtube_downloader.html {% extends 'base.html' %} {% block content %} <div class="mt-5"> <center><h1>Download Youtube Video</h1></center> </div> <div class="container mt-5"> <form method="GET" action="download/"> <div class="form-group align-items-center"> <div class="col-auto"> <label class="sr-only" for="inlineFormInput"></label> <input name="url" type="text" class="form-control mb-2" id="inlineFormInput" placeholder="Paste Youtube link here"> </div> </div> <center> <div class="col-auto"> <button type="submit" class="btn btn-primary mb-2">Go</button> </div> </center> </form> </div> {% endblock content %} -
Error creating a multi-step form using Django session
I'm currently working on building a multi-step registration form in Django. I followed the official documentation which can be seen here. Although the forms do not show any error, the user does not get created. Is there a problem I might be overlooking? def signup_step_one(request): if request.user.is_authenticated: return HttpResponseRedirect(reverse('accounts:personal-signup')) else: if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): # collect form data in step 1 email = form.cleaned_data['email'] password = form.cleaned_data['password1'] # create a session and assign form data variables request.session['email'] = email request.session['password'] = password return render(request, 'personal-signup-step-2.html', context={ 'form': form, "title": _('Create your personal account | Step 1 of 2'), }) else: form = CustomUserCreationForm() return render(request, 'personal-signup-step-1.html', { "title": _('Create your personal account | Step 1 of 2'), 'form': form, }) def signup_step_two(request): # create variables to hold session keys email = request.session['email'] password = request.session['password'] if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.email = email user.set_password(password) user.first_name(form.cleaned_data['first_name']) user.last_name(form.cleaned_data['last_name']) user.save() print('user created') return HttpResponse('New user created') else: form = CustomUserCreationForm() return render(request, 'personal-signup-step-2.html', { "title": _('Create your account | Step 2 of 2'), 'form': form, }) -
Module for pagination in the django framework
I'm writing a web application that uses the google book API to display books that the user searches for. I'm now trying to add pagination to the application, but I'm struggling to find great resources to implement this. I have looked into the Pagination Class, but it seems as it designed to paginate results from a database and not responses from API calls. Do you have any tips or good resources to look into, modules or something that could make it a little bit easier to implement this? Any tips are highly appreciated, Thanks! -
I'm trying to send an email from Django using Gmail SMTP
I've set insecure source ON in my account's setting. Also, this is my settings.py file. Can anybody help me? EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com ' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER =' my email' EMAIL_HOST_PASSWORD = 'my password' and I'm getting this error in terminal when I write this code PS D:\start here\silicium7\config-project> python manage.py sendtestemail atabarzega79@gmail.com Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "D:\start here\silicium7\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "D:\start here\silicium7\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\start here\silicium7\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "D:\start here\silicium7\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "D:\start here\silicium7\lib\site-packages\django\core\management\commands\sendtestemail.py", line 33, in handle recipient_list=kwargs['email'], File "D:\start here\silicium7\lib\site-packages\django\core\mail\__init__.py", line 61, in send_mail return mail.send() File "D:\start here\silicium7\lib\site-packages\django\core\mail\message.py", line 284, in send return self.get_connection(fail_silently).send_messages([self]) File "D:\start here\silicium7\lib\site-packages\django\core\mail\backends\smtp.py", line 102, in send_messages new_conn_created = self.open() File "D:\start here\silicium7\lib\site-packages\django\core\mail\backends\smtp.py", line 62, in open self.connection = self.connection_class(self.host, self.port, **connection_params) File "C:\Users\Ata Barzegar\AppData\Local\Programs\Python\Python37\lib\smtplib.py", line 251, in __init__ (code, msg) = self.connect(host, port) File "C:\Users\Ata Barzegar\AppData\Local\Programs\Python\Python37\lib\smtplib.py", line 336, in connect self.sock = self._get_socket(host, port, self.timeout) File "C:\Users\Ata Barzegar\AppData\Local\Programs\Python\Python37\lib\smtplib.py", line 307, in _get_socket self.source_address) for res in getaddrinfo(host, port, 0, … -
permission to add new user in Django
in localhost/admin there is a button for adding new user(figure 1) and this permission is not for all the users figure 1 how can I add this promotion to other user and make it in another template not have to enter to localhost/adminto add a new user and how can I create this new user without email or password (temporary user) (figure2 figure 2 -
Problem with django server (page not loading)
I am currently using Stripe API to develop my own checkout through python/html in Visual Studio Code. I have successfully run a localhost server and I have a django server up and running. When I press checkout, the screen does not go onto the checkout screen, it just stays on the same screen[enter image description here][1]. I am wondering why this is happening? My code for my checkout page (views.py) is: import json import stripe from django.core.mail import send_mail from django.conf import settings from django.views.generic import TemplateView from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse, HttpResponse from django.views import View from .models import Product stripe.api_key = settings.STRIPE_SECRET_KEY class SuccessView(TemplateView): template_name = "success.html" class CancelView(TemplateView): template_name = "cancel.html" class ProductLandingPageView(TemplateView): template_name = "landing.html" def get_context_data(self, **kwargs): product = Product.objects.get(name="Test Product") context = super(ProductLandingPageView, self).get_context_data(**kwargs) context.update({ "product": product, "STRIPE_PUBLIC_KEY": settings.STRIPE_PUBLIC_KEY }) return context class CreateCheckoutSessionView(View): def post(self, request, *args, **kwargs): product_id = self.kwargs["pk"] product = Product.objects.get(id=product_id) YOUR_DOMAIN = "http://127.0.0.1:8000" checkout_session = stripe.checkout.Session.create( payment_method_types=['card'], line_items=[ { 'price_data': { 'currency': 'usd', 'unit_amount': product.price, 'product_data': { 'name': product.name, # 'images': ['https://i.imgur.com/EHyR2nP.png'], }, }, 'quantity': 1, }, ], metadata={ "product_id": product.id }, mode='payment', success_url=YOUR_DOMAIN + '/success/', cancel_url=YOUR_DOMAIN + '/cancel/', ) return JsonResponse({ 'id': checkout_session.id }) @csrf_exempt … -
Django : Displays "No Value " When trying to fetch checked checkbox without submit using AJAX
i wrote a program using django to retrieve all checked checkbox without submit button by using AJAX , it is not throwing any error , but it displays "NO Value " . Can anyone check and tell me what is the mistake i did . AJAX : <script> $('.form-check-input').change(function(){ // checkbox1 change event var checked_lists = []; $(".form-check-input:checked").each(function() { checked_list.push(this.value); }); var formdata = new FormData(); $.ajax({ formdata.append('checked_list',checked_list) formdata.append('csrfmiddlewaretoken',$('input[type=hidden]').val()); $.ajax({ url:"secondtableonDashboard", //replace with you url method:'POST', data:formdata, enctype: 'application/x-www-form-urlencoded', processData:false, contentType:false, success:function(data){ alert("Display return data"+data) }, error:function(error){ alert(error.error) } }); }); }); </script> Views.py if request.method=='POST': user_list = request.getlist('checked_list') print(user_list) else: print("No Values") html : <td> <div class="form-check form-switch"> <input class="form-check-input" name="Servers[]" value="{{datas.ServerName}}" type="checkbox" id="flexSwitchCheckDefault"> <label class="form-check-label" for="flexSwitchCheckDefault"> </div> </td> -
How can we get the user to add .csv files using django and mongodb?
I'm very new to both Django & MongoDB and I'm trying to make a project which is about NLP. So, at first, we are going to have a web site. It starts with a user login. User can upload .csv files to the web site and we are going to processes and return to the user as a result. We are going to keep the NLP processing codes in docker. For the database, we are using MongoDB and for the backend side, we are using Django. My question is, How am I going to read and store these .csv file data in MongoDB? I know how to upload .csv files into Django. But, I have no idea what I am going to do if the files coming from the user. -
how can I get an id from request.POST of the form that I'm submitting now
I'm building a clinic Management System and in the section that you add a new doctor, I want the admin to be able to add the days that the doctor is available at, so that means the days' field is a list but Django doesn't have a list field in its models so I created CharField-> days days = models.CharField(max_length=200,null=True) and then I've created a multi-select input field inside the form <select name="days" class="form-select" multiple aria-label="multiple select example"> <option value="mon">Mon</option> <option value="sun">sun</option> <option value="wed">wed</option> <option value="etc">etc</option> </select> so I took the Selected data by using this code for i in request.POST.getlist("days"): d= str(i)+" "+d print(d) # result gonna be the days in string value splited by spaces eg : mon sun wed so I can use it later by using split() but the thing is I'm not able to add this data into the form while submitting it so I thought that I can save the form data and then alter the field days like that def add_doctor(request): form = Add_doctorForm() if request.method == "POST": form = Add_doctorForm(request.POST) if form.is_valid(): form.save() d = "" for i in request.POST.getlist("days"): d= str(i)+' '+d print(d) formdata = Doctors.objects.get(id = request.POST.get("id") formdata.days = d … -
how to link two models in one form in CreateView?
There are two models. Attachment must bind to Post. models.py class Post(models.Model): title = models.CharField(verbose_name='Название', max_length=300) slug = models.SlugField(verbose_name='Ссылка', max_length=300, blank=True, db_index=True) category = models.ForeignKey('Category', verbose_name='Категория', on_delete=models.CASCADE) content = models.TextField(verbose_name='Описание') created_by = models.ForeignKey(User, verbose_name='Материал добавил', on_delete=models.SET_DEFAULT, default=1, related_name='post_created_by') updated_by = models.ForeignKey(User, verbose_name='Материал обновил', on_delete=models.SET_DEFAULT, default=1, null=True, related_name='post_updated_by') is_published = models.BooleanField(verbose_name='Опубликовать', default=True) views = models.PositiveIntegerField(verbose_name='Просмотры', default=0, blank=True) time_create = models.DateTimeField(verbose_name='Дата создания', auto_now_add=True) time_update = models.DateTimeField(verbose_name='Дата обновления', auto_now=True) # META author = models.CharField(max_length=255, verbose_name='Автор', blank=True) source = models.URLField(max_length=255, verbose_name='Ссылка на источник', blank=True) def get_absolute_url(self): return reverse('post', kwargs={'cat_slug': self.category.slug, 'slug': self.slug, 'pk': self.pk}) class Attachment(models.Model): post = models.ForeignKey('Post', verbose_name='Прикрепить файл', on_delete=models.SET_NULL, null=True, related_name='post_attachment') link = models.URLField(verbose_name='Основная ссылка', blank=True) meta_link = models.CharField(verbose_name='Информация', max_length=255, blank=True) load = models.PositiveIntegerField(verbose_name='Загрузки', default=0, blank=True) type = models.ManyToManyField('Type', related_name='type_post') version = models.CharField(verbose_name='Версия материала', max_length=255, blank=True) forms.py class PostForm(ModelForm): class Meta: model = Post fields = '__all__' class AttachmentForm(ModelForm): class Meta: model = Attachment fields = '__all__' exclude = ('post',) How to connect them in CreatView in views.py? I just tried different ways, errors came out. I don't understand a little how to make a formsets. -
I am trying make a custom user signup form and getting following error while making this
I am trying to extend the user model from django.db import models # Create your models here. class RegisterUser(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(max_length=50, unique=True) phone_number = models.CharField(max_length=20) sector = models.CharField(max_length=50) and tried to create a form for the signup from django.contrib.auth.forms import UserCreationForm from .models import RegisterUser class CreateUserForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = RegisterUser fields = UserCreationForm.Meta.fields + ('first_name', 'last_name', 'email', 'phone_number', 'sector') ** These are the only changes I made I am getting the following error:** raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (username) specified for RegisterUser -
MultipleObjectsReturned: get() returned more than one Post -- it returned 2
This error only happens if multiple users have the same title for their posts. For example, if john has a page with a title 'mypage' this is the error shown if another user has the same title for their page as john. `MultipleObjectsReturned at /john/mypage/update/` get() returned more than one Post -- it returned 2! but if no one else has it, no error is shown when trying to update the post. class PostUpdateView(LoginRequiredMixin, UpdateView): model = Post form_class = PostForm def form_valid(self, form): form.instance.author = self.request.user ##author = current logged in user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Post success_url = '/' def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False Model class Post(models.Model): title = models.CharField(max_length=100, default=None) slug = AutoSlugField(populate_from='title', null=True) def get_absolute_url(self): return reverse('post-detail', kwargs={'slug': self.slug, 'author': self.author}) urls urlpatterns = [ path('landingpage/new/', PostCreateView.as_view(), name='post-create'), path('<str:author>/<slug:slug>/', PostDetailView.as_view(), name='post-detail'), path('<str:author>/<slug:slug>/update/', PostUpdateView.as_view(), name='post-update'), path('<str:author>/<slug:slug>/delete/', PostDeleteView.as_view(), name='post-delete'), ] + static(settings.M EDIA_URL, document_root=settings.MEDIA_ROOT) -
Can't display SVG images
I can't manage to display and SVG image in an HTML template. I'm working with Django, and this is how my HTML looks like: <svg><use xlink:href="{% static 'user_template_2/assets/test.svg' %}"></use></svg> The path and the filename are correct, I'm loading other static assets using that same directory. I've already added this to my settings file: import mimetypes mimetypes.add_type("image/svg+xml", ".svg", True) mimetypes.add_type("image/svg+xml", ".svgz", True) Any idea what I might be missing? -
Embed Linux screen Terminal in webpage
I am want to embed Linux screen session to embed in django website. Is there is any way to do embed only specific screen in webpage. -
Django tests fails with <model> has not attribute 'object' error
I have the following two models: class Resource(models.Model): identifier = models.UUIDField(default=uuid.uuid4, unique=True) date_added = models.DateTimeField(default=now) def __repr__(self): return f'Resource: {self.identifier}, Time added: {self.date_added}' class URLResource(Resource): url = models.URLField() def __repr__(self): return f'{self.identifier} URL: {self.url}' When I run the following commands in the django shell, everything works fine: > from user_page.models import URLResource > URLResource.objects.create(url='abc') # outputs: `a3157372-7191-4d70-a4b1-c6252a2a139c URL: abc` > URLResource.objects.get(url='abc') # outputs: `a3157372-7191-4d70-a4b1-c6252a2a139c URL: abc` However, my seemingly trivial test case fails, even though the similar execution succeeds in the django shell: from django.test import TestCase from users.models import CustomUser from .models import Resource, URLResource, Record class URLResource(TestCase): def setUp(self): url_resource = URLResource.objects.create(url='abc') print(repr(url_resource)) def test_url(self): print(repr(URLResource.objects.get(url='abc'))) I get the following error: ====================================================================== ERROR: test_url (user_page.tests.URLResource) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/admin/Desktop/readrrr/user_page/tests.py", line 26, in setUp url_resource = URLResource.objects.create(url='abc') AttributeError: type object 'URLResource' has no attribute 'objects' ---------------------------------------------------------------------- -
configuration has an unknown property 'devDependencies'
When I run my django server and try 'npm run dev', it gives me an error stating that there is no property called devDependencies. Is there something wrong with my JSON file? This is my package.json file: { "name": "frontend", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "dev": "webpack --mode development --watch", "build": "webpack --mode production" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "@babel/core": "^7.13.13", "@babel/preset-env": "^7.13.12", "@babel/preset-react": "^7.13.13", "babel-loader": "^8.2.2", "react": "^17.0.2", "react-dom": "^17.0.2", "webpack": "^5.28.0", "webpack-cli": "^4.6.0" }, "dependencies": { "@babel/plugin-proposal-class-properties": "^7.13.0", "@material-ui/core": "^4.11.3", "@material-ui/icons": "^4.11.2", "react-router-dom": "^5.2.0" } } -
Get index info in postgres usin Django ORM
I'm using Postgres with Django and I want to get the info of an index I made on a table, specifically I want to see the size of the index. -
RelatedManager' object has no attribute 'description
I perform request http://167.71.57.114/api2/workout-exercises/3 I want to receive data about WorkoutExercise object number 3 (detail view) Got AttributeError when attempting to get a value for field description on serializer ExerciseSerializer. The serializer field might be named incorrectly and not match any attribute or key on the RelatedManager instance. Original exception text was: 'RelatedManager' object has no attribute 'description'. serializers.py class WorkoutExerciseSerializer(serializers.ModelSerializer): exercises = ExerciseSerializer() class Meta: model = WorkoutExercise fields = ('week', 'exercises') views.py class WorkoutExerciseViewSet(viewsets.ModelViewSet): queryset = WorkoutExercise.objects.all() serializer_class = WorkoutExerciseSerializer http_method_names = ['get', 'post'] models.py class WorkoutExercise(models.Model): workout_program = models.ForeignKey(WorkoutProgram, on_delete=models.CASCADE, related_name='workout_exercises') week = models.PositiveIntegerField(default=1) day = models.PositiveIntegerField(default=1) order = models.PositiveIntegerField(default=1) def save(self, *args, **kwargs): if not self.pk: last_order = WorkoutExercise.objects.all().aggregate(largest=models.Max('order'))['largest'] if last_order is not None: self.order = last_order + 1 return super(WorkoutExercise, self).save(*args, **kwargs) def get_workout_programs(self): return self.workout_program.name def get_exercises(self): pass def __str__(self): return self.workout_program.name class Meta: ordering = ('week', 'day') -
'django.db.models' has no attribute 'StdImageField'
I'm trying to use django-stdimage to resize my picture but i'm getting this error AttributeError: module 'django.db.models' has no attribute 'StdImageField' Model from django.db import models from django.contrib.auth.models import AbstractUser from django.views.generic import TemplateView from django.db.models import Q from cloudinary.models import CloudinaryField from .validators import validate_file_size from stdimage.models import StdImageField class CustomUser(AbstractUser): picture = models.StdImageField(null=True, blank=True, upload_to="images", validators=[validate_file_size], size=(256, 256)) -
How to fetch data from database and show it in bootstrap's modal box ( pop up ) in django respectively?
Technologies I'm using --> Back-end --> Python, Web Framework --> Django, Front-end --> HTML5, CSS3, Bootstrap 4, Database --> SQLite3. What I want --> To display the data of each object in each bootstrap's modal box( popup ). The problem --> Data of the first object is only being shown in all the modal boxes( popups ). Files are as follows: HTML template --> manage_requisition.html 👇 {% extends 'hod_template/base_template.html' %} {% block page_title %} Manage Requisitions {% endblock page_title %} {% block main_content %} <!-- Main content --> <section class="content"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <!-- general form elements --> <div class="card card-primary"> <div class="card-header"> <h3 class="card-title">Manage Requisitions</h3> </div> <!-- /.card-header --> <!-- form start --> <div class="table"> <table class="table"> <tr> <th style="text-align: center;">Action</th> <th>View Requisition</th> </tr> {% for requisition in requisitions %} <tr> <td style="text-align: center; vertical-align: middle;"> {% if requisition.requisition_status == 0 %} <a style="width: 85px;" href="{% url 'supervisor_approve_requisition' requisition_id=requisition.id %}" class="btn btn-success inline" >Approve</a> <a style="width: 85px;" class="btn btn-danger inline" href="{% url 'supervisor_rejected_requisition' requisition_id=requisition.id %}" >Reject</a> {% elif requisition.requisition_status == 1 %} <button class="btn btn-warning" disabled="disabled" data-toggle="modal" data-target="#reply_modal">Approved</button> {% else %} <button class="btn btn-danger" disabled="disabled" data-toggle="modal" data-target="#reply_modal">Rejected</button> {% endif %} </td> <td> <button type="button" class="btn btn-warning" …