Django extends not working - python

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>>

Related

Trying to show model data on web page by using ListView. Its not working

I created the model post and I want to show all the posts on Web Page using Class-based views but It's not working. the URL is opening but the web page is not showing anything( stuff that is on homepage.html and on _post.html but navbar is there which is coming from _inject.html). The problem is in coding in the template.
Post Model-
class Post(models.Model):
auther = models.ForeignKey(User, related_name="posts",on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now=True)
heading = models.CharField(max_length=400)
message = models.TextField()
message_html = models.TextField(editable=False)
def __str__(self):
return self.message
def save(self,*args,**kwargs):
self.message_html = misaka.html(self.message)
super().save(*args,**kwargs)
def get_absolute_url(self):
return reverse('posts:single',kwargs={'username':self.user.username,'pk':self.pk})
class Meta:
ordering = ['-created_at']
unique_together = ['auther','message']
Post view-
class ListPosts(generic.ListView):
model = models.Post
template_name = "homepage.html"
homepage.html
{% extends "_inject.html" %}
{% block content %}
<div class="col-md-8">
{% if post.count == 0 %}
<h2>No posts in this group yet!</h2>
{% else %}
<ul>
{% for p in Post.all %}
<h1>p.message</h1>
<li> {% include "_post.html" %} </li>
{% endfor %}
</ul>
{% endif %}
</div>
{% endblock %}
_post.html-
<div class="media">
<h3 class="mr-5">#{{ post.user.username }}</h3>
<div class="media-body">
<strong>{{ p.user.username }}</strong>
<h5>{{ p.message_html|safe }}</h5>
<time class="time">{{ p.created_at }}</time>
<div class="media-footer">
{% if user.is_authenticated and post.user == user and not hide_delete %}
<a href="{% url 'posts:delete' pk=post.pk %}" title="delete" class="btn btn-simple">
<span class="fa fa-remove text-danger" aria-hidden="true"></span>
<span class="text-danger icon-label">Delete</span>
</a>
{% endif %}
</div>
</div>
</div>
Try changing your homepage.html to something like this:
{% extends "_inject.html" %}
{% block content %}
<div class="col-md-8">
{% if post_list %}
{% for post in post_list %}
<h1>{{post.message}}</h1>
<li>{% include "_post.html" %} </li>
{% endfor %}
{% else %}
<h2>No posts in this group yet!</h2>
{% endif %}
</div>
{% endblock %}

Access model properties in Django Admin templates?

I have Django 2.0.3 on Python 3.5.3. I search for simple way to small improve my standard Django Admin dashboard (main page of Django Admin).
Here is my template for Admin main page ./templates/admin/index.html:
{% extends "admin/base_site.html" %}
{% load i18n static %}
{% block extrastyle %}{{ block.super }}
<link rel="stylesheet" type="text/css" href="{% static "admin/css/dashboard.css" %}"/>{% endblock %}
{% block coltype %}colMS{% endblock %}
{% block bodyclass %}{{ block.super }} dashboard{% endblock %}
{% block breadcrumbs %}{% endblock %}
{% block content %}
<div id="content-main">
{% if app_list %}
{% for app in app_list %}
<div class="app-{{ app.app_label }} module">
<table>
<caption>
<a href="{{ app.app_url }}" class="section"
title="{% blocktrans with name=app.name %}Models in the {{ name }} application{% endblocktrans %}">{{ app.name }}</a>
</caption>
{% for model in app.models %}
<tr class="model-{{ model.object_name|lower }}">
{% if model.admin_url %}
<th scope="row">{{ model.name }}</th>
{% else %}
<th scope="row">{{ model.name }}</th>
{% endif %}
{% if model.add_url and request.user.is_superuser %}
<td>{% trans 'Add' %}</td>
{% else %}
<td> </td>
{% endif %}
{% if model.admin_url and request.user.is_superuser %}
<td>{% trans 'Change' %}</td>
{% else %}
<td> </td>
{% endif %}
</tr>
{% endfor %}
</table>
</div>
{% endfor %}
{% else %}
<p>{% trans "You don't have permission to edit anything." %}</p>
{% endif %}
</div>
{% endblock %}
I delete sidebar block, because I never use it. And it looks like:
I want to add to each model link count of objects. For example, Cities (23), Citizenships (102) and similar for all models in list. I try to add function with #property decorator in ./app/models.py, but it's not working:
class APIConfig(models.Model):
...
#property
def with_active_status(self):
return self.objects.filter(is_active=True).count()
...
I call this property in Admin template, like {{ model.with_active_status }} and it shows nothing.
This can't be a property. You don't have an instance of the model to call it on. In any case, if you did have an instance it still wouldn't work, as model managers - objects - can only be accessed from the class, not the instance.
You should make it a classmethod:
#classmethod
def with_active_status(cls):
return cls.objects.filter(is_active=True).count()

Django Uploading Files

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

DetailView template is not showing value of selected record. in django

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

Something like publish notes in a webpage

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 %}

Categories