I'm building a site where I publish a notice and it appear in one webpage but my code dosen't return the objects. I post my code then:
Models:
from django.db import models
class Contenidos(models.Model):
title = models.CharField(max_length = 255)
content = models.TextField()
created = models.DateTimeField(auto_now_add=True)
published = models.BooleanField(default=True)
class Meta:
ordering = ['-created']
def __unicode__(self):
return u'%s' % self.title
Views:
from django.shortcuts import render
from granada.models import Contenidos
def contenidos(request):
contenido_list = Contenidos.objects.all()
return render(request, 'contenidos.html', {'contenido_list' : contenido_list})
contenidos.html
{% extends 'base.html' %}
{% block title %} Contenidos {% endblock %}
{% block content %}
<h2> contenidos </h2>
{% for contenido in contenido_list %}
<h3>
{{ contenido_list.title }}
</h3>
<p>{{ contenido_list.content }}</p>
{% endfor %}
{% endblock %}
You're accessing the wrong object in your loop, contenidos instead of contenido.
{% extends 'base.html' %}
{% block title %} Contenidos {% endblock %}
{% block content %}
<h2> contenidos </h2>
{% for contenido in contenidos %}
<h3>
{{ contenido.title }} {# was contenidos.title #}
</h3>
<p>{{ contenido.content }}</p>
{% endfor %}
{% endblock %}
Related
The 'Thumbnail' attribute has no file associated with it.
I have tried Django {% if %} {% else %} {% endif %} in my HTML list and it works on the page, but when I do the same for a detailview HTML it doesn't work and returns "The 'Thumbnail' attribute has no file associated with it."
** Models.py **
class Article(models.Model):
Title = models.CharField(max_length=150)
Thumbnail = models.ImageField(blank=True, null=True)
Author = models.ForeignKey(Author, on_delete=models.CASCADE)
Content = QuillField()
Date = models.DateField(auto_now_add=True)
slug = AutoSlugField(populate_from='Title')
** Views.py**
class ArticlesDetailView(DetailView):
model = Article
template_name = 'articles_app/articles_detail.html'
def get_context_data(self, **kwargs):
latest = Article.objects.order_by('-id')[0:3]
context = super().get_context_data(**kwargs)
context['latest'] = latest
return context
** HTML - List (articles_list.html) ** It works perfectly fine here!!!
<img src=" {% if articles.Thumbnail %}
{{ articles.Thumbnail.url }}
{% else %}
{% static 'img/add-ons/article_thumbnail_default.jpg' %}
{% endif %} " alt="..." class="card-img-top">
** HTML - Detail (articles_detail.html) ** It doesn't work here.
{% for obj in latest %}
<img src="{% if obj.Thumbnail %}
{{ obj.Thumbnail.url }}
{% else %}
{% static 'img/add-ons/article_thumbnail_default.jpg' %}
{% endif %} " alt="..." class="card-img-top">
{% endfor %}
What am I doing wrong? Please help!
try object.Thumbnail instead of obj.Thumbnail, I think that will solve your problem.
I have a problem with execute html view. I have base.html which do not showing the child views from another files. Can anybody help me what I doing wrong? Here are my files:
models.py
from django.db import models
from django.utils import timezone
class Kategorie(models.Model):
glowna = models.CharField(max_length=150, verbose_name='Kategoria')
class Meta:
verbose_name='Kategoria'
verbose_name_plural='Kategorie'
def __str__(self):
return self.glowna
class Witryna(models.Model):
nazwa = models.CharField(default="", max_length=150, verbose_name = 'Nazwa strony')
adres_www = models.CharField(max_length=70, verbose_name='Adres www')
slug = models.SlugField(max_length=250, verbose_name='Przyjazny adres url')
email = models.CharField(max_length=100, verbose_name='Adres e-mail')
text = models.TextField(max_length=3000, verbose_name='Opis strony')
kategoria = models.ForeignKey(Kategorie, verbose_name='Kategoria')
data_publikacji = models.DateTimeField(blank=True, null=True, verbose_name='Data publikacji')
class Meta:
verbose_name='Strona www'
verbose_name_plural = 'Strony www'
def publikacja(self):
self.data_publikacji=timezone.now()
self.save()
def __str__(self):
return self.nazwa
urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^strony$', views.widok_strony, name='widok_strony'),
url(r'^$', views.widok_kategorii, name='widok_kategorii'),
]
views.py
from django.shortcuts import render
from .models import Witryna, Kategorie
from django.utils import timezone
#from django.db.models import Count
def widok_strony(request):
firmy = Witryna.objects.filter(data_publikacji__lte=timezone.now()).order_by('data_publikacji')
return render(request, 'firmy/widok_strony.html', {'firmy': firmy})
def widok_kategorii(request):
kategorie = Kategorie.objects.all()
wpisy_kat = Kategorie.objects.count()
return render(request, 'firmy/widok_kategorii.html', {'kategorie': kategorie, 'wpisy_kat': wpisy_kat})
widok_kategorii.html
{% extends 'firmy/base.html' %}
{% block kategorie %}
{% for kategoria in kategorie %}
<table>
<tr>
<th>
{{ kategoria.glowna|linebreaksbr }} ({{ wpisy_kat }})
</th>
</tr>
</table>
{% endfor %}
{% endblock kategorie%}
widok_strony.html
{% extends 'firmy/base.html' %}
{% block firmy %}
{% for firma in firmy %}
<div>
<img src="http://free.pagepeeker.com/v2/thumbs.php?size=s&url={{ firma.adres_www }}"/>
{{ firma.nazwa }}<p>
</div>
{% endfor %}
{% endblock %}
base.html
{% include 'firmy/header.html' %}
<html>
<body>
<h4>Ostatnio dodane</h4>
{% block firmy %}
{% endblock %}
<h4>Kategorie</h4>
{% block kategorie %}
{% endblock %}
</body>
{% include 'firmy/footer.html' %}
</html>
When I try to run localhost:8000 the base.html showing me only the view from widok_kategorii.html file.Of course when I change the url to localhost:8000/strony that page is loading perfectly. But I want to have this two html files on the one page base.html
Have you tried renaming your blocks so that they do not overlap with the names of arguments you are passing through view.py.
I would try the following:
widok_kategorii.html
{% extends 'firmy/base.html' %}
{% block content_kat %}
{% for kategoria in kategorie %}
<table>
<tr>
<th>
{{ kategoria.glowna|linebreaksbr }} ({{ wpisy_kat }})
</th>
</tr>
</table>
{% endfor %}
{% endblock %}
widok_strony.html
{% extends 'firmy/base.html' %}
{% block content_firm %}
{% for firma in firmy %}
<div>
<img src="http://free.pagepeeker.com/v2/thumbs.php?size=s&url={{ firma.adres_www }}"/>
{{ firma.nazwa }}<p>
</div>
{% endfor %}
{% endblock %}
base.html
{% include 'firmy/header.html' %}
<html>
<body>
<h4>Ostatnio dodane</h4>
{% block content_firm %}
{% endblock %}
<h4>Kategorie</h4>
{% block content_kat %}
{% endblock %}
</body>
{% include 'firmy/footer.html' %}
</html>
Realize that you will not get both content on the same page at one instance. If you would like to have both content on the same page then you need to combine the views and htmls.
I would do the following:
views.py
def widok_strony_kategorii(request):
firmy = Witryna.objects.filter(data_publikacji__lte=timezone.now()).order_by('data_publikacji')
kategorie = Kategorie.objects.all()
wpisy_kat = Kategorie.objects.count()
return render(request, 'firmy/widok_strony_kategorii.html', {'firmy': firmy,'kategorie': kategorie, 'wpisy_kat': wpisy_kat})
firmy/widok_strony_kategorii.html
{% extends 'firmy/base.html' %}
{% block content_kat %}
{% for kategoria in kategorie %}
<table>
<tr>
<th>
{{ kategoria.glowna|linebreaksbr }} ({{ wpisy_kat }})
</th>
</tr>
</table>
{% endfor %}
{% endblock %}
{% extends 'firmy/base.html' %}
{% block content_firm %}
{% for firma in firmy %}
<div>
<img src="http://free.pagepeeker.com/v2/thumbs.php?size=s&url={{ firma.adres_www }}"/>
{{ firma.nazwa }}<p>
</div>
{% endfor %}
{% endblock %}
firmy/base.html
<<Same as the edited one above>>
I have a dashboard where you upload files and can see the files you uploaded. Strangely enough, when you go to upload a second file, it uploads but gives the error: IntegrityError at /dashboard/ column client_id is not unique I'm not sure why. My database is fresh and clean. What would cause this? The first file uploads and displays correctly redirecting you to the dashboard. The second file uploads, but doesn't display in the file list and displays that error. Any ideas why this is occurring or how to fix this error? I'm really stuck here so any help would save me big time.
Here is the view:
#login_required(login_url='/dashboard-login/')
def dashboard(request):
current_user = request.user
current_client = request.user.client
files = ClientUpload.objects.filter(client=current_client)
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
new_file = ClientUpload(client=current_client, file_upload = request.FILES['file_upload'])
new_file.save()
return HttpResponsePermanentRedirect('/dashboard/')
else:
form = UploadFileForm()
data = {'form': form, 'client': current_client, 'files': files}
return render_to_response('dashboard.html', data, context_instance=RequestContext(request))
The models:
#python_2_unicode_compatible
class Client(models.Model):
user = models.OneToOneField(User)
company = models.CharField(max_length=100)
def __str__(self):
return self.company
class Meta:
verbose_name_plural = _("Clients")
verbose_name = _("Client")
permissions = (
("can_upload", _("Can upload files.")),
("can_access_uploads", _("Can access upload dashboard.")),
("is_client", _("Is a client.")),
)
def generate_filename(self, filename):
name = "uploads/%s/%s" % (self.client.company, filename)
return name
#python_2_unicode_compatible
class ClientUpload(models.Model):
client = models.OneToOneField(Client)
created_at = models.DateTimeField(auto_now_add=True)
file_upload = models.FileField(upload_to=generate_filename)
def __str__(self):
return self.client.company
class Meta:
verbose_name_plural = _("Client Uploads")
verbose_name = _("Client Upload")
The form:
class UploadFileForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.add_input(Submit(_('submit'), _('Submit')))
super(UploadFileForm, self).__init__(*args, **kwargs)
class Meta:
model = ClientUpload
fields = ('file_upload',)
And lastly, the templates:
Upload file:
{% load i18n %}
{% load crispy_forms_tags %}
{% crispy form %}
File list:
{% load i18n %}
<table class="table">
<tr>
<th>{% blocktrans %}Filename{% endblocktrans %}</th>
<th>{% blocktrans %}Size{% endblocktrans %}</th>
<th>{% blocktrans %}Upload Time{% endblocktrans %}</th>
</tr>
{% for file in files %}
{% with uploaded_file=file.file_upload %}
<tr>
<th><a href='{{ uploaded_file.url }}'>{{ uploaded_file.name }}</a></th>
<th>{{ uploaded_file.size }}</th>
<th>Uploaded At</th>
{% endwith %}
{% endfor %}
</tr>
</table>
And the one that ties them together, dashboard:
{% extends "base.html" %}
{% load i18n %}
{% block title %}Shenkan & Associates - {% trans 'Dashboard' %}{% endblock title %}
{% block css %}
{{ block.super }}
{% endblock css %}
{% block extra_css %}
{% endblock extra_css %}
{% block ie_shim %}
{{ block.super }}
{% endblock ie_shim %}
{% block header %}
{{ block.super }}
{% endblock header %}
{% block slider %}
{% endblock slider %}
{% block page_header %}{% endblock page_header %}
{% block content %}
<!--=== Content ===-->
{% trans 'Logout' %}
<div class="container content-md">
{% include "upload_file.html" %}
</div>
<div class="container content-md">
{% include "file_list.html" %}
</div>
<!--=== End Content ===-->
{% endblock content %}
{% block footer %}
{{ block.super }}
{% endblock footer %}
{% block js %}
{{ block.super }}
{% endblock js %}
{% block ie_js %}
{{ block.super }}
{% endblock ie_js %}
{% block extra_js %}
{% endblock extra_js %}
You don't need to see base.html obviously.
If someone could help me solve this mystery it would help a ton as I am having tons of problems with this and have been stuck for days.
Thanks a bunch.
I think you should use "get_or_create" in the views.
I hope this can help: get_or_create throws Integrity Error
On DetailView template I am not able to print name,date of post only '|' sign is being printed but on ListView it is working fine. Here is code written in files. Thanks!!
blog/urls.py
urlpatterns = patterns('',url(r'^$', ListView.as_view(queryset =
Blog.objects.all(), template_name ='blog.html')),
url(r'^(?P<pk>\d+)/$', DetailView.as_view(model=Blog, template_name='detail.html')), )
blog.html
{% extends 'base.html' %}
{% block content %}
{% for post in object_list %}
<ul> {{ post.name }} ||{{ post.date }}</ul>
{% endfor %}
{% endblock %}
detial.html
{% extends 'base.html' %}
{% block content %} <h2> <a href="/blog/{{ post.id }}">{{ post.name }}
</a>||{{ post.date }}</h2> {% endblock %}
context_object_name Designates the name of the variable to use in the context. Default is "object"
Try
{% extends 'base.html' %}
{% block content %} <h2> <a href="/blog/{{ object.id }}">{{ object.name }}
</a>||{{ object.date }}</h2> {% endblock %}
See SingleObjectMixin and making-friendly-template-contexts
I am trying to get a list of all manuscripts in my db, print out the shelfmarks for each of them and in case that they are linked to other manuscripts also print out the shelfmarks of those manuscripts.
Here is what my models look like:
class MSS(models.Model):
shelfmark = models.CharField(max_length=50)
MSSLink = models.ManyToManyField('self',through='MSSLink',symmetrical=False)
[...]
class MSSLink(models.Model):
link1 = models.ForeignKey('MSS', related_name='First_MSS')
link2 = models.ForeignKey('MSS', related_name='Second_MSS')
[...]
Here is the code in views.py
def show_all_MSS(request):
all_MSS = MSS.objects.select_related().all() # get all MSS
t = loader.get_template('list.html')
c = Context({'all_MSS': all_MSS, })
return HttpResponse(t.render(c))
The question is then what to do in my template. I thought about doing something like this, but I don't know how I can test whether the current MS in the for-loop has been linked to another MS and if so how to display those shelfmarks:
{% if all_MSS %}
<ul>
{% for i in all_MSS %}
<li>{{ i.shelfmark }}</li>
{% if i.MSSLink %}
<p>This MS is linked to the following MSS: {{ i.MSSLink.link1 }}</p>
{% endif %}
{% endfor %}
</ul>
{% else %}
<p>No MSS found</p>
{% endif %}
Your models are a bit complicated - you can probably get rid of MSSLink:
class MSS(models.Model):
shelfmark = models.CharField(max_length=50)
links = models.ManyToManyField('self', symmetrical=False, blank=True)
def __unicode__(self):
return self.shelfmark
and add this to your template:
{% if i.links.all %}
<ul>
{% for l in i.links.all %}
<li>{{ l.shelfmark }}</li>
{% endfor %}
</ul>
{% endif %}