i want to display the list of django many to many field not query set - django-queryset

i want to have the list of many to many field
this is my model
class ElectionType(models.Model):
name = models.CharField(max_length = 255)
class Election Name(models.Model):
name = models.CharField(max_length=200)
types = models.ManyToManyField(ElectionType)
view
def ElectionType(request):
ElectionType = ElectionName.objects.all()
context = {'election_type': election_type}
type.types is returning ElectionType.None
{% for type in election_type %}
<tr>
<td>{{ type.id }}</td>
<td>{{ type.name }}</td>
<td>{{ type.types }}</td>
<tr>

Related

Value correlation from multiple tables in laravel

I have two tables. One employees and one timesheets
I would like to have correct name at the result but different ID. If you see the result I have the same name everywhere.
How can make the code to fixed my challenge?
Thank you.
In controller I have this code
$profile = ['no' => Auth::user()->no];
$timesheets = Timesheet::where($profile)->select('*')->orderBy('created_at','DESC')->get();
foreach ($timesheets as $employee) {
$emp = ['identification' => $employee->identification];
$oneemployee = Employees::where($emp)->select('*')->orderBy('created_at','DESC')->get();
}
return view('contractor.employees.timesheets', compact('timesheets', 'oneemployee'));
and in blade I have
#foreach ($timesheets as $row1)
<tr>
<td>#</td>
#foreach ($oneemployee as $row2)
<td>{{ $row2->fname}}</td>
<td>{{ $row2->lname}}</td>
#endforeach
<td>{{ $row1->identification}}</td>
<td>{{ $row1->week}}</td>
<td>{{ $row1->year}}</td>
</tr>
#endforeach
According to your commit, I suggest the following solution
If you want dispay timesheet with employees you can use eager loading.
For example:
In your controller:
$profile = ['no' => Auth::user()->no];
$timesheets = Timesheet::where($profile)->with("employees")->select('*')->orderBy('created_at','DESC')->get();
return view('contractor.employees.timesheets', compact('timesheets'));
In your Timesheet model add hasOne relation to Employee:
public function employee(){
return $this->hasOne(Employee::class,'identification','identification')
}
And your view:
#foreach ($timesheets as $timesheet)
<tr>
<td>#</td>
<td>{{ $timesheet->employee->fname}}</td>
<td>{{ $timesheet->employee->lname}}</td>
<td>{{ $timesheet->identification}}</td>
<td>{{ $timesheet->week}}</td>
<td>{{ $timesheet->year}}</td>
</tr>
#endforeach

How to calculate using data from get() in controller

