Not able to retrieve data from MongoDB using Flask [closed] - mongodb

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 days ago.
Improve this question
I have extablised a successful db connection in flask and trying to display courses in courses.html as follows:
#app.route('/courses')
#app.route('/courses/<term>')
def courses(term = None):
if term == None:
term= 2023
classes = Courses.objects.all()
return render_template('courses.html', coursesData=classes, courses=True, term=term)
The courses class is as follows:
class Courses(db.Document):
courseID=db.StringField(max_length=10, unique=True)
title = db.StringField(max_length=100)
description = db.StringField(max_length=300)
credits = db.IntField()
term=db.StringField(max_length=100)
The courses.html page is as follows:
<table class="table table-hover">
<thead>
<tr>
<th scope="col">Course ID</th>
<th scope="col">Title</th>
<th scope="col">Description</th>
<th scope="col">Credits</th>
<th scope="col">Term</th>
<th scope="col">Enroll</th>
</tr>
</thead>
<tbody>
{% for data in coursesData %}
<tr>
<td scope='row'>{{ data["courseID"] }}</td>
<td>{{ data["title"] }}</td>
<td>{{ data["description"] }}</td>
<td>{{ data["credits"] }}</td>
<td>{{ data["term"] }}</td>
<td>
<form action="{{ url_for('enrollment') }} " , method="POST">
<input type="hidden" name="id" value="{{ data[ 'courseID' ] }}">
<input type="hidden" name="title" value="{{ data[ 'title' ] }}">
<input type="hidden" name="term" value="{{ data[ 'term' ] }}">
<button>Enroll</button>
</form>
</td>
</tr>
{% endfor %}
</tbody>
When i run it, no courses were displayed. Can anyone please help me with this?

Instead of:
classes = Courses.objects.all()
Could you please try:
classes = Courses.query.all()
That is the "legacy query interface", the latest syntax is HERE.

Related

Display data to every <td> from Firestore using Nuxt

how do I want to display those particular values into those particular td tag from a document in Firestore using Nuxt?
I already looking into some of the StackOverflow QnA but have not quite found the answer that I wanted.
Here is the image of the table:
The table
So as you can see I manage to get the document into my app, but I want the data to be on that right column. How I can achieve this?
my HTML part:
<template>
<div id="SubPackageDetailTable">
<h2>Sub-Packages Detail</h2>
<table
items="SubPackagesDetails">
<tr>
<th>Subcontractor</th>
<td>{{ SubPackagesDetails.SubContractorName }}</td>
</tr>
<tr>
<th>WPC</th>
<td>{{ SubPackagesDetails.WorkPackageContractorName }}</td>
</tr>
<tr>
<th>Package</th>
<td>{{ SubPackagesDetails.Package }}</td>
</tr>
<tr>
<th>Sub-Package</th>
<td>{{ SubPackagesDetails.Subwork }}</td>
</tr>
<tr>
<th>Code</th>
<td>{{ SubPackagesDetails.code }}</td>
</tr>
<tr>
<th>Commencement Date</th>
<td>{{ SubPackagesDetails.CommencementDate }}</td>
</tr>
{{ SubPackagesDetails }}
</table>
</div>
</template>
my Script part:
<script>
import firestore from "#/plugins/firebasetest";
export default {
data: () => ({
SubPackagesDetails: [
{
SubContractorName: '',
WorkPackageContractorName: '',
Package: '',
Subwork: '',
code: '',
CommencementDate: '',
}
],
}),
created() {
this.refreshSubPackagesDetails();
},
methods: {
refreshSubPackagesDetails() {
this.SubPackagesDetails = [];
firestore
.collection("subsub")
.get()
.then(querySnapshot => {
querySnapshot.forEach(doc => {
this.SubPackagesDetails.push({ ...doc.data(), id: doc.id });
this.loading = false;
});
console.log(this.SubPackagesDetails);
});
},
},
}
</script>
Thanks to #kissu, using v-for solved the problem. Not sure how to explain how it can work but here is how I do it. I'll put as answer in case if someone had a problem same as me.
<table>
<tr v-for="(subcontractorname, i) in SubPackagesDetails" :key="i">
<th>Subcontractor</th>
<td
>{{ subcontractorname.SubContractorName }}</td>
</tr>
<tr v-for="(workpackagecontractorname, i) in SubPackagesDetails" :key="i">
<th>WPC</th>
<td>{{ workpackagecontractorname.WorkPackageContractorName }}</td>
</tr>
<tr v-for="(packages, i) in SubPackagesDetails" :key="i">
<th>Package</th>
<td>{{ packages.Package }}</td>
</tr>
<tr v-for="(subwork, i) in SubPackagesDetails" :key="i">
<th>Sub-Package</th>
<td>{{ subwork.Subwork }}</td>
</tr>
<tr v-for="(Code, i) in SubPackagesDetails" :key="i">
<th>Code</th>
<td>{{ Code.code }}</td>
</tr>
<tr v-for="(commencementdate, i) in SubPackagesDetails" :key="i">
<th>Commencement Date</th>
<td>{{ commencementdate.CommencementDate }}</td>
</tr>
</table>

