image does not show up. Django - html

Can not find what I'm doing wrong (I guess it should be some syntax error). My pictures does not showing up. I'm getting "NO FILES".
html
<!-- RECENTLY ADDED FILES -->
<div class="buttom-box floatleft">
<h3>Recently Added Files</h3>
<p>New class papers. Now you can enjoy and study them</p>
<br>
{% if recent_files %}
{% for file in recent_files %}
<img src="{{ MEDIA_URL }}{{ file.image }}" alt="Sample 1" width="125" height="125" />
{% endfor %}
{% else %}
<p>NO FILES</p>
{% endif %}
</div>
views.py
def index(request):
recent_files = FileDescription.objects.all()
context_instance=RequestContext(request)
return render_to_response('index.html',
{'recent_files':recent_files,},
context_instance,
)
MySQL for FileDescription:
mysql> SELECT * FROM school_filedescription;
+----+------------+--------------+-----------+------------------+-----------+------------------+---------------------+---------------------+-----------------------------+
| id | subject_id | subject_name | file_type | file_uploaded_by | file_name | file_description | file_creation_time | file_modified_time | image |
+----+------------+--------------+-----------+------------------+-----------+------------------+---------------------+---------------------+-----------------------------+
| 1 | 1 | Math 140 | class | rrr | lalala | lalala | 2012-08-23 12:12:12 | 2012-08-23 12:12:12 | files/rrr/class/smart.jpg |
| 2 | 1 | Math 140 | class | rrr | ,s,s,s | s msms | 2012-08-23 12:32:39 | 2012-08-23 12:32:39 | files/rrr/class/smart_1.jpg |
+----+------------+--------------+-----------+------------------+-----------+------------------+---------------------+---------------------+-----------------------------+
2 rows in set (0.00 sec)
However this code in the other page works fine
other page:
{% extends "base.html" %}
{% block main-menu %}
<div class="contentarea">
<img src="{{ MEDIA_URL }}{{ picture.image }}"/>
</div>
{% endblock %}

Try adding the recent file parameter to your request context instance, like this:
context_instance = RequestContext(request, {
'recent_files': recent_files
})
and then call the request like this...
return render_to_response('index.html', context_instance = context_instance)

Related

django multiple form separated in the html, merge again with submit

there is a formmodel like:
class foo(forms.ModelForm):
a = forms.BooleanField(label='a', required=False)
b = forms.BooleanField(label='b', required=False)
c = forms.BooleanField(label='c', required=False)
d = forms.BooleanField(label='d', required=False)
e = forms.BooleanField(label='e', required=False)
f = forms.BooleanField(label='f', required=False)
g = forms.BooleanField(label='g', required=False)
h = forms.BooleanField(label='h', required=False)
#...
further there are multiple instances of foo in a list:
L = []
L.append(foo(instance=object_1))
L.append(foo(instance=object_2))
L.append(foo(instance=object_3))
#...
L.append(foo(instance=object_n))
this is shown on the html in different tables in different columns.
The problem now is to send the data back correctly with subbmit. I have to put the tables and lines back together correctly. I was thinking of something like this:
<form class="form-inline" action ="{% url 'bla:blo' %}" method="post">
Table #1
| ID of Form | Value #1 | Value #2 | Value #3 | Value #4 |
| ---------- | -------- | -------- | -------- | -------- |
<form id=1>| 1 | a1 | b1 | c1 | d1 |</form>
<form id=2>| 2 | a2 | b2 | c2 | d2 |</form>
<form id=3>| 3 | a3 | b3 | c3 | d3 |</form>
<form id=4>| 4 | a4 | b4 | c4 | d4 |</form>
Table #2
| ID of Form | Value #1 | Value #2 | Value #3 | Value #4 |
| ---------- | -------- | -------- | -------- | -------- |
<form id=1>| 1 | e1 | f1 | g1 | h1 |</form>
<form id=2>| 2 | e2 | f2 | g2 | h2 |</form>
<form id=3>| 3 | e3 | f3 | g3 | h3 |</form>
<form id=4>| 4 | e4 | f4 | g4 | h4 |</form>
{% csrf_token %}
<button type="submit" class="btn btn-dark">Save</button>
</form>
i.e. the rows of the table with the same form id must be converted back into the same django form.
the submit must then of course still be accepted in the view.py
kinda like that
def boo(request):
if request.method == 'POST':
if form.is_valid():
f = foo(request.POST):
# f[0] = form id 1
# f[1] = form id 2
# f[2] = form id 3
# ...
# f[n] = form id n
You can only send multiple forms via context, but getting all these form data using another wrapper form will not be possible. You can only see the list of forms, but you may not be able to get data using post requests for all forms.
def boo(request):
if request.method == 'GET':
form_list = []
object_list = [] # YOUR_OBJECT_LIST
for instance in object_list:
form_list.append(foo(instance=instance))
return render("footemplate.html", context={"forms": form_list})
if request.method == "POST":
<form>
{% csrf_token %}
{% for form in forms %}
{{ form }}
{% endfor %}
</form>
To send all forms data via post request, I will suggest using javascript and ajax. and for backend part, use RestfulAPI to handle this complex system

