UPDATE #1:
I'm still having some issues, I'm getting some of the content using tags like {{object.title}}, but content that I've included using {% include "sidebar.html" %} and {% include "slider.html" %} are not showing up.
Part of my sidebar.html looks like this:
<div class="navItem">
<div class="overlay">
</div><!-- /.overlay -->
<img src="{{article.relatedImage}}" alt="" class="navPicture">
<p class="navTitle">{{article.title|truncatewords:"4"}}</p>
</div><!-- /.navItem -->
I'm doing a class assignment and I'm using the same tags as I have on my main page on my detailed page in Django, but the actual content on the detailed page is not showing up when I use the {{tags}}.
Snippet of detailed.html
<p class="date">{{article.pubDate|date:"l, F j, Y" }}</p> | {{article.author}}
<img src="{{article.heroImage}}" alt="" class="largeImage">
<div class="contentBlock">
<img src="{{article.relatedImage}}" alt="" class="relatedImage">
views.py
from django.views import generic
from . import models
# Create your views here.
class BlogIndex(generic.ListView):
queryset = models.FullArticle.objects.published()
template_name = "list.html"
class BlogDetail(generic.DetailView):
model = models.FullArticle
template_name = "detailed.html"
urls.py
from django.conf.urls import patterns, url
from . import views
urlpatterns = patterns(
'',
url(r'^$', views.BlogIndex.as_view(), name="list"), url(r'^(?P<slug>\S+)$', views.BlogDetail.as_view(), name="detailed"),
)
Screenshot of list.html: http://imgur.com/vygVAkj
Screenshot of detailed.html: http://imgur.com/umnCE27
You are using {{ article }} in your template. Which is undefined. Either user {{ object }}, either specify context_object_name = 'article' in your Detail View.
Moreover, you are using white spaces for identifying your objects??? i.e. you are doing stuff like models.FullArticle.objects.get(pk=' ') which is really weird.
Mihai zamfir was right.
Here's the full code - this should be in your views.py
class FoodDetail(DetailView)
model = FoodPost
context_object_name = 'post'
template_name = 'views/detail-views/food-details.html'
for urls.py
path('posts/<str:link>/<int:pk>', FoodDetail.as_view(), name="food-detail")
and inside details view
<h1>{{post.pk}}</h1>
and the template from which you are referring should be
read more
Related
My detail View in Django, isn't successfully displaying the content selected from the listviews. The following is my code.
Models.py:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Post_Model(models.Model):
Title = models.CharField(max_length=50)
Author = models.ForeignKey(User, on_delete=models.CASCADE)
Body = models.TextField()
def __str__(Self):
return Self.Title + ' | ' + str(Self.Author)
urls.py:
from django.urls import path
from .views import Article_details, Home_page
urlpatterns = [
path('', Home_page.as_view(), name="Home"),
path('Article/<int:pk>/', Article_details.as_view(), name="Article"),
Views.py:
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from . models import Post_Model
class Home_page(ListView):
model = Post_Model
template_name = 'June11App/Home.html'
class Article_details(DetailView):
model = Post_Model
template_name = 'June11App/Article.html'
Html list view:
<h1>Home Page</h1>
<ul>
{% for Post in object_list %}
<li>
<a href="{% url 'Article' Post.pk %}">
{{Post.Title}}
</a>
- {{Post.Author}}<br>
{{Post.Body}}
</li>
<br>
{% endfor %}
</ul>
Html detail view:
<h1>Article Page</h1><br>
{{Post.Author}}
{{Post.Body}}
I hope my query made sense. I don't receive any error on myside, its just not working as it should.
The object data is passed as object and post_model, not Post, so:
<h1>Article Page</h1><br>
{{ object.Author }}
{{ object.Body }}
Note: Models normally have no …Model suffix. Therefore it might be better to rename Post_Model to Post.
Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.
Note: normally the name of the fields in a Django model are written in snake_case, not PascalCase, so it should be: author instead of Author.
Django Blog APP comes with an out of the box index.html where it shows a list of all posts.
I need to show this list in a new URL, when I somply copy the html code from index.html and paste onto planoacao.html it doesn´t show anything.
This is the index.html:
{% for post in post_list %}
<div class="card mb-4" style="width: 18rem; ">
{% if post.get_finalizado_display == 'Não' %}
<!--<p class="card-text text-muted h6"> NOK </p>-->
<div class="card-body" style="background-color:#FF0909;">
{% else %}
<!--<p class="card-text text-muted h6"> ok </p>-->
<div class="card-body">
{% endif %}
{% endfor %}
This is my views.py:
from django.views import generic
from .models import Post
class PostList(generic.ListView):
queryset = Post.objects.filter(status=1).order_by('-created_on')
template_name = 'index.html'
class PostDetail(generic.DetailView):
model = Post
template_name = 'post_detail.html'
class Calendar(generic.DetailView):
model = Post
template_name = 'calendar.html'
class Planoacao(generic.DetailView):
model = Post
template_name = 'planoacao.html'
This is my urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')),
url(r'^planoacao/', TemplateView.as_view(template_name="planoacao.html")),
url(r'calendar', TemplateView.as_view(template_name="calendar.html")),
url(r'^admin/', admin.site.urls),
url(r'^', include('blog.urls'), name="Blog"),
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
How can I show a list of all posts in a different URL? xxx/planoacao.html ? Simply copying the html from index.html doesn´t work.
Note that I don´t want to change the regular index.html post list, I just want to add a second post list page.
It seems you want to show your PostList view at /planoacao, so in urls.py you can hook this path up to that view:
url(r'^planoacao/', PostList.as_view()),
Note that in Django there is no direct link between the path of a view and the template used. You can use any template with any path, all you have to do is define which template to use in the view.
Why am I getting an error when trying to run my server to access the database to see if my code works? While in my projects folder in Terminal, I ran sudo python manage.py runserver to try to run the server but it doesn't work because of the aforementioned error. I've looked around SO but can't find one directly related to my problem.
I'm guessing my if() statement is the problem.
The error I'm getting says:
RuntimeError: maximum recursion depth exceeded while calling a Python object
Here's my views.py file:
from .models import Album
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.core.urlresolvers import reverse_lazy
from django.views import generic
from django.views.generic import View
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from .forms import UserForm
class IndexView(generic.ListView):
template_name = 'music/index.html'
context_object_name = 'all_albums'
def get_queryset(self):
return Album.objects.all()
class DetailView(generic.DeleteView):
model = Album
template_name = 'music/detail.html'
class AlbumCreate(CreateView):
model = Album
fields = ['artist', 'album_title', 'genre', 'album_logo']
class AlbumUpdate(UpdateView):
model = Album
fields = ['artist', 'album_title', 'genre', 'album_logo']
class AlbumDelete(DeleteView):
model = Album
success_url = reverse_lazy('music:index')
class UserFormView(View):
form_class = UserForm
template_name = 'music/registration_form.html'
# display blank form
def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
def post(self):
form = self.form_class(request.POST)
if form.is_valid():
user = form.save(commit=False)
#cleaned normalized data
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user.set_password(password)
user.save()
Here's the error:
File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/urls/resolvers.py", line 255, in check
warnings.extend(check_resolver(pattern))
File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/core/checks/urls.py", line 26, in check_resolver
return check_method()
File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/urls/resolvers.py", line 172, in check
warnings = self._check_pattern_startswith_slash()
File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/urls/resolvers.py", line 140, in _check_pattern_startswith_slash
regex_pattern = self.regex.pattern
Here's my forms.py file:
from django.contrib.auth.models import User
from django import forms
class UserForm(forms.ModelForm): # UserForm inherits from forms.
passwords = forms.CharField(widget=forms.PasswordInput)
class Meta: # Information about your class.
model = User # whenevr a creates sign up to your site it's gonna go in same table
fields = ['username', 'email', 'password']
Here's my urls.py file:
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
app_name = 'music'
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^music/', include('music.urls'))
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root = settings.STATIC_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.MEDIA_ROOT)
Here's my album_form.html file:
{% extends 'music/base.html' %}
{% block title %}Add a New Album{% endblock %}
{% block album_active %}active{% endblock %}
{% block body %}
<div class="container-fluid">
<div class="row">
<div class="col-sm-12 col-md-7">
<div class="panel panel-default">
<div class="panel-body">
<form class="horizontal" action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% include 'music/form-template.html' %}
<div class="form-group">
<div class="col-sum-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
Here's my index.html file:
{# loads path to static file #}
{% extends 'music/base.html' %}
{% block body %}
<ul>
{% for album in all_albums %}
<li>{{ album.album_title }}</li>
{% endfor %}
</ul>
{% endblock %}
I suspect you have a recursive reference from your include in music.urls to urls.py since the error that django throws is specific to URL resolver.
Your if statement has no error. 'music:index' refers to namespaced url names and still need named url statements in urls.py. Since in simple projects, there is only one application, the namespace is redundant. So in most cases, 'index' should be used instead, just like what I have show below.
In your urls.py, there is a include to music.urls, and it seems to be recursive reference to itself. 'music.urls' refers to the file urls.py in music directory.
If you do not have a valid python object for 'music.urls', then your include statement is wrong.
I do not use include urls in my project, so there will need to be a statement for each view defined in views.py. To test whether your server starts correctly, I would try the following urlpatterns. Don't forget to import IndexView and DetailView. Add more url statements for you other views after testing out 1 or 2 first.
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^music/index/$', IndexView.as_view() , name='Index'),
url(r'^music/detail/(?P<pk>[0-9]+)/$', DetailView.as_view() , name='Detail'),
]
I use named url, and the statement in index.html should be written as follows:
{{ album.album_title }}
The namespace 'music:' is omitted since it is implicit and will look simpler. You should leave it out for simple applications as it may be confusing for beginners.
I'm a starter of Django1.10. I just started play around with it. I am trying to show an image on website.
This is myproject/settings.py:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
and myproject/urls.py
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^poster/', include('poster.urls')),
url(r'^admin/', admin.site.urls ),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
myproject/app/views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Info
# give a set of summary of items
def index(request):
latest_item_list = Info.objects.all()
context = {'latest_item_list': latest_item_list}
return render(request, 'poster/index.html', context)
def detail(request, item_id):
return HttpResponse("This function will return detail info for items %s" % item_id)
myproject/app/models.py
from django.db import models
class Info(models.Model):
def __str__(self):
return self.info_text
info_text = models.CharField(max_length=50)
pub_date = models.DateTimeField('date published')
info_image = models.ImageField(upload_to='images/%Y%m/%d')
myproject/app/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
# ex:/poster
url(r'^$', views.index, name='index'),
# ex: /poster/5
url(r'^(?P<item_id>[0-9]+)/$', views.detail, name = 'detail'),
]
myproject/app/templates/app/index.html
{% if latest_item_list %}
<ul>
{% for item in latest_item_list %}
{{forloop.counter}}.{{ item.info_text }}
{% endfor %}
</ul>
{% else %}
<p>No poster are available.</p>
{% endif %}
If I run python manage.py runserver, and go http://127.0.0.1:8000/poster/. I can see one object I created before, when I click it, the url it points to get repeated many times
I believe there is something wrong in the url.py, but I am not sure. Can someone help?
First of all I think you are missing a forwardshals in your models.py on line :
info_image = models.ImageField(upload_to='images/%Y%m/%d')
Unless it's your intention, I think it should be like this:
info_image = models.ImageField(upload_to='images/%Y/%m/%d')
^
Next thing is that you are not providing the right url for href attribute in the <a> tag of your index.html template.
{{forloop.counter}}.{{ item.info_text }}
This line will point to the image itself. So you can use it example in the <image src="{{ item.info_image.url }}" /> but not in a link tag. So I guess this is what you were looking for.
To point to your detail view of specific image you would want to ideally create get_absolute_url method on your Info model class.
Model.get_absolute_url()
Define a get_absolute_url() method to tell Django how to calculate the canonical URL for an object. To callers, this method should appear to return a string that can be used to refer to the object over HTTP.
For example:
# models.py
class Info(models.Model):
...
info_image = models.ImageField(upload_to='images/%Y%m/%d')
def get_absolute_url(self):
return reverse('detail',
args=[self.id])
Then you could use that in your template like this:
{{forloop.counter}}.{{ item.info_text }}
and display your image, wherever you want, using:
<image src="{{ item.info_image.url }}" />
Have you checked how the URL looks in the generated HTML code? E.g. does the URL look correct when the HTML is loaded, and when you click it, it starts repeating it?
I'm new to Django and have been stuck on this for a few days now. Hoping to find some help here. I've searched stackoverflow and read through the django docs but haven't been able to grasp this. I'm using Django 1.6.2 and Python 2.7.
I'm setting up a simple news app in which article has a ManyToMany relationship with category. I'm running into trouble trying to display articles from a specific category. I have the index working displaying all articles and also the single page view is working e.g. clicking on article title from index brings you to the article itself. Once in the article I am displaying the article category. Up to here all is well. When I try to link the category and display an index for all posts in that category I get a NoReverseMatch for the url 'category-archive'.
Should I do this in a view like I'm trying or would the Manager work better? Open to all suggestions and answers. Like I said I'm new so would like to know best practice. Here is my code and thank you in advance for dealing with a noobie.
models.py
from django.db import models
from tinymce import models as tinymce_models
class ArticleManager(models.Manager):
def all(self):
return super(ArticleManager, self).filter(active=True)
class Category(models.Model):
title = models.CharField(max_length=65)
slug = models.SlugField()
def __unicode__(self, ):
return self.title
class Article(models.Model):
title = models.CharField(max_length=65)
slug = models.SlugField()
description = models.CharField(max_length=165)
content = tinymce_models.HTMLField()
categories = models.ManyToManyField(Category)
image = models.ImageField(upload_to='article/images')
active = models.BooleanField(default=False)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
objects = ArticleManager()
def __unicode__(self, ):
return self.title
class Meta:
ordering = ['-timestamp',]
views.py
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response, RequestContext, get_object_or_404
from .models import Article, Category
def all_articles(request):
articles = Article.objects.all()
return render_to_response('news/all.html', locals(), context_instance=RequestContext(request))
def single_article(request, slug):
article = get_object_or_404(Article, slug=slug)
return render_to_response('news/single.html', locals(), context_instance=RequestContext(request))
def category_archive(request, slug):
articles = Article.objects.filter(category=category)
categories = Category.objects.all()
category = get_object_or_404(Category, slug=slug)
return render_to_response('news/category.html', locals(), context_instance=RequestContext(request))
single.html - for single article view
{% extends 'base.html' %}
{% block content %}
<h1>{{ article.title }}</h1>
<img src='{{ MEDIA_URL }}{{ article.image }}' class="article-image img-responsive"/>
<p>{{ article.content|safe }}</p>
<p class='small'>
**this next line gets an error for the url 'category-archive'**
{% for category in article.categories.all %}Category: <a href='{% url "category-archive" %}{{ category.slug }}'>{{ category }}</a>{% endfor %}</p>
{% endblock %}
category.html - display all articles in specific category
{% extends 'base.html' %}
{% block content %}
{% for article in articles %}
<h1><a href='{% url "articles" %}{{ article.slug }}'>{{ article }}</a></h1>
<a href='{% url "articles" %}{{ article.slug }}'><img src='{{ MEDIA_URL }}{{ article.image }}' class="img-responsive"/></a>
{{ article.description }}
{% if forloop.counter|divisibleby:4 %}
<hr/>
<div class='row'>
{% endif %}
{% endfor %}
</div>
{% endblock %}
urls.py - project urls
from django.conf.urls import patterns, include, url
from django.conf import settings
from filebrowser.sites import site
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^tinymce/', include('tinymce.urls')),
(r'^admin/filebrowser/', include(site.urls)),
(r'^grappelli/', include('grappelli.urls')),
(r'^static/(?P<path>.*)$', 'django.views.static.serve',{
'document_root': settings.STATIC_ROOT
}),
(r'^media/(?P<path>.*)$', 'django.views.static.serve',{
'document_root': settings.MEDIA_ROOT
}),
url(r'^admin/', include(admin.site.urls)),
url(r'^$', 'dl.views.home', name='home'),
(r'^news/', include('news.urls')),
(r'^guides/', include('guides.urls')),
)
urls.py - news urls
from django.conf import settings
from django.conf.urls import patterns, include, url
urlpatterns = patterns('news.views',
url(r'^$', 'all_articles', name='articles'),
url(r'^(?P<slug>[-\w]+)/$', 'single_article'),
**This next one is giving me the problem I suspect - should be url to category with articles**
url(r'^chive/(?P<slug>[-\w]+)/?', 'category_archive', name='category-archive'),
)
I would have post it as a comment but i don't have the reputation.
I think that the thing is that the URL Dispatcher expects the category-archive to also get the slug. so you should change the URL in the template to:
{% url "category-archive" category.slug %}
hope this helps!