I have this code, when submited the form dont refresh, someone know how refresh after submit on october cms?

<form data-request="onSend" data-request-update="'{{ __SELF__}}::attbanco': '#banco' "
data-request-flash >
<table>
<tr>
<td>Nome: </td> <td ><input type="text" id="nome" name="nome"></td>
</tr>
<tr>
<td>Idade: </td> <td ><input type="number" id="idade" name="idade" value="{{usuario.idade}}"></td>
</tr>
<tr>
<td>Telefone: </td> <td ><input type="text" id="telefone" name="telefone" value="{{usuario.telefone}}"></td>
</tr>
</table>
<button type="submit" >Enviar</button>
<input type="hidden" value="{{usuario.id}}" name="id">
this code work, saves the values on database, but i need manually refresh page to see the result on my
screen, someone know how refresh after submit?
Please, explain most simple possible, i am newbie
The best way to do what you want is to put the form in a partial and update it when the form is submitted.
Replace your form with this:
<div id="specialForm">
{% partial __SELF__~"::specialForm" %}
</div>
Create a partial to describe the form; I used specialForm. It should reload the form and clear the content.
<form data-request="onSend" data-request-update="'{{ __SELF__}}::attbanco': '#banco', '{{ __SELF__ }}::specialForm': '#specialForm' "
data-request-flash >
<table>
<tr>
<td>Nome: </td> <td ><input type="text" id="nome" name="nome"></td>
</tr>
<tr>
<td>Idade: </td> <td ><input type="number" id="idade" name="idade" value="{{usuario.idade}}"></td>
</tr>
<tr>
<td>Telefone: </td> <td ><input type="text" id="telefone" name="telefone" value="{{usuario.telefone}}"></td>
</tr>
</table>
<button type="submit" >Enviar</button>
<input type="hidden" value="{{usuario.id}}" name="id">
</form>

Submit button in Symfony view without a reusable form type

