Show model values in django form (ModelChoiceField) - django-forms

I am new to Django and having a hard time understanding the whole Django forms. I am creating a form which gets user input. User can add more rows (javascript). I have a few questions.
1. How do i use queryset to show combo options to the user? Currently i am getting a combobox with objects, not its original value
I need to display item_combo value
class NameForm(forms.Form):
# your_name = forms.CharField(label='Your name', max_length=100)
new_date = forms.DateField(initial=datetime.date.today, required=False, error_messages={'required': 'Your Name is Required'})
item_combo = forms.ModelChoiceField(Item.objects.all())
new_parc = forms.CharField(max_length=200, required=False)
new_vid = forms.CharField(max_length=50, required=False)
views.py
def get_name(request):
if request.method == 'POST':
form = NameForm(request.POST)
if form.is_valid():
data = form.cleaned_data
logger.info('FORM INFO')
logger.info('form info date is %s ', data)
new_date = form.cleaned_data['new_date']
new_parc = form.cleaned_data['new_date']
item_combo = form.cleaned_data['item_combo']
return HttpResponseRedirect('/thanks/')
else:
logger.error('Form is invalid. Errors are %s', form.errors)
else:
form = NameForm()
logger.error('Form has GET request. Errors are %s', form.errors)
return render(request, 'form.html', {'form': form})
form.html
<html>
{% load staticfiles %}
{% load static %}
{% include 'head.html' %}
<h1>New post</h1>
<form action="your-name" method="post">
{% csrf_token %}
<div class="fieldWrapper">
<label for="{{ form.new_date.id_for_label }}">Date</label>
{{ form.new_date }}
</div>
<div class="fieldWrapper">
<label for="{{ form.new_date.id_for_label }}">Voucher ID</label>
{{ form.new_vid }}
</div>
<div class="fieldWrapper">
<label for="{{ form.new_date.id_for_label }}">Particulars</label>
{{ form.new_parc }}
</div>
<div class="fieldWrapper">
<label for="{{ form.item_combo.id_for_label }}">Items</label>
{{ form.item_combo }}
</div>
<div class="fieldWrapper">
<label for="{{ form.item_combo.id_for_label }}">Burgers</label>
{{ form.burger_combo }}
</div>
<table>
<thead style="background-color:#9df0e0;color: #73879C">
<tr class="headings">
<th>
<input type="checkbox" id="check-all" class="flat">
</th>
<th class="column-title">Sr. No</th>
<th class="column-title">Code</th>
<th class="column-title">Particulars</th>
<th class="column-title">Qty</th>
<th class="column-title">Rate</th>
<th class="column-title">Amount</th>
<th class="bulk-actions" colspan="7">
<a class="antoo" style="color:#fff; font-weight:500;">Bulk
Actions (
<span class="action-cnt"> </span> ) <i
class="fa fa-chevron-down"></i></a>
</th>
</tr>
</thead>
<tbody>
<tr class="even pointer" id='addr0'>
<td class="a-center ">
<input type="checkbox" class="flat" name="check0">
</td>
<td><input type="hidden" name="c0">1</td>
<td>
<select class="select2_single form-control" tabindex="-1" name="scode0">
<option value="">Select One</option>
{% for item in items %}
<option value="{{ item }}">{{ item }}</option>
{% endfor %}
</select>
</td>
<td class=" "><input type="text" name='part0' placeholder='Add particulars' class="form-control"/></td>
<td class=" "><input type="text" name='qty0' placeholder='Add Quantity ' class="form-control"/></td>
<td class=" "><input type="text" name='rate0' placeholder='Add rate' class="form-control"/></td>
<td class=" "><input type="text" name='am0' placeholder='Add amount' class="form-control"/></td>
</tr>
</tbody>
</table>
<input type="submit" value="Add more rows"/>
<input type="submit" value="Delete rows"/>
<input type="submit" value="Submit"/>
</form>
</html>

