I am trying to develop a job portal where people can post jobs. I created a Listview and a DetailView for the application. The list view is working but the content isn't appearing on the details page.
views.py:
from django.shortcuts import render
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from .models import Application_create
# Create your views here.
class AllApps(ListView):
model = Application_create
template_name = 'fundamentals/allapps.html'
ordering = ['-id']
class ApplicationInDetail(DetailView):
model = Application_create
template_name = 'fundamentals/application_detail.html'
urls.py:
from django.urls import path
from .views import AllApps, ApplicationInDetail
urlpatterns = [
path('allappslist', AllApps.as_view(), name='applist'),
path('app_in_detail/<int:pk>', ApplicationInDetail.as_view(), name='application_detail')
]
models.py:
from django.db import models
from django.urls import reverse_lazy
# Create your models here.
class Application_create(models.Model):
application_title = models.CharField(max_length=500, default='')
application_opening = models.DateTimeField(auto_now=True)
application_closing = models.DateField()
application_description = models.TextField(default='')
company_name = models.CharField(max_length=500, default='')
skills_req = models.CharField(max_length=2000, default='')
job_pay = models.IntegerField(default=10000)
freelancing_pay = models.IntegerField(default=10000)
job_type = models.CharField(max_length=500)
def __str__(self):
return self.application_title + self.company_name
def get_absolute_url(self):
return reverse('application_detail', args = [str(self.id)])
base.html:
<html>
<head>
{% load static %}
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<link rel="stylesheet" href="{% static 'css/allappslist.css' %}">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light navbar_custom">
<a class="navbar-brand" href="#">
<img src="{% static 'images/expertoblogo.png' %}" width="40" height="40" alt="">
</a>
<a class="navbar-brand" href="#" >EXPERTOB</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation" style="background-color: white;">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav ml-auto">
<li class="nav-item" style="margin-right: 15px;">
<a class="nav-link" href="#" >Link</a>
</li>
<li class="nav-item" style="margin-right: 15px;">
<a class="nav-link" href="#" >Link</a>
</li>
<li class="nav-item" style="margin-right: 15px;">
<a class="nav-link" href="#" >Link</a>
</li>
</ul>
</nav>
{% block content %}
{% endblock %}
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
</body>
</html>
allapps.html:
{% extends 'fundamentals/base.html' %}
{% block content %}
{% for app in object_list %}
<ul>
<li class="list-group-item app_title" style="margin-left: 30px; margin-bottom: 0px; margin-right:30px; margin-top: 30px; background-color: #007FFF;">
<span style="color:white;"> {{app.application_title}} </span>
</li>
<li class="list-group-item list-group-item-light" style="margin-left: 30px; margin-bottom: 0px; margin-right:30px;">
<p>Company name: <span style="font-weight: bold;">{{app.company_name}} </span> </p>
</li>
<li class="list-group-item list-group-item-light" style="margin-left: 30px; margin-bottom: 0px; margin-right:30px;">
<p> {{app.application_description | slice:"0:200"}} ....... </p>
<p> <button type="button" class="btn btn-primary">View Details</button> </p>
</li>
</ul>
{% endfor %}
{% endblock %}
application_detail.html:
{% extends 'fundamentals/base.html' %}
{% block content %}
<h1> {{app.company_name}} </h1>
{% endblock %}
I've specified the model in views too but the content isn't appearing in the application_detail.html file. I'm using a mongo database which is working as the content is appearing in the allapps.html file. Please help me out
I think you must add context_object_name, change your code like below
class ApplicationInDetail(DetailView):
model = Application_create
template_name = 'fundamentals/application_detail.html'
context_object_name = 'app'
In your list view you have {% for app in object_list %}.
object_list is Django's default naming of the list of objects in your view.
In your detail view you use app, but this should be object as that is Django's default naming of the object in the detail view.
The documentation is here https://docs.djangoproject.com/en/3.1/ref/class-based-views/generic-display/
Related
I am building a website for myself I am updating my projects from django admin I wanted to create a custom field which is a map of choice(tag color) and tag text.
I want to make it look something like this
This is my model
class Project(models.Model):
projectTemplate = CloudinaryField('image')
projectTitle = models.TextField(default="Title ")
desc = models.TextField(default="not mentioned")
projectLink = models.URLField(max_length=200, default="not mentioned")
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f'{self.projectTitle} - {self.desc[:15]} ..'
views.py
def projects(request):
Projects = Project.objects.all()
return render(request, 'devpage/projects.html',{'Projects': Projects})
This is my current DTL
{% for project in Projects %}
<div class="col">
<div class="card shadow-sm">
<img src="{{ project.projectTemplate.url }}" height="225" width="100%">
<div class="card-body">
<h6 class="text-center">
{{ project.projectTitle }}
</h6>
<p class="card-text">{{ project.desc }}</p>
<div class="mb-3">
<span class="badge rounded-pill bg-secondary">Django</span>
<span class="badge rounded-pill bg-success">Python</span>
</div>
<div class="d-flex justify-content-between align-items-center">
<div class="btn-group">
<button type="button" class="btn btn-sm btn-warning btn-outline-secondary"><a
href="{{ project.projectLink }}" target="_blank" type="button"
class="btn">View</a></button>
</div>
<small class="text-muted">{{ project.created_at }}</small>
</div>
</div>
</div>
</div>
{% endfor %}
I want a custom model field which takes choice of label color and corresponding text with dynamic size I tried using json(field name tags) but its not interactive its like {"primary":"django","success":"Python","seconday":"webApp"}
This is JSON DTL
//Inner for loop for tags
<div class="mb-3">
{% for color,text in Project.tags.items %}
<span class="badge rounded-pill bg-{{ color }}">{{ text }}</span>
{% endfor %}
</div>
Assuming you have a Tag model which is a ManyToManyField, you could just store the color as an attribute to the model.
Your model:
class Tag(models.Model):
text = models.CharField(max_length=32)
color = models.CharField(max_length=32, default="bg-success")
class Project(models.Model):
...
tags = models.ManyToManyField(Tag)
Your template:
{% for tag in Project.tags %}
<span class="badge rounded-pill {{ tag.color }}">{{ tag.text }}</span>
{% endfor %}
Some future improvement to this could be a subclass that pre-defines all of the colors.
Cannot assign "'Electronic'": "Product.category" must be a "Category" instance.
File/models.py:
from django.db import models
# Create your models here.
class Category(models.Model):
name = models.CharField(max_length=150, db_index=True)
def __str__(self):
return self.name
class SubCategory(models.Model):
name = models.CharField(max_length=150, db_index=True)
category = models.ForeignKey(Category, related_name='souscatรฉgories', on_delete=models.CASCADE)
def __str__(self):
return self.name
class Product(models.Model):
name = models.CharField(max_length=100, db_index=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
subcategory = models.ForeignKey(SubCategory, on_delete=models.CASCADE)
def __str__(self):
return self.
and business logic code is there....
File/views.py
# from django.urls import reverse_lazy
# from django.views.generic import ListView, CreateView
from django.shortcuts import render
from .models import Product, Category, SubCategory
# Create your views here.
def home(request):
if request.method == "POST":
name = request.POST['name']
subcategory = request.POST['subcategory']
category = request.POST['category']
ins = Product(name=name, subcategory=subcategory, category=category)
ins.save()
data = Product.objects.all()
return render(request, 'mysiteapp/index.html', {'data': data})
and templates is there....
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Hello, world!</title>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="/">Product List </a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="/">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#">Disabled</a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</nav>
<!-- Table -->
<table class="table table-dark">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Product</th>
<th scope="col">Subcategory</th>
<th scope="col">Category</th>
</tr>
</thead>
{% for p in data%}
<tbody>
<tr>
<th scope="row">{{p.id}}</th>
<td>{{p.name}}</td>
<td>{{p.subcategory}}</td>
<td>{{p.category}}</td>
</tr>
{% endfor %}
</tbody>
</table>
<!-- modal -->
<!-- Button trigger modal -->
<h2><a class="btn btn-success" data-toggle="modal" data-target="#exampleModal">
Add Product
</a></h2>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Add Product</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">ร</span>
</button>
</div>
<!-- form -->
<form method="POST">{% csrf_token %}
<div class="form-group row">
<label for="name" class="col-sm-2 col-form-label">Product</label>
<div class="col-sm-8">
<input name="name" type="text" id="name" class="form-control mx-sm-2">
</div>
</div>
<div class="form-group row">
<label for="subcategory" class="col-sm-2 col-form-label">SubCategory</label>
<div class="col-sm-8">
<select name="subcategory" class="custom-select mr-sm-2" id="subcategory">
<option>Choose....</option>
{% for p in data %}
<option>{{p.subcategory}}</option>
{% endfor %}
</select>
</div>
</div>
<div class="form-group row">
<label for="category" class="col-sm-2 col-form-label">Category</label>
<div class="col-sm-8">
<select name="category" class="custom-select mr-sm-2" id="category">
<option>Choose....</option>
{% for p in data %}
<option>{{p.category}}</option>
{% endfor %}
</select>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save changes</button>
</div>
</form>
</div>
</div>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous"></script>
</body>
</html>
and finally error is :
ValueError at /
Cannot assign "'Electronic'": "Product.category" must be a "Category" instance.
please answer me...
You cannot directly pass category from POST data.
Either it needs to be an instance of Category class
category_id = request.POST['category']
#Get category instance
category = Category.objects.get(pk=category_id)
ins = Product(name=name, subcategory=subcategory, category=category)
or you can use the category pk value.
ins = Product(name=name, subcategory=subcategory, category_id=category_id)
I am new to Django. Practicing in a small project in Dango 3.1 I get the error "Method Not Allowed (POST)".
The error appears when a user presses the Guarder (Save) button.
Method Not Allowed: /pizarra/comunicado/
[30/Jul/2021 09:10:03] "POST /pizarra/comunicado/ HTTP/1.1" 405 0
Everything was working before and I can't understand what I'm doing wrong.
Please if someone can help me.
Thanks in advance.
comunicado_form.html
{% extends 'gestion/base_gestion.html' %}
{% block page_content %}
<form method="POST" class="form-group">
{% csrf_token %}
<div class="col-xl-12 col-md-12 mb-12">
{% if obj %}
<div class="card border-left-warning shadow h-100 py-2">
{% else %}
<div class="card border-left-success shadow h-100 py-2">
{% endif %}
<div class="card-body">
<div class="row no-gutters align-items-center">
<div class="col mr-2">
<div class="text-xs font-weight-bold text-success text-uppercase mb-1">
{% if obj %}Editar{% else %}Nuevo{% endif %} Comunicado
</div>
<div class="dropdown-divider"></div>
<div class="col-sm-8">
<div class="col-8">
<div class="form-group">
<label for="id_contenido">Contenido del mensaje:</label>
{{ form.contenido }}
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="id_fecha_vto">Fecha Vto:</label>
{{ form.fecha_vto }}
</div>
</div>
<div class="col-2">
<div class="form-group">
<label for="id_hora_vto">Hora Vto:</label>
{{ form.hora_vto }}
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="id_es_borrador">ยฟEs Borrador?:</label>
{{ form.es_borrador }}
</div>
</div>
<div class="col-2">
<div class="form-group">
<label for="id_es_borrador">Estado:</label>
{{ form.estado }}
</div>
</div>
<!-- {{ form.as_p }} -->
</div>
<div class="dropdown-divider"></div>
<div class="row">
<div class="col">
<button type="submit" class="btn btn-danger"><span class="fa fa-save"></span> Guardar</button>
<span class="fa fa-undo"></span> Cancelar
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
{% endblock page_content %}
{% block js_page %}
<script>
$(function () {
$("#id_fecha_vto").datetimepicker({
format: 'd-m-Y',
timepicker:false
});
});
$(function () {
$("#id_hora_vto").datetimepicker({
format: 'H:i',
datepicker:false
});
});
</script>
{% endblock js_page %}
urls.py in app
from django.contrib import admin
from django.urls import path, include
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from blogapp import views
# agregamos estas dos lineas
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.auth import views as auth_views
urlpatterns = [
path('admin/', admin.site.urls),
path('blogapp/',include(('blogapp.urls','blogapp'), namespace='blogapp')),
path('pizarra/', include(('pizarra.urls','pizarra'), namespace='pizarra')),
path('home',include(('blogapp.urls','home'), namespace='home')),
path('login/',auth_views.LoginView.as_view(template_name='blogapp/login.html'),
name='login'),
path('', views.index),
]
urlpatterns += staticfiles_urlpatterns()
urls.py in pizarra
from django.urls import path
from .views import ComunicadoNew, ComunicadoEdit, ComunicadoDel, ComunicadoView
urlpatterns = [
#-------------------- PIZARRA (Comunicados)---------------------------
path('comunicado/',ComunicadoView.as_view(), name='comunicado_list'),
path('comunicado/new',ComunicadoNew.as_view(), name='comunicado_new'),
path('comunicado/edit/<int:pk>',ComunicadoEdit.as_view(), name='comunicado_edit'),
path('comunicado/delete/<int:pk>',ComunicadoDel.as_view(), name='comunicado_del'),
]
views.py in pizzarra
from django.shortcuts import render, redirect
from django.views import generic
from django.urls import reverse_lazy
from django.contrib.auth.mixins import LoginRequiredMixin
from .models import Comunicado
from .forms import ComunicadoForm
# Create your views here.
class ComunicadoView(LoginRequiredMixin,generic.ListView):
model = Comunicado
template_name = "pizarra/comunicado_list.html"
context_object_name = "obj"
login_url = 'blogapp:login'
class ComunicadoNew(LoginRequiredMixin,generic.CreateView):
model = Comunicado
template_name = "pizarra/comunicado_form.html"
context_object_name = "obj"
form_class=ComunicadoForm
success_url=reverse_lazy("pizarra:comunicado_list")
login_url="blogapp:login"
def form_valid(self, form):
form.instance.uc = self.request.user
return super().form_valid(form)
I have defined the static / js as follows:
<!-- Custom fonts for this template-->
<link href="{% static 'blogapp/vendor/fontawesome-free/css/all.min.css' %}" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet">
<!-- Custom styles for this template-->
<link href="{% static 'blogapp/css/sb-admin-2.min.css' %}" rel="stylesheet">
<!-- Custom styles for this page -->
<link href="{% static 'blogapp/vendor/datatables/dataTables.bootstrap4.min.css' %}" rel="stylesheet">
<!-- jquery-confirm -->
<link href="{% static 'blogapp/vendor/jquery_confirm/jquery-confirm.min.css' %}" rel="stylesheet">
<!-- XDSoft DateTimePicker -->
<!-- <link rel="stylesheet" href="{% static 'blogapp/vendor/jquery-datetimepicker/jquery.datetimepicker.min.css" type="text/css"> -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.20/jquery.datetimepicker.min.css" integrity="sha256-DOS9W6NR+NFe1fUhEE0PGKY/fubbUCnOfTje2JMDw3Y=" crossorigin="anonymous" />
and
<!-- Bootstrap core JavaScript-->
<script src="{% static 'blogapp/vendor/jquery/jquery.min.js' %}"></script>
<script src="{% static 'blogapp/vendor/bootstrap/js/bootstrap.bundle.min.js' %}"></script>
<!-- Core plugin JavaScript-->
<script src="{% static 'blogapp/vendor/jquery-easing/jquery.easing.min.js' %}"></script>
<!-- Custom scripts for all pages-->
<script src="{% static 'blogapp/js/sb-admin-2.min.js' %}"></script>
<!-- Page level plugins -->
<script src="{% static 'blogapp/vendor/datatables/jquery.dataTables.min.js' %}"></script>
<script src="{% static 'blogapp/vendor/datatables/dataTables.bootstrap4.min.js' %}"></script>
<script src="{% static 'blogapp/vendor/jquery_confirm/jquery-confirm.min.js' %}"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.20/jquery.datetimepicker.full.min.js" integrity="sha256-FEqEelWI3WouFOo2VWP/uJfs1y8KJ++FLh2Lbqc8SJk=" crossorigin="anonymous"></script>
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" data-toggle="modal" data-target="#reqModal">
View Requisition
</button>
<div class="modal" id="reqModal" tabindex="-1" aria-labelledby="reqModal" aria-hidden="true">
<div class="modal-dialog modal-dialog-scrollable">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="reqModalTitle">Requisition Details</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">ร</span>
</button>
</div>
<div class="modal-body">
<p><strong>Position Required :</strong> {{ requisition.position_required }}</p>
<p><strong>Requirement :</strong> {{ requisition.requirement }}</p>
<p><strong>Candidate Name :</strong> {{ requisition.candidate_name }}</p>
<p><strong>Department :</strong> {{ requisition.department }}</p>
<p><strong>Post :</strong> {{ requisition.post }}</p>
<p><strong>Requirement Time Period :</strong> {{ requisition.requirement_time_period }}</p>
<p><strong>Work Type :</strong> {{ requisition.work_type }}</p>
<p><strong>Duration Start Date :</strong> {{ requisition.duration_start_date }}</p>
<p><strong>Duration End Date :</strong> {{ requisition.duration_end_date }}</p>
<p><strong>Requisition Reason :</strong> {{ requisition.requisition_reason }}</p>
<p><strong>Minimum Qualification :</strong> {{ requisition.min_qualification }}</p>
<p><strong>Maximum Qualification :</strong> {{ requisition.max_qualification }}</p>
<p><strong>Minimum Experience :</strong> {{ requisition.min_experience }}</p>
<p><strong>Maximum Experience :</strong> {{ requisition.max_experience }}</p>
</div>
<div class="modal-footer">
</div>
</div>
</td>
</tr>
{% endfor %}
</table>
</div>
</div>
<!-- /.card -->
</div>
</div>
</div>
</section>
<!-- Modal -->
<!-- /.content -->
{% endblock main_content %}
Views file --> HODviews.py ๐
def Manage_Requisitions(request):
requisitions = Requisition.objects.all()
context = {"requisitions":requisitions}
return render(request, "hod_template/manage_requisition.html", context)
urls.py file --> urls.py ๐
path("manage_requisition/", HODviews.Manage_Requisitions, name="manage_requisition")
models.py file --> models.py ๐
class Requisition(models.Model):
id = models.AutoField(primary_key=True)
position_required = models.CharField(max_length=2000, default="")
requirement_choices = (
("New", "New"),
("BackFill", "BackFill")
)
requirement = models.CharField(max_length=100, choices=requirement_choices, default="")
candidate_name = models.CharField(max_length=2000, default="")
department = models.CharField(max_length=2000, default="")
post = models.CharField(max_length=2000, default="")
requirement_type = (
("Permanent", "Permanent"),
("Temporary", "Temporary"),
("Fixed Contract", "Fixed Contract")
)
requirement_time_period = models.CharField(max_length=500, choices=requirement_type, default="")
work_type = (
("Full-Time", "Full-Time"),
("Part-Time", "Part-Time")
)
work_type = models.CharField(max_length=500, choices=work_type, default="")
duration_start_date = models.DateField(blank=True)
duration_end_date = models.DateField(blank=True)
requisition_reason = models.TextField()
min_qualification = models.CharField(max_length=1000 ,default="")
max_qualification = models.CharField(max_length=1000 ,default="")
min_experience= models.CharField(max_length=1000 ,default="")
max_experience= models.CharField(max_length=1000 ,default="")
requisition_status = models.IntegerField(default=0)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now_add=True)
objects = models.Manager()
def __str__(self):
return self.candidate_name
Image of the UI ๐
Image of the first pop up ๐
Image of the second popup ๐
I'm getting the data of first objet in each popup. But I want the data of every object to be displayed in each popup.
You can contact me here ๐
Linkedin --> https://www.linkedin.com/in/precioushuzaifa/
Instagram --> https://www.instagram.com/precious_huzaifa/
The problem is all your modals have the same id and so your buttons are just going to open the first modal they find with the ID. You need to add some sort of id to each modal. you can use {{ forloop.counter }} to get the iteration number and attach that to the id.
<button type="button" class="btn btn-warning" data-toggle="modal" data-target="#reqModal-{{ forloop.counter }}">
View Requisition
</button>
<div class="modal" id="reqModal-{{ forloop.counter }}" tabindex="-1" aria-labelledby="reqModal" aria-hidden="true">
View class :
from sqlalchemy import desc
from datamodels.relational_tables import initialize_datamodels
from dataaccess.postgresql.database import (session_scope)
import datamodels.relational_tables
from flask.ext.admin import Admin, BaseView, expose
from akamai_env import get_akamai_config
from flask import request
import json
from sqlalchemy.sql.functions import now
from flask import Flask, redirect, url_for
import logging
_log = logging.getLogger(__name__)
akamai_config = get_akamai_config()
base_url = akamai_config['webserver']['base_url']
class RollBack(BaseView):
#expose('/')
def fetch_healthy_dataset_from_db(self):
initialize_datamodels()
with session_scope() as session:
epd_ip_dataset = datamodels.relational_tables.EpdIpDataset
qry = session.query(epd_ip_dataset).filter_by(dataset_state='healthy').order_by(
desc(epd_ip_dataset.dataset_id)).all()
qry_last = session.query(epd_ip_dataset).filter_by(dataset_state='healthy').order_by(
desc(epd_ip_dataset.dataset_id)).first()
url = url_for('.return_rollback_ui')
url_for('rollback.return_rollback_ui')
return self.render('airflow/base.html',
qry=qry,
dataset_id=qry_last.dataset_id,
base_url=base_url,
url=url)
#expose('/roll', methods=['POST'])
def return_rollback_ui(self):
if request.method == 'POST':
#body_req = request.json
body_req = request.get_data()
_log.error("Body of the request is ", body_req)
#data = json.dumps(body_req)
#self.initalize_db(body_req)
return '<html> <h1> Hi I am sending a response</h1></html>'
def initalize_db(self, body):
dataset_id = body
epdumppushrollback = datamodels.relational_tables.EpdUmpPushRollback
with session_scope() as session:
epdumppushrollback_obj = epdumppushrollback()
epdumppushrollback_obj.dataset_id = dataset_id
epdumppushrollback_obj.record_id = ''
epdumppushrollback_obj.operator_name = ''
epdumppushrollback_obj.activation_flag = 'active'
epdumppushrollback_obj.record_creation_time = now()
epdumppushrollback_obj.start_time = now()
epdumppushrollback_obj.end_time = ''
session.add(epdumppushrollback_obj)
session.flush()
class RollBackResume(BaseView):
# #expose('/')
# def index(self):
# return self.render('airflow/dags.html')
def fetch_audited_dataset_from_db(self):
initialize_datamodels()
with session_scope() as session:
epd_ip_dataset = datamodels.relational_tables.EpdIpDataset
qry = session.query(epd_ip_dataset).filter_by(dataset_state='audited'). \
order_by(desc(epd_ip_dataset.dataset_id)).all()
return qry
#expose('/')
def return_resume_ui(self):
qry = self.fetch_audited_dataset_from_db()
return self.render('airflow/rollback_resume.html',
qry=qry,
base_url=base_url)
#expose('/rollbackresume', methods=['POST'])
def return_rollback_ui(self):
if request.method == 'POST':
body_req = request.json
data = json.dumps(body_req)
def fetch_from_db(self):
dataset_id = None
initialize_datamodels()
with session_scope() as session:
epd_ump_push_rollback = datamodels.relational_tables.EpdUmpPushRollback
qry = session.query(epd_ump_push_rollback).filter_by(activation_flag='active'). \
order_by(desc(epd_ump_push_rollback.dataset_id)).first()
if qry:
dataset_id = qry.dataset_id
return dataset_id
def write_to_db(self):
dataset_id = self.fetch_from_db()
epd_ump_push_rollback = datamodels.relational_tables.EpdUmpPushRollback
with session_scope() as session:
qry = session.query(epd_ump_push_rollback)
for rows in qry:
if rows.dataset_id == dataset_id:
rows.activation_flag = 'inactive'
rows.end_time = now()
session.commit()
session.flush()
break
HTML Page :
<html>
<style>
p
{
opacity: 0;
}
</style>
<head>
<title>Roll back UI</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="{{base_url}}/admin/">Airflow</a>
</div>
<ul class="nav navbar-nav">
<li class="active">DAGs</li>
<li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown" href="#">Data Profiling <span class="caret"></span></a>
<ul class="dropdown-menu">
<li>Ad Hoc query</li>
<li>Charts</li>
<li>Known Events</li>
</ul>
</li>
<li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown" href="#">Browse <span class="caret"></span></a>
<ul class="dropdown-menu">
<li>SLA Instances</li>
<li>Task Instances</li>
<li>Logs</li>
<li>Jobs</li>
<li>DAG Runs</li>
</ul>
</li>
<li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown" href="#">Admin <span class="caret"></span></a>
<ul class="dropdown-menu">
<li>Pools</li>
<li>Configuration</li>
<li>Users</li>
<li>Connections</li>
<li>Variables</li>
<li>XComs</li>
</ul>
</li>
<li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown" href="#">Rollback <span class="caret"></span></a>
<ul class="dropdown-menu">
<li>Rollback </li>
<li>Resume</li>
</ul>
</li>
<li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown" href="#">Docs <span class="caret"></span></a>
<ul class="dropdown-menu">
<li>Documentation</li>
<li>Github</li>
</ul>
</li>
<li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown" href="#">About <span class="caret"></span></a>
<ul class="dropdown-menu">
<li>Version</li>
</ul>
</li>
</ul>
</div>
</nav>
<div class="container">
<h3>RollBack UI</h3>
<table class="table table-bordered">
<thead class="thead-dark">
<tr>
<th scope="col">#</th>
<th scope="col" >Dataset Id</th>
<th scope="col">Dataset State</th>
</tr>
</thead>
<tbody>
{% for i in qry%}
<tr>
<th scope="row"> </th>
<td> {{ i.dataset_id }} </td>
<td> {{ i.dataset_state }} </td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<head>
<div class="container">
<button type="button" class="btn btn-primary" onclick="loadDoc()" id="myBtn"> Rollback to {{dataset_id}} </button>
</div>
<p id="dataset_id"> {{ dataset_id }}</p>
<script>
function loadDoc()
{
document.getElementById("myBtn").disabled = true;
var xhttp = new XMLHttpRequest();
var dataset_id = document.getElementById("dataset_id");
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("POST", "http://localhost:8085/admin/rollback/roll/", true);
xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhttp.send("foo=bar&lorem=ipsum");
}
</script>
</head>
<body>
<h2> Url of the index is {{ url }} </h2>
</body>>
</html>
Explanation of code :
I have class RollBack which returns a table after querying the database, there is a button present on that page; when I click on that button, I want to post some data to an endpoint which I am doing using XMLHttpRequest in the html page.
When I click on that button, the post data is directing me to #expose('/') method instead of #expose('/roll'), since #expose('/') method doesn't support post method it is throwing 405 error. I want my onclick action of button to redirect to #expose('/roll') method.
The reason that your code is throwing a 405 is because you haven't configured your expose function to handle POST methods. The default is to handle only GET as explained in the docs.
Your code logic should look something like the following:
from flask import request
class RollBack(BaseView):
#expose('/', methods=('GET', 'POST'))
def fetch_healthy_dataset_from_db(self):
if request.method == 'POST':
# Anything within this block is processing a POST method
# make sure you eventually return a view
return "Success"
# Anything after this point is processing a GET method