In my Controller I have an action:
/**
* #Route("/admin/tour/approve/{id}",name="approve_one_tour")
*/
public function approveOneTourAction($id,Request $request)
{
$tour=$this->getDoctrine()->getRepository('HearWeGoHearWeGoBundle:Tour')->findById($id);
if ($request=='POST')
{
$tour->setStatus(true);
$em=$this->getDoctrine()->getEntityManager();
$em->persist($tour);
$em->flush();
return $this->redirectToRoute('manage_tour');
}
else {
return $this->render('#HearWeGoHearWeGo/Manage/tour/approveonetour.html.twig', array('tour' => $tour));
}
}
In View:
{% extends('admin/admin.html.twig') %}
{% block mainpageheader %}
<h1 class="page-heading">APPROVE TOUR</h1>
{% endblock %}
{% block mainpagecontainerheader %}
<h3 class="block-title">Approve {{ tour.name }}</h3>
{% endblock %}
{% block mainpagecontainer %}
<div class="block">
<div class="block-content">
<table class="table">
<thead>
<tr>
<th class="text-center" style="width: 50px;">#</th>
<th style="width:15%">Name</th>
<th style="width:15%">Company</th>
<th style="width:15%">Destination</th>
<th style="width:20px">Start Date</th>
<th style="width:20px">End Date</th>
<th>Price</th>
<th>Discount</th>
<th style="width:40%">Info</th>
<th style="width:20px">Submission Date</th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center">{{ tour.id }}</td>
<td>{{ tour.name }}</td>
<td>{{ tour.company.name }}</td>
<td>{{ tour.destination.name }}</td>
<td>{{ tour.startdate|date('Y-m-d') }}</td>
<td>{{ tour.enddate|date('Y-m-d') }}</td>
<td>{{ tour.price }}</td>
<td>{{ tour.discount }}</td>
<td>{{ tour.info|raw }}</td>
<td>{{ tour.createdAt|date('Y-m-d') }}</td>
</tr>
</tbody>
</table>
<form action="{{ path('approve_one_tour',{'id':tour.id}) }}" method="POST">
<input type="submit" class="btn btn-primary" value="Approve"/>
</form>
</div>
</div>
{% endblock %}
When the button is clicked, nothing happens
Because I only want to show the data of a Tour entity object, not allow the user to edit it, so I think I needn't create a Form Type that adds editable and reusable attributes. The only thing I need is a button, when I click the button, the only attribute of Tour entity needs changing is status, from false (default) to true. Is there any way? If any, please help fix my code above
First of all use $request->getMethod()== instead of $request if you want to check the request method.
You can create a form with just a submit button like so.
//in your controller
protected function createForm(){
$ff = $this->get('form.factory'); // get the form factory service, or inject it in
$builder = $ff->createBuilder('form');
$builder->add('submit', 'submit');
return $builder->getForm();
}
public function approveOneTourAction(Request $request, $id){
$form = $this->createForm();
$form->handleRequest($request);
if($form->isValid() && $form['submit']->isClicked()){
// ... do what you want with the tour here
}
return $this->render('#HearWeGoHearWeGo/Manage/tour/approveonetour.html.twig', array('tour' => $tour, 'form' => $form->createView()));
}
Then render the form passed as form to your template as explained in Symfony forms Documentation

Submit checkbox values Spring MVC

