Retrieve image from django - django-media

I am completely beginner in Django, trying to make a table, which gets data from the Django database(included image). Here before adding the image field in the Django model, all was working perfectly. but I cannot get an image from the Django media file(I also upload images with superuser and Django form both, and they worked perfectly). here is my approach below-
in views.py:
def index(request):
table_data = TableA.objects.order_by('roll')
index_dict = {'insert_me' : "hello this is from views.py",
'dynamic_table' : table_data,
}
return render(request, 'app26/index.html', context=index_dict)
in HTML:
{% if dynamic_table %}
<table class="table table-striped">
<thead class="thead-dark">
<tr>
<th>Name</th>
<th>Roll</th>
<th>Email</th>
<th>Password</th>
<th>Address</th>
<th>Profile Pic</th>
</tr>
</thead>
<tbody>
{% for i in dynamic_table %}
<tr>
<td>{{ i.name }}</td>
<td>{{ i.roll }}</td>
<td>{{ i.email }}</td>
<td>{{ i.password }}</td>
<td>{{ i.address }}</td>
<td><img class="profile-pic" src="{{media_url}}{{ i.profile_pic }}" alt=""></td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p>sorry cannot load the data for technical error</p>
{% endif %}
in urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
I've also set up MEDIA_URL and MEDIA_ROOT. From the Admin I can upload images and they are ok.
in settings.py:
MEDIA_ROOT = os.path.join(BASE_DIR, 'Media')
MEDIA_URL = '/images/'
Now my problem is nothings is show in the profile pic column in the table, even any error is not showing.
Please suggest me how can I get the image file from the database for my this uses

I think the main reason the images where not being displayed was because the path to your media_url was not added into the render function. See below:
def index(request):
img = Upload.objects.filter(file_type='image')
index_dict = {
'insert_me' : "hello this is from views.py",
'dynamic_table' : table_data,
'media_url': settings.MEDIA_URL
}
return render(request, 'app26/index.html', context=index_dict)
Give it a shot!

Related

Laravel get one record from the database

Im trying to make a list with game developers, and when you click on one of them you can see the games they have made. I only dont know how to get further....
This is what i have now:
Index.blade.php:
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">#</th>
<th scope="col">Naam</th>
<th scope="col">Opgericht in:</th>
</tr>
</thead>
<tbody>
#foreach($gamedevs as $gamedev)
<tr>
<td>{{ $gamedev['id'] }} </td>
<td>{{ $gamedev['naam'] }}</td>
<td>{{ $gamedev['opgericht'] }}</td>
</tr>
#endforeach
</tbody>
I already tried some methods like these:
href="{{route('games.show', ['id'=>$gamedev->id])}}
and
href="/games/{{$gamedev['id']}}
listcontroller.php
public function index()
{
$gamedevs = Gamedevs::all();
return view("index", [ 'gamedevs' => $gamedevs]);
}
public function show(Gamedevs $gamedevs)
{
$gamedevs = Gamedevs::where($gamedevs)->first();
return view('pages.games.show')->with('Gamedevs',$gamedevs);
}
Never did this before.. so hope im on the right way :)
Laravel controller methods like show will use service container to resolve all the parameters you define there. Since you define a model, laravel will automatically find the one corresponding with explicit model binding.
So you wont have to write another query to show your Gamedev:
public function show(Gamedevs $gamedevs)
{
return view('pages.games.show')->with('Gamedevs',$gamedevs);
}
Sample route in web.php
Route::get('/games/{dev_id}','listController#show');
Sample Method in your listController.php
public function show($gamedevs)
{
#let's say your $gamedevs is your devs id so target their id's
$devs = Gamedevs::where('id',$gamedevs)->first();
return view('pages.games.show')->with([
'Gamedevs'=>$devs
]);
}
In your view
href="/games/{{$Gamedevs->id}}

How to auto refresh html table fields rendered with a for loop in flask?

Snippet from the function in Flask.
I'm generating a list of all positions and then sending them over. Then using jinja and the for loop I'm populating the table.
#app.route("/")
def table_list():
position_list=["a","b","c","d"]
return render_template("index.html",
position=position_list)
This is on the homepage and needs to be automatically refreshed every couple of seconds so the position values will get updated.
The HTML table:
<table>
<tbody id="data">
{% for pos1, pos2, pos3, pos4 in position %}
<tr id="data_table">
<td id="pos1"> {{ pos1 }} </td>
<td id="pos2"> {{ pos2 }} </td>
<td id="pos3"> {{ pos3 }} </td>
<td id="pos4"> {{ pos4 }} </td>
{% endfor %}
</tbody>
</table>
How do I use JS to refresh only the values in the table, and automatically every couple of seconds?
You will have to change multiple things to make this work.
Separate endpoint into html endpoint and web-service endpoint.
#app.route("/table_list")
def table_list():
return render_template("index.html")
#app.route("/get_list")
def get_list():
position_list = ["a", "b", "c", "d"]
return make_response({"output": position_list})
Change the html for table
<table>
<tbody id="data">
<tr id="data_table">
</tr>
</tbody>
</table>
Change the html template to keep calling get_list and refresh the html
</body>
<script>
setInterval(function () {
let myRequest = new Request('/get_list');
fetch(myRequest).then(response => response.json()).then(function (data) {
let data_table = document.getElementById("data_table");
data_table.innerHTML = "";
for (let d in data['output']) {
data_table.innerHTML += `<td>${data['output'][d]}</td>`
}
});
}, 1000);
</script>
</html>