Answering my own question.This is one way to do it.
widgets = {
'description': forms.Select(choices=Item.objects.all().values_list('id', 'description'), attrs={})
}

Related

Blade filter data depending on the authenticated user's role

I'm trying to make a school management system with laravel and jQuery. Currently it's working ok with admin as logged in user. But I'm having trouble to create the blade for when the parents are logged in.
I've in a StudentController the index formula below
if( Auth::user()->is_parent ){
$students = Student::with(['status', 'birth_country', 'main_nationality', 'secondary_nationality', 'spoken_languages', 'student_categories', 'p_1_relationship',
'p_1_main_nationality', 'p_1_pref_comm_lang', 'p_2_relationship', 'p_2_main_nationality', 'p_2_pref_comm_lang', 'academic_session',
'academic_formation', 'academic_class', 'registration_type', 'academic_section', 'option_1', 'option_2', 'option_3', 'option_4', 'option_5',
'option_6', 'option_7', 'option_8', 'option_9', 'option_10', 'user_student', 'created_by'])
->where('p_1_email', '=', Auth::user()->email)
->orWhere('p_2_email', '=', Auth::user()->email)
->get();
} else{
$students = Student::with(['status', 'birth_country', 'main_nationality', 'secondary_nationality', 'spoken_languages', 'student_categories', 'p_1_relationship',
'p_1_main_nationality', 'p_1_pref_comm_lang', 'p_2_relationship', 'p_2_main_nationality', 'p_2_pref_comm_lang', 'academic_session',
'academic_formation', 'academic_class', 'registration_type', 'academic_section', 'option_1', 'option_2', 'option_3', 'option_4', 'option_5',
'option_6', 'option_7', 'option_8', 'option_9', 'option_10', 'user_student', 'created_by'])
->get();
}
$statuses = Status::where('module', 'Academic Registration')->get();
$countries = Country::get();
$languages = Language::get();
$categories = Category::where('head_category_id',24)->get();
$relationships = Relationship::get();
$academic_sessions = AcademicSession::get();
$academic_formations = AcademicFormation::get();
$academic_classes = AcademicClass::get();
$types = Type::where('module', 'Academic Registration')->get();
$academic_sections = AcademicSection::get();
$academic_subjects = AcademicSubject::get();
$users = User::get();
return view('app.students.index', compact('academic_classes', 'academic_formations', 'academic_sections', 'academic_sessions', 'academic_subjects', 'categories',
'countries', 'languages', 'relationships', 'statuses', 'types', 'students', 'users'));
And my index blade ,
#if ( Auth::user()->is_parent )
<table class=" table table-bordered table-striped table-hover table-sm">
<thead>
<tr>
<th width="6" class="text-center">
</th>
<th width="10" class="text-center">
{{ trans('student.fields.status') }}
</th>
<th class="text-center">
{{ trans('student.fields.student_category') }}
</th>
<th class="text-center">
{{ trans('student.fields.first_registration') }}
</th>
<th class="text-center">
{{ trans('student.fields.first_name') }}
</th>
<th class="text-center">
{{ trans('student.fields.last_name') }}
</th>
<th class="text-center">
{{ trans('student.fields.birth_date') }}
</th>
<th class="text-center">
{{ trans('cruds.student.fields.academic_session') }}
</th>
<th class="text-center">
{{ trans('student.fields.academic_formation') }}
</th>
<th class="text-center">
{{ trans('student.fields.academic_class') }}
</th>
<th class="text-center">
{{ trans('student.fields.registration_type') }}
</th>
<th class="text-center">
</th>
</tr>
</thead>
<tbody>
#foreach($students as $student)
<tr>
<td class="text-center">
</td>
<td class="text-center">
{{ $student->status->name ?? '' }}
</td>
<td class="text-center">
#foreach($student->student_categories as $key => $item)
<span class="label label-info label-many">{{ $item->name }}</span>
#endforeach
</td>
<td class="text-center">
<span style="display:none">{{ $student->first_registration ?? '' }}</span>
<input type="checkbox" disabled="disabled" {{ $student->first_registration ? 'checked' : '' }}>
</td>
<td class="text-center">
{{ $student->first_name ?? '' }}
</td>
<td class="text-center">
{{ $student->last_name ?? '' }}
</td>
<td class="text-center">
{{ $student->birth_date ?? '' }}
#if ( $student->birth_date )
<ul class="list-unstyled">
<li>
{{ trans('student.fields.age') }} : {{ $student->age ?? '' }} years
</li>
</ul>
#endif
</td>
<td class="text-center">
{{ $student->academic_session->name ?? '' }}
</td>
<td class="text-center">
{{ $student->academic_formation->code ?? '' }}
</td>
<td class="text-center">
{{ $student->academic_class->name ?? '' }}
</td>
<td class="text-center">
{{ $student->registration_type->name ?? '' }}
<ul>
#if ( $student->entry_date )
<li>
{{ trans('student.fields.entry_date') }} : {{ $student->entry_date ?? '' }}
</li>
#endif
#if ( $student->exit_date )
<li>
{{ trans('student.fields.entry_date') }} : {{ $student->exit_date ?? '' }}
</li>
#endif
</ul>
</td>
<td class="text-center">
<ul class="list-unstyled">
<li>
#can('student_show')
<a class="btn btn-xs btn-primary" href="{{ route('app.students.show', $student->id) }}">
{{ trans('view') }}
</a>
#endcan
</li>
<li>
#can('student_edit')
<a class="btn btn-xs btn-info" href="{{ route('app.students.edit', $student->id) }}">
{{ trans('edit') }}
</a>
#endcan
</li>
<li>
#can('student_delete')
<form action="{{ route('app.students.destroy', $student->id) }}" method="POST" onsubmit="return confirm('{{ trans('are You Sure') }}');" style="display: inline-block;">
<input type="hidden" name="_method" value="DELETE">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="submit" class="btn btn-xs btn-danger" value="{{ trans('delete') }}">
</form>
#endcan
</li>
</ul>
</td>
</tr>
#endforeach
</tbody>
</table>
#else
.........
#endif
When I logged in as admin, the index datatable is working fine, but when I logged in as a parent which as children listed, the children aren't showed.
What did I miss?