I have some data from a table and I'm doing an eloquent get for it. So far from what I know is when using get(), I need to loop it first using foreach to get the data.
My question is how to move my logic code to controller? so I just need to pass it to view. Because I'm doing it on blade directly
Bellow is my controller, I'm just simply get a data from database:
$attendances = Attendance::where('company_id', Auth::user()->company_id)->get();
#foreach ($attendances as $attendance)
// How to move this php code to my controller?
#php
$work_hour_start = $attendance->work_hour_start;
$attendance_time = \Carbon\Carbon::parse($attendance->attendance_time)->format('H:i:s');
$tolerance = \Carbon\Carbon::parse($attendance_time)->addMinutes($attendance->late_tolerance);
if ($tolerance > $work_hour_start) {
$is_late = 'Late';
} else {
$is_late = 'On Time';
}
#endphp
<tr>
<td>{{ $attendance->employee->name }}</td>
<td>{{ Carbon\Carbon::parse($attendance->attendance_time)->format('H:i:s') }}</td>
<td>{{ $attendance->location_library->location_name }}</td>
<td>{{ $is_late }}</td>
</tr>
#endforeach
I want my blade to be clean, but I don't know how to do that.
You could add attendance_time to the $casts property and make tolerance/is_late accessors in the Attendance Model
# Attendance.php
class Attendance extends Model
{
...
protected $casts = [
'attendance_time' => 'datetime',
];
...
public function getToleranceAttribute()
{
return $this->attendance_time->addMinutes($this->late_tolerance);
}
public function getIsLateAttribute()
{
return $this->tolerance > $this->work_hour_start
? 'Late'
: 'On time';
}
...
}
#foreach ($attendances as $attendance)
<tr>
<td>{{ $attendance->employee->name }}</td>
<td>{{ $attendance->attendance_time->format('H:i:s') }}</td>
<td>{{ $attendance->location_library->location_name }}</td>
<td>{{ $attendance->is_late }}</td>
</tr>
#endforeach
Just do it, move the logic to your controller and set it up in your $attendances collection. Something like this:
$attendances = Attendance::where('company_id', Auth::user()->company_id)->get();
foreach ($attendances as $key => $attendance){
$attendances[$key]->attendance_time = \Carbon\Carbon::parse($attendance->attendance_time)->format('H:i:s');
if (\Carbon\Carbon::parse($attendances[$key]->attendance_time)->addMinutes($attendance->late_tolerance > $attendance->work_hour_start) {
$attendances[$key]->setAttribute('is_late', 'Late');
} else {
$attendances[$key]->setAttribute('is_late', 'On Time');
}
}
return view('your-view', ['attendances' => $attendances]);
Now it will be able to iterate on your template:
#foreach ($attendances as $attendance)
<tr>
<td>{{ $attendance->employee->name }}</td>
<td>{{ $attendance->attendance_time }}</td>
<td>{{ $attendance->location_library->location_name }}</td>
<td>{{ $attendance->is_late }}</td>
</tr>
#endforeach

Accessing further data

So I am accessing an external API and I am trying to display this data
https://i.stack.imgur.com/Yop0I.png
and everything was fine so far as you can see
https://i.stack.imgur.com/L3hXq.png
using this code
<tr v-for="cv_output in cv_outputs" :key="cv_output.id">
<td>{{ 'teste' }}</td>
<td>{{ cv_output['id'] }}</td>
<td>{{ cv_output['last-modified-date'] }}</td>
<td>{{ cv_output['output-category']['value'] }}</td>
<td>{{ cv_output['output-category']['code'] }}</td>
<td>{{ cv_output['output-type']['value'] }}</td>
<td>{{ cv_output['output-type']['code'] }}</td>
<td>{{ cv_output['other-output'] }}</td>
but as soon as I try to go further such as
{{ cv_output ['other-output']['title'] }}
the data stops displaying in the table and in the console i get the following:
TypeError: Cannot read property 'title' of null
which doesn't make any sense I think. Any idea why?
Controller method:
public function getRemoteOutputs()
{
$science = Auth::user()->science_id;
$client = new Client(['headers' => ['Accept' => 'application/json']]);
$request = $client->get(
'https://url_to_the_api/'.$science.'/degree',
[
'auth' => ['client', 'secret'],
]
);
$data = $request->getBody()->getContents();
return $data;
}
I #Helpinghand is correct, one of the records is missing other-output.
Try:
<td>
<span v-if="cv_output['output-type']">{{ cv_output['output-type']['title'] }}</span>
<span v-else>No Output Type Title</span>
</td>
Try this:
{{ cv_output ['other-output'] ? cv_output ['other-output']['title']: ''}}
This will return the other-output->title if it exists, if not it should return nothing without error. (you can put whatever you want in the single quotes there if you want something like 'not available' as default)

Django form in every row of a table

I want to have a simple text form on every row of a table.
Fiddle illustration of expected result: https://jsfiddle.net/wstg759f/1/
My Models.py:
class Person(models.Model):
name = models.CharField(max_length=30)
class Quality(models.Model):
name = models.CharField(max_length=30)
person=models.ForeignKey(Person)
I have a queryset that returns aggregated list of all persons, count of qualities for each person, one random quality of this person:
[
{'the_count': 5, u'randomquality': u'Nice’, u'person__name': u'Joe'},
{'the_count': 4, u'randomquality': u'Generous’,u'person__name': u'Mike'},
{'the_count': 4, u'randomquality': u'Healthy’,u'person__name': u'John’'},
..
]
My view.html (qualities is my queryset)
<table>
<thead>
<tr>
<th>Person</th>
<th>Qualities count</th>
<th>One random quality</th>
<th>Add a Quality?</th>
</tr>
</thead>
<tbody>
{%for obj in qualities%}
<tr>
<td>{{ obj.person__name }}</td>
<td>{{ obj.the_count }}</td>
<td>{{ obj.randomquality }}</td>
<td>text form to submit a quality for this person</td>
</tr>
{% endfor %}
</tbody>
</table>
The user should be able to input a quality in the text field, and once submitted it will be added to the model, and the text field is replaced by "thanks, submitted"
The submit form have to be independent.
I have no clear direction where to look at.
How would you do?
From my reading, I understand that formset could be a solution, but they are really unclear for me.
Should I even use django form in this case?
If yes, I believe the form should take an argument form the template: I don't need the user to tell me about the person name as it's already here.
Let me know if I can clarify.
Thanks in advance.
As a bonus, maybe for later, I want to avoid page refresh.
Is ajax the only way?
You can do this with ajax, form and views
template.html
<table>
<thead>
<tr>
<th>Person</th>
<th>Qualities count</th>
<th>One random quality</th>
<th>Add a Quality?</th>
<th>Button</th>
</tr>
</thead>
<tbody>
{% for obj in qualities %}
<tr id="row_{{ obj.id }}">
<td>{{ obj.person__name }}</td>
<td>{{ obj.the_count }}</td>
<td>{{ obj.randomquality }}</td>
<td>{{ form.quality }}</td>
<td><button value="{{ obj.id }}" onclick="addQuality(this.value)">Add</button></td>
</tr>
{% endfor %}
</tbody>
</table>
<script>
function addQuality(id_object) {
const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value
let data_to_backend = new FormData()
let qualityToAdd = document.getElementById(`id_${id_object}-quality`).value
if (qualityToAdd !== '') {
data_to_backend.append('quality', qualityToAdd)
data_to_backend.append('object_index', id_object)
} else return
const request = new Request("./",
{
method: 'POST',
headers: {'X-CSRFToken': csrftoken},
body: data_to_backend
})
fetch(request, {
method: 'POST',
mode: 'same-origin'
}).then(
function(response) {
if (response.status === 200) {
let tableRow = document.getElementById(`row_${ id_object }`)
tableRow.innerHTML = "<p>thanks, submitted</p>"
} else {
alert("Error")
console.log(response)
}
}
)
}
</script>
Set your views to receive a post request or just create a new urls path and another views
views.py
def addQuantity(request, codigo_orcamento):
if request.method == "POST":
form = formAddQuantity(request.POST)
if form.is_valid():
id_object = form.cleaned_data['object_index']
quality = form.cleaned_data['quality']
# get the object and add this quality
return HttpResponse(status=200)
else:
return HttpResponse(status=400)
else:
return HttpResponse(status=405)
In this view we simply check if the form is valid, get the object from db and add the quality on it
forms.py
class formAddQuantity(forms.Form):
object_index = forms.IntegerField(min_value=0)
quality = forms.CharField(max_length=100)
A simple check, but i recommend you to add more requirements to this fields
(Not tested, if throws a error let me know)

Golang function call on template fails on a single struct

i have following code
func (w *Warehouse) GetId() string {
return w.Id.Hex()
}
view multiple works perfect
{{ range .Data }}
<tr>
<td>{{ .Name }}</td>
<td>{{ .City }}</td>
<td>{{ .Manager }}</td>
<td><a class="blue" href="/warehouse/show/{{ .GetId }}">view</a></td>
</tr>
{{ end }}
in single show warehouse i do this but that fails while .Data.Name return the name correctly
{{ .Data.GetId }}
any idea what i am missing here?
problem is that i needed to make instance of my struct like this
var warehouse = new(models.Warehouse) // works
instead of
var warehouse models.Warehouse // fails
According to your code .Data is array or slice. It does not have GetId() method

Resources