How to give a Hugo / markdown table a class, when the table contains shortcodes?

In hugo (version v0.77.0) I'm trying to render a table with some specific styling. I'm using the
I'm trying to use zwbetz's {{ bootstrap-table "classname" }} shortcode. It's defined in /layouts/shortcodes/bootstrap-table.html like this:
{{ $htmlTable := .Inner | markdownify }}
{{ $class := .Get 0 }}
{{ $old := "<table>" }}
{{ $new := printf "<table class=\"%s\">" $class }}
{{ $htmlTable := replace $htmlTable $old $new }}
{{ $htmlTable | safeHTML }}
It works correctly with a trivial table in markdown like so:
{{< bootstrap-table "someclassname" >}}
| animal | sound |
|--------|-------|
| dog | meow |
| cat | woof |
{{< /bootstrap-table > }}
But if the marked-down table contains other Hugo shortcodes, it rejects the table markup and makes an empty table, followed in the generated html by messages (in html comments) saying Hugo rejected some html.
Here's an offending markdown table.
{{< bootstrap-table "someclassname" >}}
| animal | sound |
|--------|-------|
| {{< img src="dog.jpg" alt="Dog" class="align__left size__80" >}} | meow |
| {{< img src="cat.jpg" alt="Cat" class="align__left size__80" >}} | woof |
{{< /bootstrap-table > }}
What can I do to make this bootstrap-table Hugo tag accept my table with images or other hugo shortcodes in it?
This depends on your img.html shortcode because the bootstrap-table.html is rendering the inner HTML with markdownify. So my guess is that the img.html is outputting non-markdown syntax so the outer shortcode is not able to comprehend it.
I tested your bootstrap-table.html shortcode with regular image markdown syntax to insert images and that seems to work fine.
{{< bootstrap-table "someclassname" >}}
| animal | sound |
|--------|-------|
| ![alt text](https://i.imgur.com/JOKsNeT.jpg "cat") | meow |
| ![alt text](https://i.imgur.com/zq0bDrk.jpeg "dog") | woof |
{{< /bootstrap-table >}}
I tried all sorts of combinations of {{<. {{%. and so on. No joy. It looks like markdownify referenced from a shortcode definition doesn't allow embedded shortcodes that themselves render HTML.
This {{< tablestyle class="table-striped" >}} shortcode did work for me; it adds the class or classes to all tables in the page in the browser after the page loads, and it sets the tables' ids to table_0, table_1, etc.
A bit javascript-kludgey, but it works.
{{ $classes := .Get "class" }}
{{ $name := .Get "name" }}
{{ $filename := .Page.File.BaseFileName }}
<script>
window.addEventListener('DOMContentLoaded', (event) => {
try {
var filename = {{ $filename }} || "page"
filename = filename.toLowerCase()
var name = {{ $name }}
name = name || filename || "t"
var tables = document.querySelectorAll("body section article table")
var classes = {{ $classes }}
var classarray = classes.split(/\s+/)
for (var i = 0; i < tables.length; i++){
var table = tables[i]
for (var c = 0; c < classarray.length; c++ ) {
table.classList.add(classarray[c])
}
var id = "table_" + i
if (!table.id) table.id = id
if (!table.getAttribute("name")) table.setAttribute ("name", id)
table.classList.add(id)
table.classList.add(name + "_table")
}
}
catch (e) {
/* empty, intentionally, don't honk out if this doesn't work. */
}
});
</script>
here is the ultimate table shortcode.
Features: HTML5 compatibility (no align-*), markdown alignment, Bootstrap 4/5 compatibility, support, Schema.org markup, WAI accessibility, custom CSS, custom Id, responsive (with CSS)
<script src="https://gist.github.com/djibe/7a8ba9516f4495dbd6fdf1d1de7a60fe.js"></script>
{{< table title="Optional title" class="optional CSS class declaration" id="optional- declaration-a-unique-one-will-be-generated" >}}
| Stade | DFG (CKD-EPI) | Définition |
|:-------:|:----------------------:|------------|
| 1 | > 90 | MRC avec DFG normal ou augmenté |
| 2 | 60-89 | MRC avec DFG légèrement diminué |
| 3A | 45-59 | IRC modérée |
| 3B | 30-44 | IRC modérée |
| 4 | 15-29 | IRC sévère |
| 5 | < 15 | IRC terminale |
{{< /table >}}

Laravel 5.6 How to take duplicated datas from column

And that i want to print each topic_id's count
show.blade.php
#foreach($questions as $question)
{{ $question->topic_id }}
#endforeach
ExamsController#index
$topics = Topic::all();
return view('exams.show', compact('topics','questions'));
Just want to take duplicated datas count and print.
| id | topic_id |
| ---|:--------:|
| 1 | 4 |
| 2 | 9 |
| 3 | 5 |
| 4 | 5 |
| 5 | 2 |
| 6 | 4 |
| 7 | 5 |
that i wanted result is count of each topic_id duplicates. its like
| id | topic_id |
| ---|:--------:|
| 1 | 4 |
| 6 | 4 |
2
| id | topic_id |
| ---|:--------:|
| 3 | 5 |
| 4 | 5 |
| 7 | 5 |
count = 3
You could make use of groupBy
$duplicates = Topic::selectRaw("count('id') as total, topic_id")
->groupBy('topic_id')
->get();
// pass the duplicates along with other variables to the view
return view('exams.show', compact('topics','questions', 'duplicates'));
and in your view you could do
#foreach ($duplicates as $duplicate)
{{ $duplicate->topic_id }} - {{ $duplicate->total }}
#endforeach
maybe you can use collection feature on laravel to group data by topic_id
$topic = Topic::all();
$topicArray = $topic->groupBy('topic_id')->toArray();
in your view you can simply use $topicArray to display your data & count its duplicate
#foreach ($topicArray as $key => $value)
#foreach ($value as $key2 => $value2)
| {{ $value2['id'] }} | {{ $value2['topic_id'] }} |<br>
#endforeach
count {{ count($value) }}<br><br>
#endforeach
I am not sure what duplicated datas you mean, but I believe you are looking for a distinct.
The distinct method allows you to force the query to return distinct
results
https://laravel.com/docs/5.6/queries#selects
$topics = Topic::distinct()->get();

Django Duplicate entry '2' for key 'user_id'

Im trying to do a registration page in Django 1.4.
These are my files:
view.py
mensaje = ""
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
usr = User.objects.create_user(username = form.cleaned_data['username'], email = form.cleaned_data['mail'], password = form.cleaned_data['pa$
cli = cliente(user=usr, nombre=form.cleaned_data['nombre'], apellidos = form.cleaned_data['apellidos'], empresa = form.cleaned_data['empresa$
mensaje = "Cliente %s guardado exitosamente con el username %s" % (cli.nombre,cli.user)
cli.save()
ctx = {'mensaje':mensaje}
return HttpResponseRedirect('/')
else:
mensaje = "el formulario no es valido"
ctx = {'form': form, 'mensaje': mensaje}
return render_to_response('pymes/register.html', ctx, context_instance=RequestContext(request))
else:
form = RegistrationForm()
context = {'form':form}
return render_to_response('pymes/register.html', context, context_instance=RequestContext(request))
models.py
class perfilCliente(models.base.ModelBase):
def _prepare(self):
super(perfilCliente, self)._prepare()
def create_cliente_user_callback(sender, instance, created, **kwargs):
if created:
self.objects.create(user=instance)
post_save.connect(create_cliente_user_callback, sender=User, weak=False)
class cliente(models.Model):
__metaclass__ = perfilCliente
user = models.OneToOneField(User)
nombre = models.CharField(max_length=200)
apellidos = models.CharField(max_length=200)
mail = models.CharField(max_length=200)
empresa = models.CharField(max_length=200)
status = models.BooleanField(default=True)
plan = models.ForeignKey('pymes.plan',null=True,blank=True)
def __unicode__(self):
nombreCompleto = "%s %s"%(self.nombre,self.apellidos)
return nombreCompleto
register.html
{% extends "base.html" %}
{% block title %} Login {% endblock %}
{% block content %}
{{ mensaje }}
<form action="" method="post">
{% csrf_token %}
{% if form.errors %}<p> Corregir los campos: </p> {% endif %}
<div class="register_div">
{% if form.nombre.errors %}<p class="error">{{ form.nombre.errors }}</p>{% endif %}
<p><label for="nombre"{% if form.nombre.errors %} class="error"{% endif %}>Nombre:</label>{{ form.nombre }}</p>
</div>
<div class="register_div">
{% if form.apellido.errors %}<p class="error">{{ form.apellido.errors }}</p>{% endif %}
<p><label for="apellido"{% if form.apellido.errors %} class="error"{% endif %}>Apellido:</label>{{ form.apellidos }}</p>
</div>
<div class="register_div">
{% if form.empresa.errors %}<p class="error">{{ form.empresa.errors }}</p>{% endif %}
<p><label for="empresa"{% if form.empresa.errors %} class="error"{% endif %}>Empresa:</label> {{ form.empresa }}</p>
</div>
<div class="register_div">
{% if form.mail.errors %}<p class="error">{{ form.mail.errors }}</p>{% endif %}
<p><label for="mail"{% if form.mail.errors %} class="error"{% endif %}>Email:</label> {{ form.mail }}</p>
</div>
<div class="register_div">
{% if form.username.errors %} <p class="error">{{ form.username.errors }}</p>{% endif %}
<p><label for="username"{% if form.username.errors %} class="error"{% endif %}>Username:</label> {{ form.username }}</p>
</div>
<div class="register_div">
{% if form.password.errors %}<p class="error">{{ form.password.errors }}</p>{% endif %}
<p><label for="password"{% if form.password.errors %} class="error"{% endif %}>Password:</label> {{ form.password }}</p>
</div>
<div class="register_div">
{% if form.passworduno.errors %}<p class="error">{{ form.passworduno.errors }}</p>{% endif %}
<p><label for="password1"{% if form.passworduno.errors %} class="error"{% endif %}>Verify Password:</label>{{ form.passworduno }}</p>
</div>
<p><input type="submit" alt="register" /></p>
</form>
The pages works fine but, when send the form show me this error:
Request Method: POST
Request URL: http://192.168.2.106:8000/register/
Django Version: 1.4.5
Python Version: 2.7.3
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'saas.apps.pymes',
'django.contrib.admindocs')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/root/project/saas/saas/apps/pymes/views.py" in register_view
52. cli.save()
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in save
463. self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in save_base
551. result = manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py" in _insert
203. return insert_query(self.model, objs, fields, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in insert_query
1593. return query.get_compiler(using=using).execute_sql(return_id)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py" in execute_sql
912. cursor.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/util.py" in execute
40. return self.cursor.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/mysql/base.py" in execute
114. return self.cursor.execute(query, args)
File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py" in execute
174. self.errorhandler(self, exc, value)
File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py" in defaulterrorhandler
36. raise errorclass, errorvalue
Exception Type: IntegrityError at /register/
Exception Value: (1062, "Duplicate entry '3' for key 'user_id'"
This create a new user properly in database with id=3
mysql> select * from auth_user;
+----+-----------+------------+-----------+--------------------+----------+----------+-----------+--------------+---------------------+---------------------+
| id | username | first_name | last_name | email | password | is_staff | is_active | is_superuser | last_login | date_joined |
+----+-----------+------------+-----------+--------------------+-------------------------------------------------------------------------------+----------+-----------+--------------+---------------------+---------------------+
| 1 | root | | | sdfds#sdfa.com | pass1 | 1 | 1 | 1 | 2013-04-01 07:49:58 | 2013-04-01 07:49:58 |
| 2 | oespinoza | | | zdssd#yahoo.es | pass2 | 0 | 1 | 0 | 2013-04-01 07:50:46 | 2013-04-01 07:50:46 |
| 3 | loco | | | sdfsd | pass3 | 0 | 1 | 0 | 2013-04-01 08:03:37 | 2013-04-01 08:03:37 |
+----+-----------+------------+-----------+--------------------+---------+----------+-----------+--------------+---------------------+---------------------+
And the realtionship works fine too. But, in table "cliente" show only this:
mysql> select * from pymes_cliente;
+----+---------+--------+-----------+------+---------+--------+---------+
| id | user_id | nombre | apellidos | mail | empresa | status | plan_id |
+----+---------+--------+-----------+------+---------+--------+---------+
| 1 | 1 | | | | | 1 | NULL |
| 2 | 2 | | | | | 1 | NULL |
| 4 | 3 | | | | | 1 | NULL |
+----+---------+--------+-----------+------+---------+--------+---------+
Help me please.
It looks like you are creating 2 instance of your Profile object for every registration: the first in your view, and a second via your signal.
# Create & save User object
usr = User.objects.create_user(...)
...
# Create profile
cli = cliente(user=usr, ...)
# Save profile & fire your signal
cli.save()
In your signal
# Creates second profile with same user object, causing error
self.objects.create(user=instance)
Delete the signal (and the _prepare) and the issue should go away.
Sidenote: I'm not sure why you are registering your signal in the _prepare method. It's usually best to register any signals at the bottom of your models file:
class Client(models.Model):
...
def create_cliente_user_callback(sender, instance, created, **kwargs):
...
post_save.connect(create_cliente_user_callback, sender=User, weak=False)

Styling octopress image layout (eg images all in a row)

Any tips on styling image layout with the {%img ... %} plugin?
I'm ok with left and right but I'd really like to have all images in a row vertically for example and can't quiet figure out how to style things.
I thought perhaps add a <div class="right"> around a bunch on {% img ... %} but that seems to mess with the HTML too much.
Thanks in advance for any pointers
ps, I saw this question but it didn't answer my question exactly
In markdown, you can write tables using the following syntax
-----------------
| A | B |
| :---: | :---: |
| C | D |
-----------------
The two points on each side of the horizontal lines define the alignment of your cells:
centered: :--:
left: :---
right: ---:
You can use as many dashes as you want in the middle.
I used this technique to align images as a table in this blog post (search for "Nil" inside). It looks like this:
using this code:
| Nil | Inline / list | Table |
| :---: | :---: | :---: |
| {% img /images/2013-02-04-nil.png 36 92 Nil line numbers %} | {% img /images/2013-02-04-inline.png 62 92 Inline line numbers %} | {% img /images/2013-02-04-table.png 72 92 Table line numbers %} |