How do I match users permission with all the permissions in the database

I'm trying to get the user role with permissions and compare them with all permissions that are in the database, if they match then a checkbox should be checked... I'm not sure if I'm doing it correctly
RoleController :
public function edit($id)
{
$role =Role::where('id', $id)->with('permissions')->first();
$permissions = Permission::all();
return view('admin.roles.edit', compact('role', 'permissions'));
}
edit.blade.php :
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">TYPE</th>
<th scope="col">CREATE</th>
<th scope="col">VIEW</th>
<th scope="col">UPDATE</th>
<th scope="col">DELETE</th>
</tr>
</thead>
<tbody>
#foreach($permissions as $permission)
<tr>
<td>
<div class="custom-control custom-checkbox ml-3">
<input type="checkbox" class="custom-control-input" id="{{ $permission->name }}" value="{{ ($permission->name) }}" {{ ($permission->name == "$role->permissions->name") ? "checked" : "" }}>
<label class="custom-control-label" for="{{ $permission->name }}">{{ $permission->display_name }}</label>
</div>
</td>
</tr>
#endforeach
</tbody>
</table>
I'm not getting any errors but I cant make the checkbox to be checked if they match... I'm using Laratrust 5.2
You can do it like this,
#foreach($permissions as $permission)
#php
$attribute = ($permission->id === $role->permissions->id)
? 'checked="checked"'
: '';
#endphp
<label for="permission-{{ $permission->id }}">
<input type="checkbox" {{ $attribute }} class="custom-control-input" id="permission-{{ $permission->id }}" value="{{ ($permission->id) }}">
<span>{{ ($permission->name) }}</span>
</label>
#endforeach
$permissions and $role->permissions should share the id field with same integer value where applicable.
I've added some extra html as it's considered as a good practice and changed your id & value attributes so it becomes more precise & standard.

