I am new to Django and trying to make a basic website and having a few difficulties getting the relevant record for a page.
Models.py
import datetime
from django.db import models
from django.conf import settings
from ckeditor.fields import RichTextField
from markdown import markdown
class LiveEntryManager(models.Manager):
def get_query_set(self):
return super(LiveEntryManager,self).get_query_set().filter(status=self.model.LIVE_STATUS)
class Page(models.Model):
LIVE_STATUS = 1
HIDDEN_STATUS = 2
STATUS_CHOICES = (
(LIVE_STATUS, 'Live'),
(HIDDEN_STATUS, 'Hidden'),
)
title = models.CharField(max_length=250, help_text='Max 250 characters.')
slug = models.SlugField(unique=True, help_text='Suggested automatically generated from the title. Must be unique')
description = RichTextField()
description_html = models.TextField(editable=False, blank=True)
status = models.IntegerField(choices=STATUS_CHOICES, default=LIVE_STATUS,
help_text="Only pages with live status will be publicly displayed")
def save(self, force_insert=False, force_update=False):
self.description_html = markdown(self.description)
super(Page, self).save(force_insert, force_update)
def get_record(self):
return self.objects.get()
#Managers
live = LiveEntryManager()
objects = models.Manager()
class Meta:
ordering = ['title']
verbose_name_plural = "Pages"
def __unicode__(self):
return self.title
def get_absolute_url(self):
return "/%s/" % self.slug
class Image(models.Model):
page = models.ForeignKey(Page)
name = models.CharField(max_length=250)
image = models.ImageField(upload_to='gallery')
class Meta:
ordering = ['name']
def __unicode__(self):
return self.name
And Views.py
from django.shortcuts import get_object_or_404, render_to_response
from django.views.generic.list_detail import object_list
from mainsite.models import Page, Image
def home(request):
return render_to_response('templates/home.html')
def page(request, slug):
one_page = get_object_or_404(Page, slug=slug)
return render_to_response('templates/page/page.html',
{ 'object_list': one_page.get_record() })
and Urls.py
urlpatterns = patterns('',
# Examples:
url(r'^$', 'mainsite.views.home', name='home'),
# url(r'^disability/', include('disability.foo.urls')),
url(r'^page/(?P<slug>[-\w]+)/$', 'mainsite.views.page'),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^grappelli/', include('grappelli.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
What I want to do is to be able to go to say /page/test and get the title, description and image for that object only. I know how to get all objects and display them in a template but cannot figure out how to get a single record and would be grateful of some help.
Thanks
If you would want to query the database for a single Page model you could use
views.py
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponse
from models import Pages
def page(request, slug):
try:
page = Pages.objects.get(slug=slug)
except ObjectDoesNotExist:
return HttpResponse(status=404)
return render(request, 'templates/page/page.html', {'page': page})
Then just use
{{page.title}}
or something like that in your template.
Also, if you want to query and have an iterable list returned intead you coule use
Pages.objects.filter()
instead of
Pages.objects.get()
Where'd you get get_record() from? The return value of get_object_or_404 is a model instance. There's nothing else to "get", just pass the instance to your context. And, don't use object_list as a context name. Not only is this an instance, not a list or queryset, but that name is most often used with pagination, and you'll simply create confusion in your code if you're not actually paginating anything.
return render_to_response('templates/page/page.html', {
'one_page': one_page,
})
Then in your template:
<h1>{{ one_page.title }}</h1>
<img src="{{ one_page.image.url }}" alt="">
<p>{{ one_page.description }}</p>
Related
I have problem with django request.I dont know. I tried to do everything, but I got
'blog' object has no attribute 'get'. I want to do mini blog on my website,but it isnt working now. I would like to get all objects from database.(Sorry,If I did something wrong,I am beginner in django and tried to functions for my website) :)
models.py
from django.db import models
# Create your models here.
CHOOSE =[
('Usual','Обычный тариф'),
('Premium','Премиум тариф'),
('Prise','Аукционный')
]
class VDSTARIFS( models.Model):
id = models.CharField(max_length=40, primary_key= True,serialize=True)
name = models.CharField(max_length=20, verbose_name = 'Цены')
choosen = models.CharField(max_length= 20, choices = CHOOSE, verbose_name = 'Тариф', help_text='Выбор тарифного плана.')
title = models.CharField(max_length= 15)
def __str__(self):
return str(self.title)
class blog(models.Model):
id = models.CharField(max_length=40, primary_key= True,serialize=True)
message = models.TextField( verbose_name= 'Сообщение блога')
titleblog = models.CharField(max_length=50, verbose_name = 'Название')
img = models.ImageField(upload_to = 'admin/', verbose_name= 'Картинка' )
def __str__(self):
return str(self.titleblog)
def get_all_objects(self): ##maybe I have troubles with it.
queryset = self.__class__.objects.all()
blog.html
{% csrftoken %}
{% for item in message %}
{% endfor %}
views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import render
from django.http import HttpResponseRedirect
import os
from polls.models import VDSTARIFS
from polls.models import blog
from django.template.loader import render_to_string
def index_view(request):
#return HttpResponse("<h1>Hello</h1>")
return render(request, "home.html", {})
def about(request):
return render(request, "about.html", {})
def minecraft(request):
return render(request, "minecraft.html",{})
def vds(request):
HTML_STRING = render_to_string("vds.html", context = context1)
return HttpResponse(HTML_STRING)
try:
VDS1 = VDSTARIFS.objects.get(id=0)
name = VDS1.name
except VDSTARIFS.DoesNotExist:
VDS1 = None
context1 = {
'name':name,
'prise':VDS1,
}
def messagesblog(request,self):
HTML_STRING = render_to_string('blog.html')
return HttpResponse(HTML_STRING)
urls.py
from django.contrib import admin
from django.urls import path
from polls import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index_view, name='home'),
path('vds', views.vds, name='vds' ),
path('minecraft', views.minecraft, name='minecraft' ),
path('about', views.about, name='about'),
path('blog', views.blog, name='blog')
]
The actual error is probably caused by the wrong url pattern:
path('blog', views.blog, name='blog')
views.blog refers to the blog model due to:
from polls.models import blog
What you need here is the view not the model, so:
path('blog', views.messagesblog, name='blog')
Then, remove the "self" argument from your messagesblog function.
Use the "render" function from django.shortcuts and provide a context with the blog objects:
def messagesblog(request):
return render(request, "blog.html", {message: blog.objects.all()})
That might solve your problem.
Still, there are some things you could improve.
E.g.: Don't use "id" fields in your model definitions if you don't really, really have to, as this is usually an auto-generated number (BigInt) field.
That's only one tip from an old Django veteran happy to be finally heard. You'll find out much more yourself as you proceed.
this is the error I got when I wanted to create a dynamic sitemap.
sitemap.py
from django.contrib import sitemaps
from django.shortcuts import reverse
from django.utils import timezone
from django.contrib.sitemaps import Sitemap
#models
from home.models import Page
class StaticViewSitemap(sitemaps.Sitemap):
priority = 0.5
changefreq = "daily"
protocol = 'https'
def items(self):
return [
'home:about',
]
def location(self, item):
return reverse(item)
def lastmod(self, item):
return timezone.now()
class DynamicSitemap(Sitemap):
changefreq = "daily"
priority = 0.5
def items(self):
return Page.objects.all()
models.py
class Page(models.Model):
city = models.CharField(max_length=40, verbose_name="Şehir")
seo = models.CharField(max_length=50, verbose_name="Seo")
def __str__(self):
return self.city
def get_absolute_url(self):
return reverse('home:page', kwargs={'pk': self.pk})
home/urls.py:
app_name = "home"
urlpatterns = [
# ⋮,
path(r'page/<int:pk>', views.yardimsayfalari, name="page"),
# ⋮,
]
static sitemap works fine but dynamic sitemap I get the same error. Thank you to those who are interested so far.
I'm sorry for my bad english
Based on the get_absolute_url, you try to link this to:
path(r'page', views.yardimsayfalari, name='page'),
The name of your view is page, not Page. Furthermore you specified app_name = 'home', hence full name of the view is home:page. Finally your path does not contain any parameter, so args=(self.pk,) makes not much sense.
You thus likely should include a primary key parameter:
app_name = "home"
urlpatterns = [
# ⋮,
path('page/<int:pk>/', views.yardimsayfalari, name="page"),
# ⋮,
]
include that pk parameter in your view:
def yardimsayfalari(request, pk):
# …
# return HTTP response
and finally refer to the view with:
class Page(models.Model):
# ⋮
def get_absolute_url(self):
return reverse('home:page', args=(self.pk,))
It might also make more sense to work with a named parameter, so:
class Page(models.Model):
# ⋮
def get_absolute_url(self):
return reverse('home:page', kwargs={'pk': self.pk})
based on this, I would advise to (re)read the third part of the Django tutorial.
I'm building an e-commerce (like) project. While running the program, from Homepage, if we select a product I got hit by this error, instead of showing that product details. Now I can't figure out how to fix this please help me to fix it.enter image description here
Here's my Models.py
class Category(models.Model):
name=models.CharField(max_length=250,unique=True)
slug=models.SlugField(max_length=250,unique=True)
desc=models.TextField(blank=True)
image=models.ImageField(upload_to='category',blank=True)
class Meta:
ordering=('name',)
verbose_name='category'
verbose_name_plural='categories'
# for menu linking (url)
def get_url(self):
return reverse("ecommerce_app:products_by_category",args=[self.slug])
def __str__(self):
return '{}'.format(self.name)
class Product(models.Model):
name=models.CharField(max_length=250,unique=True)
slug = models.SlugField(max_length=250, unique=True)
desc = models.TextField(blank=True)
image = models.ImageField(upload_to='product', blank=True)
category=models.ForeignKey(Category,on_delete=models.CASCADE)
price=models.DecimalField(max_digits=10,decimal_places=2)
stock=models.IntegerField()
available=models.BooleanField(default=True)
created=models.DateTimeField(auto_now=True)
updated=models.DateTimeField(auto_now=True)
class Meta:
ordering = ('name',)
verbose_name = 'product'
verbose_name_plural = 'products'
# for url
def get_url(self):
return reverse("ecommerce_app:ProdCatDetails",args=[self.category.slug,self.slug])
def __str__(self):
return '{}'.format(self.name)
Her's my Urls.py
from django.urls import path
from . import views
app_name='ecommerce_app'
urlpatterns=[
path('',views.allProdCat,name='allProdCat'),
# for special urls for Category
path('<slug:c_slug>/',views.allProdCat,name='products_by_category'),
# for special urls for Product Details
path('<slug:c_slug>/<slug:product_slug>/',views.ProdCatDetails,name='ProdCatDetails'),
]
Here's my Views.py
from django.http import HttpResponse
from .models import Category,Product
from django.shortcuts import render,get_object_or_404
# Create your views here.
def home(request):
return HttpResponse("Hello")
def allProdCat(request,c_slug=None):
c_page=None
products=None
if c_slug!=None:
c_page=get_object_or_404(Category,slug=c_slug)
products=Product.objects.all().filter(category=c_page,available=True)
else:
products=Product.objects.all().filter(available=True)
return render(request,'category.html',{'category':c_page,'products':products})
# For product details
def ProdCatDetails(request,c_slug,product_slug):
try:
product=Product.objects.get(category__product=c_slug,slug=product_slug)
except Exception as e:
raise e
return render(request,'product.htmal',{'product':product})
If you filter with:
product = Product.objects.get(category=c_slug, slug=product_slug)
You will filter on the field the product ForeignKey is referring to. Since that is not specified, this is the primary key, and thus an AutoField.
You can filter with:
# filter on the slug ↓
product = Product.objects.get(category__slug=c_slug, slug=product_slug)
I am a complete beginner so I apologies for my noobiness explanation. I am in the process of categorising my blogs.
I created a model -> migrated it -> imported in view.py -> Imported the view that I created into urls.py -> and created URL for my new page but when I add the href to other pages (home) it takes me to the error.
My codes:
models.py
class Category(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Post(models.Model):
title = models.CharField(max_length=100)
content=models.TextField()
date_posted=models.DateTimeField(default=timezone.now)
author=models.ForeignKey(User, on_delete=models.CASCADE)
category = models.CharField(max_length=100, default='Engineering')
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk})
Views.py:
from .models import Post, Category
class CategoryListView(ListView):
model = Post
template_name= 'blog/category_posts.html'
context_object_name = 'posts'
ordering = ['-date_posted']
paginate_by = 3
urls.py:
from django.urls import path
from .views import (
PostListView,
PostDetailView,
PostCreateView,
PostUpdateView,
PostDeleteView,
UserPostListView,
CategoryListView)
path('category/<str:category>/', CategoryListView.as_view(), name='category-posts'),
home.html
{{ post.category }}
In addition to what Arun said.
I think you need to set url_patters in your urls.py. Something like this:
from django.urls import path
from .views import (
PostListView,
PostDetailView,
PostCreateView,
PostUpdateView,
PostDeleteView,
UserPostListView,
CategoryListView)
urlpatterns = [
path('category/<str:category>/', CategoryListView.as_view(), name='category-posts'),
]
You should also pass the category in your url, like this
{{ post.category }}
Because your url needs a str parameter category.
I'm just about finished building the Poll app and everything seems to be working except for the results page. "Vote Again" isn't showing up, or any other data after I input a selection. It looks like the page is just reloading. The new votes are getting counted, and I'm not getting an error message. I can see that I'm on the /results/ page.
Does anyone have any ideas where I should be looking for the problem?
Thanks!
Views:
# Create your views here.
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views import generic
from polls.models import Choice, Poll
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_poll_list'
def get_queryset(self):
"""Return the last five published polls."""
return Poll.objects.order_by('-pub_date')[:5]
class DetailView(generic.DetailView):
model = Poll
template_name = 'polls/detail.html'
class ResultsView(generic.DetailView):
model = Poll
template_name = 'polls/results.hmtl'
def vote(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
try:
selected_choice = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the poll voting form.
return render(request, 'polls/detail.html', {
'poll': p,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
#Always return an HttpRespsonseRedirect after successfully dealing
#with Post data. This prevents data from being posted twice if a
#user hits the Back button
return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))
URLs -
from django.conf.urls import patterns, url
from polls import views
urlpatterns = patterns('',
#ex: /polls/
url(r'^$', views.IndexView.as_view(), name='index'),
#ex: /polls/5/
url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'),
# ex: /polls/5/results/
url(r'^(?P<pk>\d+)/results/$', views.ResultsView.as_view(), name='results'),
#ex: /polls/5/vote/
url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),
)
Models
from django.db import models
import datetime
from django.utils import timezone
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.question
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
was_published_recently.admin_order_field = 'pub_date'
was_published_recently.boolean = True
was_published_recently.short_description = 'Published recently?'
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __unicode__(self):
return self.choice_text
Hoping I didn't mess up any formatting when I pasted in here.
It seems like the error is because you misspell the template page for results.
class ResultsView(generic.DetailView):
model = Poll
template_name = 'polls/results.hmtl'
correct the spelling for results.html