I have been facing this issue. And I have a url name post-page-detail but then also getting error please
See the error screenshot below.
My html page
<a href="{% url "post-detail-page" slug=post.slug %}">
<h2>{{post.tractor_company}} || {{post.tractor_model}}</h2>
<pre><h5>{{post.implimentaion}}</h5>
{{post.farmer}}
Uplode Date : {{post.date}}</pre>
</a>
</div>
URLs.py
from . import views
urlpatterns = [
path("",views.starting_page,name = "starting-page"),
path("posts",views.posts,name = "post-page"),
path("posts/<slug:slug>",views.post_detail,name="post-detail-page"),
]
View.py
from django import forms
from django.contrib.auth.models import User
from django.shortcuts import render, redirect ,get_object_or_404
from .models import Post, Farmer
# Create your views here.
from django.http import HttpResponseRedirect
# Create your views here.
def starting_page(request):
return render(request,"tractor/index.html")
def posts(request):
qs = Post.objects.all()
context = {"posts":qs}
return render(request,"tractor/all-post.html",context)
def add_post(request):
pass
def post_detail(request,slug):
indentified_post = get_object_or_404(Post,slug=slug)
return render(request,"blog/post-detail.html",{'post':indentified_post})
i am iterating through posts and using the post-detail.html page
all-post.html.
{% load static %}
{% block title %}
All Tractors
{% endblock %}
{% block content%}
<section id="all_events">
<br>
<h1 style="text-align:center;">All Tractors</h1>
<ul>
{% for post in posts %}
<br>
{% include "tractor/includes/singlePost.html" %}
{% endfor %}
</ul>
</section>
{% endblock %}```
Try this:
{% url 'post-detail-page' post.slug as post_detail_url %}
<a href="{{ post_detail_url }}">
Let me know if it worked.
Related
I have been facing this issue. And I have a url name post-page-detail but then also getting error please
See the error screenshot below.
My singlepost.html html page
<a href="{% url "post-detail-page" slug=post.slug %}">
<h2>{{post.tractor_company}} || {{post.tractor_model}}</h2>
<pre><h5>{{post.implimentaion}}</h5>
{{post.farmer}}
Uplode Date : {{post.date}}</pre>
</a>
</div>
URLs.py
from . import views
urlpatterns = [
path("",views.starting_page,name = "starting-page"),
path("posts",views.posts,name = "post-page"),
path("posts/<slug:slug>",views.post_detail,name="post-detail-page"),
]
View.py
from django import forms
from django.contrib.auth.models import User
from django.shortcuts import render, redirect ,get_object_or_404
from .models import Post, Farmer
# Create your views here.
from django.http import HttpResponseRedirect
# Create your views here.
def starting_page(request):
return render(request,"tractor/index.html")
def posts(request):
qs = Post.objects.all()
context = {"posts":qs}
return render(request,"tractor/all-post.html",context)
def add_post(request):
pass
def post_detail(request,slug):
indentified_post = get_object_or_404(Post,slug=slug)
return render(request,"blog/post-detail.html",{'post':indentified_post})
i am iterating through posts and using the post-detail.html page
all-post.html.
{% load static %}
{% block title %}
All Tractors
{% endblock %}
{% block content%}
<section id="all_events">
<br>
<h1 style="text-align:center;">All Tractors</h1>
<ul>
{% for post in posts %}
<br>
{% include "tractor/includes/singlePost.html" %}
{% endfor %}
</ul>
</section>
{% endblock %}
Root urls.py
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path("",include(("tractor.urls","tractor"))),
]
The 'tractor' part in the path('', include(('tractor.urls', 'tractor'))) in the include(…) function [Django-doc] specifies the app_namespace. This means that for all URLs you use in the tractor.urls urls, you should prefix this with tractor::
<a href="{% url 'tractor:post-detail-page' slug=post.slug %}">
…
</a>
I am using the "keyone" column in the database to filter entries. So far in the code i have written i am successfully able to render template with "keyone = 2" values. what should i write in a new template file, and how should i modify existing views.py so that when the template file renders it contains a list of links , each link for each value of "keyone" , when i click on the link say "keyone = 2", the selected entries should get rendered in home.html
models.py
# app/models.py
from django.db import models
from django.urls import reverse # new
class Post(models.Model):
text = models.TextField()
def __str__(self):
return self.text[:50]
keyone = models.IntegerField(default = '777')
def get_absolute_url(self): # new
return reverse('post_detail', args=[str(self.id)])
views.py
def HomePageView(request):
key2select = Post.objects.filter(keyone=2)
return render(request, 'home.html', {
'key2select': key2select,
})
home.html
<ul>
{% for post in key2select %}
<li>{{ post.keyone }}   {{ post.text }}</li>
{% endfor %}
</ul>
sample database
desired rendering
Firstly, we need to get all keyone values in the DB, to be passed to home.html.
Then in home.html, we need a navbar or somewhere else to put all these links which represent all the keyone values.
So the code would be like:
models.py
# app.models.py would remain the same
views.py
def homePageView(request, key):
key2select = Post.objects.filter(keyone=key)
keyones = Post.objects.distinct('keyone')
return render(request, 'home.html', {
'key2select': key2select,
'keyones': keyones
})
You can check the distinct() in the Django Docs to get distinct values of a column in DB
home.html
<!-- home.html -->
<nav>
<ul>
{% for key in keyones %}
<li>somthing {{key}} something</li>
{% endfor %}
</ul>
</nav>
...
<ul>
{% for post in key2select %}
<li>{{ post.keyone }}   {{ post.text }}</li>
{% endfor %}
</ul>
As we passed the key to the url in the nav link, we need to change the url pattern to catch this.
urls.py
urlpatterns =[
...
path('home/<int:key>/', views.homePageView, name='home')
...
]
May be I'm not understand you problem, if you'r looking for create a list of link code should be
<ul>
{% for post in key2select %}
<a href="{% url "post_detail" post.id %}"><li>{{ post.keyone }}   {{ post.text }}</li><a/>
{% endfor %}
</ul>
This will contain every post link with list item
thanks #sheng-zhuang for providing the solution. Here is the working code with some slight modifications for my benefit.
I created a new template select.html and here is the logic -
Views.py
class IndexView(TemplateView):
template_name = 'index.html'
def SelectView(request):
keyones = Post.objects.values_list('keyone',flat=True).distinct()
return render(request, 'select.html', {
'keyones': keyones
})
def HomePageView(request, key):
key2select = Post.objects.filter(keyone=key)
return render(request, 'home.html', {
'key2select': key2select,
})
index.html
<header>
Select<br />
Post
</header>
select.html
<nav>
<ul>
{% for key in keyones %}
<li>Keyone value = {{key}} </li>
{% endfor %}
</ul>
</nav>
home.html
<header>
Select<br />
Post
</header>
<br /><br /><br /><br />
<ul>
{% for post in key2select %}
<li>{{ post.keyone }}   {{ post.text }}</li>
{% endfor %}
</ul>
urls.py
path('', IndexView.as_view(), name='index'),
path('select/', SelectView, name='select'),
path('home/<int:key>/', HomePageView, name='home')
I'm using this package https://github.com/tomwalker/django_quiz to make a web quiz app. I need to add images to the multiplechoice answers.
So, I added to the Answers model:
image = models.ImageField(upload_to='uploads/%Y/%m/%d',
blank=True,
null=True,
verbose_name=_("Image"))
Images are uploading and saving into the DB.
The part that shows choosable answers are shown in template like this:
{% for answer in form.answers %}
<li class="list-group-item">
{{ answer }}
</li>
{% endfor %}
I changed it to:
{% for answer in form.answers %}
<li class="list-group-item">
{{ answer }}
<img src="{{ answer.image.url }}" alt="" />
</li>
{% endfor %}
But it's doesn't work. It renders <img src(unknown)>
This is forms.py:
class QuestionForm(forms.Form):
def __init__(self, question, *args, **kwargs):
super(QuestionForm, self).__init__(*args, **kwargs)
choice_list = [x for x in question.get_answers_list()]
self.fields["answers"] = forms.ChoiceField(choices=choice_list,
widget=RadioSelect)
And this is model:
def get_answers_list(self):
return [(answer.id, answer.content) for answer in
self.order_answers(Answer.objects.filter(question=self))]
I know this is old but I recently came across this problem, in case anyone out there is still stuck on it, here is how I solved it:
Create a ImageField in the Answer model
image = models.ImageField(upload_to='images/',
blank=True,
null=True,
verbose_name=_("Image"))
Add a model method on MCQuestion
from django.utils.safestring import mark_safe
...
def get_answers_images(self):
return [(answer.id, mark_safe(f"<img src='{answer.image.url}'/>")) for answer in
self.order_answers(Answer.objects.filter(question=self))]
In forms.py
image_choice_list = [x for x in question.get_answers_images()]
self.fields["answers"] = forms.ChoiceField(choices=image_choice_list,
widget=RadioSelect)
PS: You might also want to change your QuizTake in views.py in other to not conflict with other types of questions, in my case I separated the forms for MCQuestion and TFQuestion
# New
elif self.question.__class__ is TF_Question:
form_class = TF_QuestionForm
I hope this saves someone else from wasting hours on something relatively simple. While injecting the img tag directly might not be the "cleanest" approach I think it works well enough and doesn't require you to mess around much with the existing logic structure of the quiz app.
to display image :-
add {% load static %} in template
sample snippet:-
{% block content %}
{% load static %}
Product List
{% if product %}
{% for prd in product %}
<div class="gallery">
<a target="_blank" href="{% static prd.image1 %}">
<img src="{% static prd.image1 %} " alt="{{ prd.name }}" width="400" height="400">
</a>
<div class="desc"> {{ prd.name }}</div>
</div>
{% endfor %}
{% else %}
<p>There are no products entered by you .</p>
{% endif %}
{% endblock %}
in url.py
from django.conf.urls import url
from django.contrib import admin
**from django.conf import settings**
**from django.conf.urls.static import static**
from . import views
from .views import Productlistview,Productdetailview
app_name= 'product'
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^add/$', views.addproduct, name='addproduct'),
url(r'^addsuccess/$', views.addsuccess, name='addsuccess'),
url(r'^productview/$', Productlistview.as_view(), name='viewproduct'),
url(r'^productview/(?P<productid>[0-9a-f-]+)/view/$',Productdetailview.as_view(), name='productdetailview'),
] **+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)**
in settings.py -- project setings
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
'/dev/projects/pro_mysql_practice/product/',
'dev/projects/pro_mysql_practice/index/',
]
Still newbie in django, please help me
Urls.py :
from django.conf.urls import url
from . import views
app_name = 'lostfound'
urlpatterns = [
# /lostfound/
url(r'^$', views.IndexView.as_view(), name='index'),
# /lostfound/lostitems
url(r'lostitems/', views.LostItemsView.as_view(), name='lost_items'),
this is the main problem of my url, i can't display my register_lost.html
# /lostfound/lostitems/addlostitems
url(r'/addlostitems/$', views.RegisterLostView.as_view(), name='register_lost'),`
Views.py :
from django.views import generic
from .models import Wallet
class IndexView(generic.ListView):
model = Wallet
template_name = 'lostfound/index.html'
class LostItemsView(generic.ListView):
model = Wallet
template_name = 'lostfound/lost_items.html'
class RegisterLostView(generic.ListView):
model = Wallet
template_name = 'lostfound/register_lost.html'
lost_items.html :
<div class="menu-button z-depth-3 right">
<a class="waves-effect waves-light btn" href="{% url 'lostfound:register_lost' %}">
<i class="medium material-icons right">playlist_add</i>Tambah Data
</a>
</div>
this is my register_lost.html that i want process
register_lost.html :
{% extends 'lostfound/base.html' %}
{% extends 'lostfound/lost_items.html' %}
{% block title %}Register Lost Items{% endblock %}
{% block content %}
{% load staticfiles %}
{% block sign_in %}
{% endblock %}
<h1>Hello</h1>
{% endblock %}
Try to switch lines in the urlpatterns list
this:
url(r'/addlostitems/$', views.RegisterLostView.as_view(), name='register_lost'),
before this:
url(r'lostitems/', views.LostItemsView.as_view(), name='lost_items'),
Hi everybody!
Im just starting a way of django programming so sometimes really get confused.
I`m trying to display all my objects from DB, but when opening the page its simply empty.
There are content added and I tried ListView previously and it worked for me. But now I need to dislpay objects like a grid and here is an issue with this method.
Will be very thanksfull for any help!
models.py
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=140)
body = models.TextField()
date = models.DateField()
image = models.ImageField(upload_to='bons_images/%Y/%m/%d')
def __str__(self):
return self.title
views.py
from django.shortcuts import render, render_to_response
from django.template import RequestContext
from django.views import generic
from blog.models import Post
def image(request):
post = Post()
variables = RequestContext(request, {
'post': post
})
return render_to_response('blog/post.html', variables)
# class IndexView(generic.ListView):
# template_name = 'blog/blog.html'
# context_object_name = 'all_posts'
#
# def get_queryset(self):
# return Post.objects.all()
def index(request):
posts = Post.objects.all()
return render(request, 'blog/blog.html', {'posts': posts})
urls.py
from django.conf.urls import url, include
from django.views.generic import ListView, DetailView
from blog.models import Post
from blog import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^(?P<pk>\d+)$', DetailView.as_view(model=Post, template_name='blog/post.html')),
]
blog.html
{% extends 'base.html' %}
{% block content %}
{% if all_posts %}
{% for post in all_posts %}
<div class="container-fluid">
<div class="row">
<div class="col-sm-3 col-lg-4">
<div class="thumbnail">
<a href="/blog/{{ post.id }}">
<h5>{{ post.date|date:'Y-m-d' }} {{ post.title }}</h5>
<img src="{{ post.image.url }}" style="width: 50%; height: 50%"/>
</a>
</div>
</div>
</div>
</div>
{% endfor %}
{% endif %}
{% endblock %}
And by the way, how its possible to display your objects like in grid, not list, using Bootstrap or so on.
Thank you!
You're iterating over something called all_posts in your template. But your view doesn't send anything called all_posts; it only sends posts. You need to use consistent names.