Flask Button click not generating POST message

I am using flask to generate a single webpage.
The webpage has couple of text boxes and a button.On button click, I am planning to display table in the same page with the values fetched from the inputs.
Below is the flask code in python
===========================
#app.route('/')
def index():
return render_template('index.html')
#app.route('/ApplyFilter',methods=['POST','GET'])
def ApplyFilter():
print("Hello")
if request.method == 'POST':
import CompareDataset as cmp
df3= cmp.CompareDataset()
#conver the dataframe to the json objects
AllRecords = json.loads(df3['both'].to_json(orient="records"))
# count the number of records
totalItems = df3['both']["Client"].count()
client=request.form["client"]
account= request.form["account"]
auditstatus = request.form["auditstatus"]
effectivedate=request.form["effectivedate"]
cyclecode=request.form["cyclecode"]
return
jsonify({'data':render_template('ApplyFilter.html',AllRecords=AllRecords,totalItems=totalItems)})
return redirect('/')
snapshot of the html is as below
<td>
Apply Filter</button>
</td>
</tr>
</table>
</div>
</div>
{% if AllRecords %}
<div class="container-fluid bg-3 text-left">
<div class="counter"><span>Total Records Found : {{ totalItems }}</span></div>
<div "border-bottom: 1px solid #ddd; overflow-y: scroll;" >
<table class="table" style="width: 90%; height: 100%;" >
<thead style="color: #333; background-color: #f1f1f1">
<tr>
<th>Audit Status</th>
<th>Client</th>
<th>Effective Date</th>
<th>Source System Code</th>
<th>Account Number</th>
<th>Cycle Code</th>
<th>AuditTrailtimeStamp</th>
</tr>
</thead>
<tbody>
<tr class="success" >
{% for key,value in AllRecords.iterrows() %}
<td>{{ value["AuditStatusCode"] }}</td>
<td>{{ value["Client"] }}</td>
<td>{{ value["EffectiveDate"] }}</td>
<td>{{ value["SourceSystemCode"] }}</td>
<td>{{ value["InternalAccountId"] }}</td>
<td>{{ value["CycleCode"] }} </td>
<td>{{ value["AuditTrailtimeStamp_x"] }} </td>
{% endfor %}
</tr>
</tbody>
</table>
</div>
</div>
{% endif %}
</form>
The java script tagged to button is as below
$(function() {
$('a#applyfilter').bind('click', function() {
$.getJSON('/ApplyFilter', {
client : $("client").val(),
account : $("account").val(),
auditstatus : $("auditstatus").val(),
auditstatus : $("auditstatus").val(),
effectivedate :$("effectivedate").val(),
cyclecode : $("cyclecode").val(),
}, function(data) {
data = data.data;
});
return false;
});
});
On button click ApplyFilter is getting called. But it is not generating the POST message
127.0.0.1 - - [07/Jul/2018 17:45:40] "GET / HTTP/1.1" 200 - Hello
127.0.0.1 - - [07/Jul/2018 17:45:43] "GET /ApplyFilter HTTP/1.1" 302 -
127.0.0.1 - - [07/Jul/2018 17:45:43] "GET / HTTP/1.1" 200 - Hello
The applyfilter button is not generating the post call and hence in the route Applyfilter , the if condition is not satsifying.
Please assist and advise as to what I am missing.
There are many problems with this code and I'm still a bit confused by what you're trying to accomplish but I'll answer your question for now.
Your logs tell you exactly what the problem is. You want that if statement to run when you send a post request. But your logs show that you are receiving a get request and returning a 302 which indicates you have been redirected which is what is happening at the bottom of your method. So if you're sending a get request, an if statement that checks if you're using a post request isn't going to fire.
127.0.0.1 - - [07/Jul/2018 17:45:43] "GET /ApplyFilter HTTP/1.1" 302 -
You seem to be using getJson() when you should be using something like the post() method.
But there are other problems such as this section won't do anything
jsonify({'data':render_template('ApplyFilter.html',AllRecords=AllRecords,totalItems=totalItems)})
return redirect('/')
For some reason you're jsonifying a call to render_template and then doing nothing with it? I can't even think what you're trying to achieve by jsonifying render_template when that function will only work within your Flask app. I may just be misunderstanding you so apologies if I am, feel free to clarify further and I'll do my best to help.

Laravel Blade change row color when variable value is different in loop