Maybe this question was asked a lot but not in the same way so here is my problem and I hope someone can help.
After having retrieved some research rows from database and returned the results into a List which I have bound to the my Spring MVC Controller Model:
if(!result.hasErrors())
{
try{
List<Question> questionlist = questionservice.findByCategoryAndLevel(questionform.getCategory(),questionform.getLevel());
model.addAttribute("questionlist",questionlist);
return "addExam";
}catch(NullPointerException e)
{
return "redirect:/admin/addexam";
}
}
Here is my view:
<form:form action="addexam" method="POST" modelAttribute="questionlist">
<table class="table table-striped table-bordered table-hover" id="sample_1">
<thead>
<tr>
<th class="table-checkbox">
<input type="checkbox" class="group-checkable" data-set="#sample_1 .checkboxes"/>
</th>
<th>
Category
</th>
<th>
level
</th>
<th>
Type of question
</th>
<th>
Status
</th>
<th>
</th>
</tr>
</thead>
<tbody>
<c:forEach items="${questionlist}" var="question">
<c:choose>
<c:when test="${question.isVisible()}">
<tr class="odd gradeX">
<td>
<input type="checkbox" class="checkboxes" />
</td>
<td>
${question.category.getCategoryName() }
</td>
<td>
${question.level }
</td>
<c:choose>
<c:when test="${question.isSingleChoiceQuestion() }">
<td>Question à choix unique</td>
</c:when>
<c:otherwise>
<td>Question à choix mutiple</td>
</c:otherwise>
</c:choose>
<td class="center">
<c:choose>
<c:when test="${question.getState() == 'Desactivated'}">
<span class="label label-sm label-default"> Desactivated </span>
</c:when>
<c:when test="${question.getState() == 'Activated'}">
<span class="label label-sm label-success"> Activated </span>
</c:when>
<c:when test="${question.getState() == 'Pending'}">
<span class="label label-sm label-warning"> Pending </span>
</c:when>
</c:choose>
</td>
<td>
View
</td>
</tr>
</c:when>
</c:choose>
</c:forEach>
</tbody>
</table>
</form:form>
Now how do I submit the selected items?
yes i wanted to display the question list and then pick the ones i needed via a checkbox
i created a form, it holds the list of Idquestions
public class checkedquestion {
private List<Long> listIdQuestion ;
//getter & setter
}
then added a path attribute to checkbox like below :
<form:form action="submit" method="POST" modelAttribute="checkedquestion">
// .......
<td>
<form:checkbox value="${question.idQuestion}" path="listIdQuestion"/>
</td>
By submitting the list of id i have the ones i needed :
public String add(#ModelAttribute ("checkedquestion") #Valid CheckedQuestion checkedquestion , BindingResult result )
{
if(!result.hasErrors())
{
List<Long> list = checkedquestion.getListIdQuestion();
List<Question> questionlist = questionservice.getQuestion(list);
}
}
it seems to work fine
Give a id/name to input checkbox type as below
<input type="checkbox" class="checkboxes" id="someId" name="someId" value="uniqueValueToEachCheckBox"/>
Then after submitting your form, you can able to access your selected checkbox values in your controller as below.
request.getParameterValues("someId");

sahi and table operations

For a given table, I'd like to get the below
total number of rows
able to iterate over by row and column
using the Java Driver. I tried the option mentioned here with no luck.
Below is the HTML for table
<div id="hawkMessageCodeTable" class="ui-datatable ui-widget">
<table>
<thead>
<tr>
<th id="hawkMessageCodeTable:j_idt49" class="ui-state-default">
<div class="ui-dt-c">
<span>Code</span>
</div>
</th>
<th id="hawkMessageCodeTable:j_idt51" class="ui-state-default">
<div class="ui-dt-c">
<span>Message</span>
</div>
</th>
</tr>
</thead>
<tbody id="hawkMessageCodeTable_data" class="ui-datatable-data ui-widget-content">
<tr data-ri="0" class="ui-widget-content ui-datatable-even">
<td>
<div class="ui-dt-c">
9005
</div>
</td>
<td>
<div class="ui-dt-c">
Initial Fraud Alert on File
</div>
</td>
</tr>
<tr data-ri="1" class="ui-widget-content ui-datatable-odd">
<td>
<div class="ui-dt-c">
9003
</div>
</td>
<td>
<div class="ui-dt-c">
Security Alert or consumer statement on file relates to true name fraud or credit fraud
</div>
</td>
</tr>
<tr data-ri="2" class="ui-widget-content ui-datatable-even">
<td>
<div class="ui-dt-c">
2501
</div>
</td>
<td>
<div class="ui-dt-c">
Input/File (Current/Previous) Address Has Been Used (#) Times In The Last (30,60,90) Days On Different Inquiries
</div>
</td>
</tr>
<tr data-ri="3" class="ui-widget-content ui-datatable-odd">
<td>
<div class="ui-dt-c">
9004
</div>
</td>
<td>
<div class="ui-dt-c">
Active Duty Alert on File
</div>
</td>
</tr>
</tbody>
</table>
</div>
I have implemented a similar function with sahi for ruby. To answer your questions:
rowLen = table.fetch("rows.length").to_i
Loop through all the cells with:
#browser.cell(table,rowIndex,colIndex).exists?()
You can find the corresponding api for sahi java