I am submitting forms via django forms and I want data to refresh on submit in a certain part of the page (div)
$(function () {
$('#post-form').ajaxForm({
success: function (json) {
console.log(json); // log the returned json to the console
$('#this').append('snippet.html')
console.log("success"); // another sanity check
}
}) });
of an html snippet
<div id="this">
<tr>
<th>ID</th>
<th>Дата</th>
<th>Цена</th>
<th>Откуда</th>
<th>Куда</th>
<th>Водитель</th>
</tr>
{% for item in query_set %}
<tr>
<td>{{ item.id }}</td>
<td>{{ item.date }}</td>
<td>{{ item.price }}</td>
<td>{{ item.des_from }}</td>
<td>{{ item.des_to }}</td>
<td>{{ item.driver }}</td>
</tr>
{% endfor %}
</div>
And here is "views" file
def post(self, request):
csrf_token_value = get_token(self.request)
data = {}
form = SchedForm(request.POST)
if form.is_valid():
obj = form.save()
data['result'] = 'Created!'
data['object'] = {
'price': obj.price,
'driver': obj.driver_id,
'des_from': obj.des_from_id,
'des_to': obj.des_to_id,
'date': obj.date,
}
return JsonResponse(data)
else:
return JsonResponse(form.errors)
The problem is I have a JsonResponse in view's return while on the INTERNET I've read that there are two solutions via render_to_response and render_to_string. But as far as I'm concerned to refresh data in forms you need render_to_string. I just don't see a way to include it in the return with JsonResponse
Related
I'm working on a project which i need to fetch "clients" data on a table.
The data actually comes, but i can't manage to display it. Here's my template part, where i call for info with a v-for.
<tbody>
<tr v-for="item in clients" v-bind:key="item.id">
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
<td>{{ item.email }}</td>
<td>{{ item.documents.cpf || item.documents.cnpj }}</td>
<td>{{ item.documents.celular }}</td>
<td>{{ item.status }}</td>
<td v-if="item.address">
{{ `${item.address.localidade} / ${item.address.uf}` }}
</td>
<td v-else>-</td>
<td>
<a :href="`/ver-cliente/${item.id}`"
></a>
</td>
</tr>
</tbody>
On my DevTools, the data is shown:
Full DevTools with all errors (some of them are from other pages)
My script part:
export default {
data: () => ({
clients: [],
paginationData: {
lastPage: 0,
currentPage: 1,
},
loading: false,
}),
methods: {
getClients(page = 1) {
this.loading = true;
this.$api
.get("/api_v1/clientes", {
params: { page },
})
.then(({ data }) => {
console.log(data);
if (data.success) {
const {
data: result,
per_page,
total,
last_page,
current_page,
} = data.data;
this.clients = result;
this.paginationData = {
perPage: per_page,
total,
lastPage: last_page,
currentPage: current_page,
};
}
})
.finally(() => (this.loading = false));
},
},
mounted() {
this.getClients();
},
};
That' what i managed to do, but it isn't working.
Can anyone give me a hint of what am I doing wrong? Sorry for any rookie mistakes.
It can't find the property cnjp in the item.documents object, so it throws an error. To get rid of that error you can do
item.documents?.cnpj so if the property is not in the object, if will be null instead of throwing an error.
I'm building a component on my project, which is actually getting all the data and console logging it, but here's the problem: Inside my array of clients, i have some objects (address, documents, ...), and i can't manage to call them on my table.
My script:
<script>
export default {
data: () => ({
clients: [],
}),
methods: {
getClients() {
this.$api
.get("/api_v1/clientes", {
})
.then((response) => {
this.clients = response.data[0];
console.log(response.data);
})
.catch((e) => {
console.log(e);
});
},
},
mounted() {
this.getClients();
},
};
</script>
My table (inside ):
<tbody>
<tr v-for="client in clients" v-bind:key="client.id">
<td>{{ client.id }}</td>
<td>{{ client.name }}</td>
<td>{{ client.email }}</td>
<td>{{ client.documents.cpf || client.documents.cnpj }}</td>
<td>{{ client.documents.celular }}</td>
<td>{{ client.status }}</td>
<td v-if="client.address">
{{ `${client.address.localidade} / ${client.address.uf}` }}
</td>
<td v-else>-</td>
<td>
<a :href="`/see-client/${client.id}`"
><i class="icon-magnifier"></i
></a>
<i class="icon-check" style="color: green"></i>
<i class="icon-close" style="color: red"></i>
</td>
</tr>
</tbody>
My controller:
public function index(Request $request)
{
$data = [
'pag' => 'All clients',
'link' => '/'
];
return view('clients.index', $data);
}
The data:
Someone have a clue of a different approach i could have? I'm using Vue2. It's one of my first big projects, so previously sorry for any rookie mistake. Thanks for your time and help!
This line is only getting the first client:
this.clients = response.data[0];
response.data is your array of clients (from the looks of things). When you use .data[0], you're getting the first element of the array (i.e. the first client).
Then, this line is trying to loop over 1 client, not an array of clients.
<tr v-for="client in clients" v-bind:key="client.id">
Try changing
this.clients = response.data[0];
to
this.clients = response.data;
If that doesn't work (it looks like you've got a weird data structure), try this instead:
this.clients = response.data.data;
Or this (it's unclear to me how many nested data properties you have):
this.clients = response.data.data.data;
I just made a quick analysis about your code. I think you should polish it a little bit.
Let me start with a quick catch up:
Update yuor js section with:
<script>
export default {
// Please do use the function format instead of lambda expression, it's recommended in the vue2 docs.
data() {
return {
clients: [],
};
},
methods: {
// Change this to an async method, so you can have more control on your code.
async getClients() {
try {
/**
* Here, you should have to know, that your file `routes/api.php` hass all of the prefixed /api routes
* So you have a direct access to /api prefixed routes
* Additionally read a little bit about destructuring.
*/
const response = await this.$api.get("/api/clientes");
// Now, please notice that you have 2 data path names.
this.clients = response.data.data; // {or please follow the correct path to the array container of the clients}.
} catch (e) {
console.log("Check this error: ", e);
}
},
},
// Now, change your mounted to an async method
async mounted() {
// Trust me this is going to work perfectly.
await this.getClients();
},
};
</script>
Now, please, please change your api controller logic to a response()->json(...)
public function index(Request $request)
{
// Your retrieve logic...
return response()->json($data);
}
Finally if you have successfully configured everything abouve, your vue component should be able to retrieve the information correctly, and your tbody must work this way...
<tbody>
<tr v-for="client in clients" v-bind:key="client.id">
<td>{{ client.id }}</td>
<td>{{ client.name }}</td>
<td>{{ client.email }}</td>
<td>{{ client.documents.cpf || client.documents.cnpj }}</td>
<td>{{ client.documents.celular }}</td>
<td>{{ client.status }}</td>
<td v-if="client.address">
<!-- You can replace what you have with: -->
{{ client.address.localidade }} / {{ client.address.uf }}
</td>
<td v-else>
-
</td>
<td>
<a :href="`/see-client/${client.id}`">
<i class="icon-magnifier"></i>
</a>
<i class="icon-check" style="color: green"></i>
<i class="icon-close" style="color: red"></i>
</td>
</tr>
</tbody>
I am trying to create a table where the input is a Type object. I have managed to return the data in the table however there are currently two issues:
The Value of the Data doesn't match the column
All the values are in one row (i.e Success, Success, Success)
I understand that I should use some mapping logic however, I can't seem to get my head round that. Any help will be greatly appreciated, thanks
.ts
searchValue: string = "3";
logList: any = [];
getLogs() {
const numOfLogs = new FormData();
numOfLogs.append('n_log', this.searchValue)
this.fileUploadService.getLogs(numOfLogs).subscribe(
data => {this.logList = data},
);
}
html
<table class="table table-striped" style="width:1000px;table-layout:fixed;font-size:10px;color:black;">
<thead>
<tr>
<th>Name</th>
<th>Date</th>
<th>FilePath</th>
<th>Updated</th>
</tr>
</thead>
<tbody>
<tr>
<td *ngFor="let item of logList | keyvalue"">{{ item.value}}</td>
</tr>
</tbody>
</table>
console.log(this.logList)
{
"Name": [
"name1",
"name2",
"name3"
],
"Date": [
"2021-12-13",
"2021-12-12",
"2021-12-11"
],
"FilePath": [
"FileName1.xlsx",
"FileName2.xlsx",
"FileName3.xlsx",
],
"Updated": [
"2021-12-31T00:00:00",
"2021-12-31T00:00:00",
"2021-12-31T00:00:00",
],
}
You're telling it to repeat over each key so:
<td *ngFor="let item of logList | keyvalue">{{ item.value}}</td>
Would become:
<tr>
<td>{{ logList.Name }}</td>
<td>{{ logList.Date }}</td>
<td>{{ logList.FilePath }}</td>
<td>{{ logList.Updated }}</td>
</tr>
Which would then be interpolated as:
<tr>
<td>name1,name2,name3</td>
<td>...etc</td>
</tr>
I'm guessing what you want is:
<tr>
<td>name1</td>
<td>2021-12-13</td>
<td>FileName1.xlsx</td>
<td>2021-12-31T00:00:00</td>
</tr>
<tr>
<td>name2</td>
<td>2021-12-12</td>
<td>FileName2.xlsx</td>
<td>2021-12-31T00:00:00</td>
</tr>
...etc
The easiest thing would be to parse your data into a different type. So your data would look then like this
[
{
"Name": "name1",
"Date": "2021-12-13",
"FilePath": "FileName1.xlsx",
"Updated": "2021-12-31T00:00:00",
},
...
]
Then your html would look like this instead:
<tr *ngFor="log in logList"> <!-- notice the ngFor is now on the row -->
<td>{{ log.Name }}</td>
<td>{{ log.Date }}</td>
<td>{{ log.FilePath }}</td>
<td>{{ log.Updated }}</td>
</tr>
If you're unable to modify the data coming back to look like that, you'd have to parse it on your own:
...
this.fileUploadService.getLogs(numOfLogs).subscribe(data => {
this.logList = [];
for(var x = 0; x < data.Name.length; x++){
this.logList.push({
Name: data.Name[x],
Date: data.Date[x],
FilePath: data.FilePath[x],
Updated: data.Updated[x],
});
}
});
On my HTML template, I am printing a list of my QuerySet that I passed from views.py in Django. I want users to delete an entry from the list without refreshing the page. How do I do that?
urls.py - path("del_trans/<int:trans_num>", views.delete_transaction, name="delete_transaction")
views.py
def delete_transaction(request, trans_id):
user = User.objects.get(username=request.user)
transaction = Transaction.objects.get(ruser=user, id=trans_id)
transaction.delete()
return HttpResponse(status=204)
trans.html
<tr id="trans-{{t.id}}">
<td>{{ t.name }}</td>
<td><button class="btn" onclick="delete_trans({{t.id}})"><span style="cursor:pointer;
color:blue;
text-decoration:underline;">Delete</span></button></td>
</tr>
index.js
function delete_trans(id) {
fetch(`/del_trans/${id}`, {
method: 'PUT',
body: JSON.stringify({
trans_id: id
})
});
document.querySelector('#trans-' + id).style.display = 'none';
}
I have a table with some to-do tasks and I want to be able to remove tasks through ajax but I do not know how to refresh my table after deleting.
I already am able to delete a task but I do not see the task removed until i refresh the page. I am sending some foo message to the template and I can see it but what I dont know is how to send the result of my query again and send a bunch of tasks to the template and show them in the table
this is my code
controller
class Delete(webapp2.RequestHandler):
def get(self):
string_id = self.request.get("task")[12:28]
task_key = ndb.Key('Task', int(string_id))
task_key.delete()
session = Session(self.request)
user = User.get_by_id(session.email)
userkey=user.key
tasks=Task.query(Task.author==userkey)
response_data = {'message' : 'foo'}
self.response.out.headers['Content-Type'] = 'text/json'
self.response.out.write(json.dumps(response_data))
return
class MainPage(webapp2.RequestHandler):
#login_required
def get(self):
session = Session(self.request)
user = User.get_by_id(session.email)
userkey=user.key
tasks=Task.query(Task.author==userkey)
template_values = {
'tasks': tasks
}
template = 'index.html'
render_template(self,template,template_values)
javascript
$(document).ready(function(){
$('.delete-button').click(function() {
$.ajax({
type: 'GET',
url: '/delete',
data: $('#delete-form').serialize(),
success: showData,
error: null
});
return false;
});
})
function showData(data){
$('#prueba').html(data.message)
}
template
<table >
<thead>
<tr>
<th>Nombre</th>
<th>Descripcion</th>
<th>Fecha</th>
<th>Status</th>
<th></th>
</tr>
</thead>
<tbody>
{% for task in tasks %}
<tr>
<td>{{ task.name }}</td>
<td>{{ task.description }}</td>
<td>{{ task.date|datetime }}</td>
<td>{{ task.status }}</td>
<td>
<form action="#" id="delete-form">
<input type="hidden" name="task" value="{{task.key}}">
<input type="submit" value="Eliminar" class="delete-button">
</form>
</td>
</tr>
{% endfor %}
<tbody>
</table>
<div id="prueba"></div>
Just refresh the page or after deleting in ajax make a Jquery function which will dynamically remove this object from your view. This are only two options you have ;)
For example:
$.ajax({
type: 'GET',
url: '/delete',
data: $('#delete-form').serialize(),
success: showData,
error: null
}, function() {
Your removing function
});
In your removing function you have to just simply find this object which you want to remove and remove it, for example:
$(#ObjectName).parents("li:first").remove();