I have a report page that loops through a collection and displays the data in a generic bootstrap template table - it's showing data about users, and one user can have multiple rows in the table. I group the rows by the user ID and I want to basically stripe the table rows based on the user ID (not just alternating rows). So, for example, I might display 4 rows for user ID = 5 with a white background and then 2 rows for user ID = 6 with a gray background. I'd just use a local variable in straight php, but is there an elegant/clean way to do this in the blade templates?
#foreach($payments->getDetails() AS $k=>$detail)
<tr>
<td>{{ $detail->payment->userid }}</td>
<td>${{ $detail->payment->amount }}</td>
<td>{{ $detail->payment->status }}</td>
</tr>
#endforeach
In this example, $payments is a collection of $paymentsDetails objects. So based on the $detail->payment->userid value I'd like to determine the class or background color.
Thank you for any help in this.
Just a thought... This assumes the rows are ordered by user id naturally (it would not work otherwise in your example anyway...)... So here's the thought...
If the user id is odd, then give it a color, if it is even, give it the alternate color... that would work... Sort of ...
#foreach($payments->getDetails() AS $k=>$detail)
<tr>
<td class="{{$detail->payment->userid % 2 == 0 ? 'evenColor':'oddColor'">{{ $detail->payment->userid }}</td>
<td class="{{$detail->payment->userid % 2 == 0 ? 'evenColor':'oddColor'">{{ $detail->payment->amount }}</td>
<td class="{{$detail->payment->userid % 2 == 0 ? 'evenColor':'oddColor'">{{ $detail->payment->status }}</td>
</tr>
#endforeach
Something like this would also work... not sure I like it though
#foreach($payments->getDetails() AS $k=>$detail)
#if($detail->payment->userid % 2 == 0)
<tr>
<td class="evencolor">{{ $detail->payment->userid }}</td>
<td class="evencolor">>${{ $detail->payment->amount }}</td>
<td class="evencolor">{{ $detail->payment->status }}</td>
</tr>
#else
<tr>
<td class="oddcolor">{{ $detail->payment->userid }}</td>
<td class="oddcolor">${{ $detail->payment->amount }}</td>
<td class="oddcolor">{{ $detail->payment->status }}</td>
</tr>
#endif
#endforeach
Anyway... just a possible direction... someone else might have a more elegant idea...
I got the solution to this via www.laracasts.com from user #Cronix:
I'd do it the way you were thinking originally and just use
#php/#endphp blade directives to determine if the userid has changed
during each loop iteration and if it does change the color.
#php
$lastid = null;
$rowclass = 'grey';
#endphp
#foreach($payments->getDetails() AS $k=>$detail)
#php
//if userid changed from last iteration, store new userid and change color
if ($lastid !== $detail->payment->userid)
{
$lastid = $detail->payment->userid;
if ($rowclass == 'grey') $rowclass = 'white';
else $rowclass = 'grey';
}
#endphp
<tr class="{{ $rowclass }}">
<td>{{ $detail->payment->userid }}</td>
<td>${{ $detail->payment->amount }}</td>
<td>{{ $detail->payment->status }}</td>
</tr>
#endforeach
If anyone out there has a more elegant Blade-focused idea on how to solve it, I'd love to hear about it.
hey guys the methods above failed for me, incase anyone els needs this : im using laravel 5.4 with php 5.6===> this is what has worked for me;
#php
if ( $post->dbdata == 'approved'):
$color = 'green';
elseif ( $post->dbdata == 'Pending'):
$color = 'yellow';
elseif ( $post->dbdata == 'rejected'):
$color = 'red';
else:
$color = 'black';
endif;
#endphp
<tr style="background-color: {{$color}}">
<td>
<h6>{{ $post->dbdata }}</h6>
</td>
</tr>

Laravel with Revisionable Package and catching errors

Using Laravel and Revisionable package. I am populating a table with user record modifications and have the following code snippet:
<tr>
<td width="150">{{ $revision->updated_at }}</td>
<td>User</td>
<td>{{ $revision->revisionable->first_name }} {{ $revision->revisionable->last_name }}</td>
<td width="50">{{ $revision->fieldName() }}</td>
<td width="50">{{ $revision->userResponsible()->first_name }}</td>
<td>{{ $revision->oldValue() }}</td>
<td>{{ $revision->newValue() }}</td>
</tr>
Getting the users first and last name works fine when the original user record exists but in some cases the original record (user) is deleted and it causes an error because the user record no longer exists. Is there an IF Statement I can use to first check if the first name field returns an error? Then I can display first/last name for records that still exist and something else if it doesn't exist.
Thanks in advance!
Blade has the orsyntax, really nice:
{{ $revision->revisionable->first_name or 'N/A'}}
{{ $revision->revisionable->last_name or 'N/A'}}
alternatives, though not as elegant:
{{ isset($revision->revisionable->first_name) ? $revision->revisionable->first_name : 'N/A' }}
or
#if (isset($revision->revisionable->first_name))
{{ $revision->revisionable->first_name }}
#else
N/A
#endif

Resources