Uploading image can't saved at directory and having error "htmlspecialchars() expects parameter 1 to be string, array given "

i have a view input like that :
<form class="form-group" action="/user6" method="post" enctype="multipart/form-data">
<table class="table table-striped">
<tbody><tr>
<th style="width: 10px">#</th>
<th>Pertanyaan</th>
<th style="width: 60px">Tidak Baik</th>
<th style="width: 60px">Baik</th>
</tr>
<div class="form-group">
<tr>
<td>1.</td>
<td><input class="form-control" style="border:none" type="text" name="question1" value="Kondisi, kebersihan, pelumasan bearing" readonly></td>
{{-- <td><input class="form-control" type="text" placeholder=".input-lg"></td> --}}
<td>
<label><input type="radio" name="answer1" value="tidak baik" checked></label>
</td>
<td>
<label><input type="radio" name="answer1" value="baik"></label>
</td>
</tr>
<tr>
<td></td>
<td> <input class="form-control" style="border:none" type="file" name="image" value="" readonly> </td>
</tr>
</div>
<tr>
<td></td>
<td> <div class="form-group">
<label>Catatan</label>
<textarea class="form-control" name="catatan" rows="3" placeholder="Enter ..." required></textarea>
</div>
</tr>
<input type="hidden" name="alat_id" value="7">
<input type="hidden" name="status" value="3 Bulanan">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</tbody>
</table>
<div class="box-footer">
<button type="submit" class="btn btn-primary" name="name" value="post">Submit</button>
</div>
</form>
and to save this i have controller :
public function store6(Request $request)
{
if($request->hasfile('image'))
{
foreach($request->file('image') as $file)
{
$name=$file->getClientOriginalName();
$file->move(public_path().'/images/', $name);
$data[] = $name;
}
}
$user = new pemeliharaan;
$id = Auth::user()->id;
$user->user_id = $id;
$user->alat_id = $request->alat_id;
$user->pertanyaan =json_encode($request->except
(['_token','name','alat_id','status','catatan']));
$user->catatan = $request->catatan;
$user->status = $request->status;
$user->save();
//dd($user);
return redirect('user/show6')->with('success', 'Data Telah Terinput');
}
before i add "enctype="multipart/form-data" , my view dont have error BUT cant display and saved image at directory . i want saved image to directory but cant saved .
i create a folder named 'images' at public . after i add enctype="multipart/form-data" . this view having error "htmlspecialchars() expects parameter 1 to be string, array given "
its my view after input :
<table class="table table-condensed">
<tbody><tr>
<th style="width: 10px">#</th>
<th>Pertanyaan</th>
<th>Hasil</th>
{{-- <th style="width: 40px">Label</th> --}}
</tr>
<tr>
<td>1.</td>
<td>{{ $pemeliharaan->pertanyaan['question1'] }}</td>
<td>
{{ $pemeliharaan->pertanyaan['answer1'] }}
</td>
</tr>
<tr>
<td>2.</td>
<td>{{ $pemeliharaan->pertanyaan['image'] }}</td>
<td>
{{ $pemeliharaan->pertanyaan['image'] }}
</td>
</tr>
<td><img src="{{ url('images/'.$pemeliharaan->pertanyaan['image'])}}"></td>
</tbody></table>
Something in your table is array, it's not a string so when you put it inside {{}}, it will show error.
You should check
$pemeliharaan->pertanyaan['question1']
$pemeliharaan->pertanyaan['answer1']
$pemeliharaan->pertanyaan['image']
by using dd() function.
Deal with one problem at a time. At present you are storing the image but not saving the path to the file, which you saved in $data. You are not using $data anywhere.
Then you have a problem rendering the new model in the view. This is a totally different issue and is caused by having non-string data passed to the htmlspecialchars function which is what {{ }} does.

Form Input Bindings v-model not rendering in a views page in laravel

