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.
Related
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 want get my album.object.all() coding running in my web site. i have included data but after putting it in urls.py file it doesnt find the path to response. please help me.
this is django 1.11.2
my urls.py file
from django.conf.urls import url
from django.contrib import admin
from myapp import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', views.home, name='home'),
url(r'^album/?$', views.music, name='music'),
url(r'^album/(?P<album_id>\d+)/$', views.detail, name='detail'),
url(r'^Database/?$', views.Database, name='Database'),
]
my views.py file
from django.shortcuts import render
from django.http import HttpResponse
from myapp.models import Album
# Create your views here.
def home(request):
return render(request, 'index.html')
def music(request):
all_albums = Album.objects.all()
context ={'all_albums': all_albums,}
return render(request, 'album.html', context)
def detail(request, album_id):
return HttpResponse("<h2>Details for album id: " + str(album_id) + "</h2>")
def Database(request):
return render(request, 'data.html')
my model.py page
from django.db import models
class Album(models.Model):
artist = models.CharField(max_length=250)
album_title = models.CharField(max_length=500)
genre = models.CharField(max_length=100)
album_logo = models.CharField(max_length=1000)
def __str__(self):
return self.album_title+ ' - ' +self.artist
class Song(models.Model):
Album = models.ForeignKey(Album, on_delete=models.CASCADE)
#any songs of the related to the deleted album will be deleted
file_type = models.CharField(max_length=10)
song_title = models.CharField(max_length=200)
want to use it get the whole directory by <pk>=album_id
My goal is to Create hyperlinks which would toss a keyword into a views function which would then pull a query from my db onto the page.
GOAL: Press hyperlink which would give me query of a specific major.
I was attemping to use the converter,
So the goal was, 1 being the first step, 3 being final step.
Is this possible?
1) Click the hyperlink -> Major = Accounting
2)URL.py
path(<str:Accounting/, views.Major, name=Major)
3)Views.py
def Major(request, Accounting):
major_choice = professor.objects.filter(Major = Accounting)
return render(request, 'locate/major.html', {'major_choice': major_choice})
NOTE: I replaced variables with what I want it to contain "Accounting", you will notice inside the bottom views.py its called "Major".
Index.html
Accounting
major.html
<ul>
{% for major in major_choice %}
<li>{{major.ProfessorName}}</li>
{%endfor%}
</ul>
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('<str:Major/', views.Major, name='Major')
]
models.py
from django.db import models
class professor(models.Model):
ProfessorIDS = models.IntegerField()
ProfessorName = models.CharField(max_length=100)
ProfessorRating = models.DecimalField(decimal_places=2,max_digits=4)
NumberofRatings = models.CharField(max_length=50)
Major = models.CharField(max_length=50)
def __str__(self):
return self.ProfessorName
views.py
from django.http import HttpResponse
from django.shortcuts import render
from .models import professor
def index(request):
professors = professor.objects.all()
return render(request, 'locate/index.html', {'professors': professors})
def Major(request, major):
major_choice = professor.objects.filter(Major = major)
return render(request, 'locate/major.html', {'major_choice': major_choice})
Please update your url path to this:
path('<str:Major>/', views.Major, name='Major')
And in your html:
Accounting
in views:
def Major(request, Major):
....
I was writing a model online shop django app, wanted to incorporate slug in it. Having trouble in opening a page.
This is my model:
from __future__ import unicode_literals
from django.db import models
from django.db.models.signals import pre_save
from django.utils .text import slugify
class Customer(models.Model):
customer_name = models.CharField(max_length=200)
slug = models.SlugField(unique = True)
def __str__(self):
return self.customer_name
def get_absolute_url(self):
return reverse("OnlineShop:order", kwargs={"slug": self.slug})
def pre_save_customer_receiver(sender, instance, *args, **kwargs):
slug = slugify(instance.customer_name)
exists = Customer.objects.filter(slug = slug).exists()
if exists:
slug = "%s-%s" % (slug,instance.id)
instance.slug=slug
pre_save.connect(pre_save_customer_receiver, sender = Customer)
This is my view:
def customer(request):
customer_list = Customer.objects.all()
template_path = 'OnlineShop/customer.html'
context={
'customer_list':customer_list,
}
return render(request,template_path,context)
def order(request,slug):
Customer = Customer.objects.filter(slug=slug)
''' some code from here '''
And my template customer.html:
<h1>List of Customers:</h1>
<ul>
{% for customer in customer_list %}
<li><a href='{% url 'order' customer.slug %}'>{{ customer.customer_name }}<br></li>
{% endfor %}
</ul>
This is my urls.py
from django.conf.urls import url
from . import views
urlpatterns=[
url(r'^$',views.customer, name='customer'),
url(r'^customer/(?P<slug>[\w-]+)$',views.order, name='order'),
]
Is the problem in the template? What is wrong?
I hope you've defined your urls.py like below,
from django.conf.urls import url, include
from . import views
onlineshop_patterns = [
url(r'^$', views.customer, name='customer'),
url(r'^customer/(?P<slug>[\w-]+)$', views.order, name='order'),
]
urlpatterns = [
# ...
url(r'^OnlineShop/', include(onlineshop_patterns)),
# ...
]
Read Reverse resolution of URLs and Regex for SlugField.
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>