I have question on it for the vue.js I already have a library vue.js in my web application site. Now my problem is when i try to use the Form Input Bindings the v-model this line of code here below
<input v-model="message" placeholder="edit me">
<p>Message is: {{ message }}</p>
what i notice is it says
Use of undefined constant test - assumed 'test'
So i try to see the solution on this one by adding a # beacuase laravel is using blade template. Now when i add a # the error is gone but the render goes this way {{ test }} . Why does it not rendered correctly in my browser?. Can someone help me figured this thing out?. Any help is muchly appreciated. TIA.
Here is my code
#extends('layouts.app')
#section('title', 'Cases New Invoice | RMTG')
#section('content')
<div id="content-wrapper">
<div class="container-fluid">
<!-- Breadcrumbs-->
<ol class="breadcrumb">
<li class="breadcrumb-item">
Dashboard
</li>
<li class="breadcrumb-item active">Cases New Invoice</li>
</ol>
<div class="row">
<div class="col-lg-12">
<div class="card mb-3">
<div class="card-header">
<i class="fa fa-file"></i>
New Invoice</div>
<div class="card-body">
<div class="form-group">
<div class="form-row">
<div class="col-md-6" >
<div class="table-responsive">
<form action="" method="post">
{{ csrf_field() }}
<table class="table table-bordered" width="100%" cellspacing="0">
<thead>
<tr>
<th width="150px;">Contact Name: </th>
<td>{{ $opp->contacts }}</td>
</tr>
<tr>
<th>Case Number:</th>
<td>OPP -{{ $opp->code }}</td>
</tr>
<tr>
<th>Case Name:</th>
<td>{{ $opp->tax_year }}</td>
</tr>
<tr>
<th>Item Code:</th>
<td>
<div id="app-item">
<select name="itemCode" class="form-control">
<option v-for="item in items" v-bind:value="item.value">
#{{ item.text }}
</option>
</select>
</div>
</td>
</tr>
<tr>
<th>Notes: </th>
<td>
<input type="text" name="notes" class="form-control" />
</td>
</tr>
<tr>
<th>Amount: </th>
<td><input v-model="test" type="text" name="amount" class="form-control" required />
</td>
</tr>
<tr>
<th>VAT 20% Amt: </th>
<td>
<input type="text" name="vatAmount" class="form-control" />
</td>
</tr>
<tr>
<th>Total Amount: </th>
<td>
<input type="text" name="totalAmount" class="form-control" />
</td>
</tr>
</thead>
</table>
<div class="pull-right">
<button type="submit" class="btn btn-success">
<i class="fa fa-save" aria-hidden="true" style="font-size:24px"></i> Save
</button>
</div>
</form>
</div>
</div>
<div class="col-md-6" >
<h3>Amount Due: £ #{{ test }}</h3>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
//Item code
new Vue({
el: '#app-item',
data: {
items:[
{ text:'Tax Returns', value: 'Tax Returns' },
{ text:'UTR Filing', value: 'UTR Filing'}
]
}
})
</script>
#endsection

How to get sum score when checked the checkboxess?

I have score field in table of infractions. And I have many checkboxes. When I checked thed chechboxes, The total of scores are collected with ajax.
<div id="collapse6" class="panel-collapse collapse">
<div class="panel-body">
<div class="table-responsive">
<table class="table table-bordered">
#foreach($infractions as $infraction)
<tr>
<th>{{ $infraction->title }}</th>
<td>
<input type="hidden" name="infractions[{{ $infraction->id }}]" value="0" >
<input type="checkbox" value="1" onclick="{{ $infraction->score }}" name="infractions[{{ $infraction->id }}]" data-toggle="toggle">
</td>
</tr>
#endforeach
</table>
</div>
<div class="text-right"> Totlal
<span id="total">
</span>
</div>
</div>
</div>
Ajax
function scorePlus (id)
{
// var value = parseInt(document.getElementById('num'+id).value, 10);
value = isNaN(value) ? 0 : value;
value++;
document.getElementById('total').value = value;
}

Resources