Views in Django 1.8 - python-2.7

I am having trouble linking views to a basic HttpResponse in an ecommerce template I am building.
The error I am getting is 404 but after looking through here and what the docs say I am a little confused as to what I have missed,
The Model
from django.db import models
class Category(models.Model):
parent = models.ForeignKey('self', null=True, blank=True)
name = models.CharField(max_length=255)
slug = models.SlugField(max_length=150)
description = models.TextField()
pub_date = models.DateTimeField(auto_now_add=True)
mod_date = models.DateTimeField(auto_now=True)
class Manufacturer(models.Model):
name = models.CharField(max_length=150)
slug = models.SlugField(max_length=150)
class Product(models.Model):
category = models.ForeignKey(Category)
manufacturer = models.ForeignKey(Manufacturer)
name = models.CharField(max_length=300)
slug = models.SlugField(max_length=150)
description = models.TextField()
photo = models.ImageField(upload_to='itemphotos')
price_in_sterling = models.DecimalField(max_digits =6, decimal_places=2)
available = models.BooleanField()
instock = models.IntegerField()
pub_date = models.DateTimeField(auto_now_add=True)
mod_date = models.DateTimeField(auto_now=True)
My views.py
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return HttpResponse("Hi, your view worked")
def catagory(request):
return HttpResponse("Hi, you are looking at the catagory landing page")
def manufacturer(request):
return HttpResponse("Hi, here you can shop by brand")
def product(request):
return HttpResponse("Hi, here you can search by product")
My urls.py
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^productcatalog/', include('productcatalog.urls')),
url(r'^admin/', include(admin.site.urls)),
]
My urls.py from the app produtcatalog
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^productcatalog/$', views.catagory, name='catagory'),
url(r'^productcatalog/$', views.manufacturer, name='brand'),
url(r'^productcatalog/$', views.product, name='products'),
]
I am sure the error is in the second urls.py file but can't seem to catch it.

well I have another method for this
urls.py
from views import product
urlpatterns=[url(r'^product/$', product)]
views.py
def product(request):
view="""<html><head></head><body><p>something</p></body></html> """
return HttpResponse(view)
I don't remember if I used the render method but is really useful specially when you put variables inside a html page

You are using the same url for all the views functions. Try changing it.
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^productcatalog-1/$', views.catagory, name='catagory'),
url(r'^productcatalog-2/$', views.manufacturer, name='brand'),
url(r'^productcatalog-3/$', views.product, name='products'),
]

Related

Django blog post views count adds two instead of one

I built this blog with django and everything is working except the blog post view count. On the page it adds 1 as instructed but adds 2 in django admin. Please let me know what I am doing wrongly
Models.py
from django.db import models
from django.utils import timezone
from django.contrib.auth import get_user_model
User = get_user_model()
from ckeditor_uploader.fields import RichTextUploadingField
class Subscribe(models.Model):
email = models.EmailField()
class Comments(models.Model):
name = models.CharField('Name', max_length=120)
post_id = models.IntegerField(null=True)
email = models.EmailField()
website = models.URLField(max_length=200)
comment = models.TextField(blank=True)
date_created = models.DateTimeField(blank=True,null=True)
def publish(self):
self.date_created=timezone.localtime(timezone.now())
self.save()
class Category(models.Model):
name = models.CharField('Name', max_length=120)
slug = models.SlugField(default="", null=False)
def __str__(self):
return self.name
class Author(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
about = RichTextUploadingField()
image = models.ImageField(upload_to='images/', null=True)
slug = models.SlugField(default="", null=False)
views = models.IntegerField(default=0)
def __str__(self):
return self.user.username
def image_url(self):
if self.image and hasattr(self.image, 'url'):
return self.image.url
STATUS_CHOICES = (
('draft', 'Draft'),
('published', 'Published'),
)
class Post(models.Model):
title = models.CharField('Post Title', max_length=120)
date = models.DateTimeField()
status = models.CharField(max_length = 10, choices = STATUS_CHOICES, default ='draft')
category = models.ForeignKey(Category,on_delete = models.SET_NULL, blank = True, null = True,)
author = models.ForeignKey(User,on_delete = models.SET_NULL, blank = True, null = True,)
details = RichTextUploadingField()
slug = models.SlugField(default="", null=False)
image = models.ImageField(upload_to='images/', null=True)
post_views = models.IntegerField(default=0)
class Meta:
ordering = ['-date']
def __str__(self):
return self.title
def image_url(self):
if self.image and hasattr(self.image, 'url'):
return self.image.url
Views.py
from django.shortcuts import render
from .models import Post
from .models import Comments
from .models import Category
from .models import Author
from .models import Subscribe
from django.http import JsonResponse
from django.utils import timezone
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.db.models import Count
# DEFINING CONTEXTS DETAILS
posts = Post.objects.filter(status="published")
recentPosts = Post.objects.filter(status="published").order_by("-id")[:3]
sidebarPosts = Post.objects.filter(status="published").order_by("-id")[:5]
morePosts = Post.objects.filter(status="published").order_by("-id")[:2]
popularPosts = Post.objects.order_by("-post_views")[:3]
categoryList = Category.objects.annotate(nblog=Count('post')).values()
# VIEW FOR POST DETAILS PAGE
def details(request, slug):
thisPost = Post.objects.filter(slug=slug).first()
thisPost.post_views+=1
thisPost.save()
id = thisPost.id
author = thisPost.author
category = thisPost.category
postCategory = Category.objects.filter(name = category).first()
authorDetail = Author.objects.filter(user = author).first()
allComments = Comments.objects.filter(post_id = id).order_by("-date_created").values()
commentCount = len(Comments.objects.filter(post_id = id))
context = {
'details' : thisPost,
'postCategory' : postCategory,
'allComments' : allComments,
'count' : commentCount,
'authorDetail' : authorDetail,
'sidebarPosts' : sidebarPosts,
'morePosts' : morePosts,
'recentPosts' : recentPosts,
'popularPosts' : popularPosts,
'categoryList' : categoryList
}
return render(request,'markedia/details.html', context)
Urls
from django.urls import path
from markedia_blog import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', views.index, name="index"),
path('index', views.index, name="index"),
path('contact', views.contact, name="contact"),
path('details/<slug:slug>', views.details, name="details"),
path('comment', views.comment, name="comment"),
path('subscribe', views.subscribe, name="subscribe"),
path('blog', views.blog, name="blog"),
path('author/<slug:slug>', views.author, name="author"),
path('category/<slug:slug>', views.category, name="category"),
path('search', views.search, name="search"),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
ADMIN PAGE
Default = 0
Admin page
TEMPLATE PAGE
Post views is equal to 1 on template page
Post views is equal to 1 on template page
ADMIN PAGE AFTER VIEWING TEMPLATES PAGE
Post views is equal to 2 instead of 1
Post views is equal to 2 instead of 1
Could you tell me what i'm doing wrong??
Template page post views shows 1 but admin page shows 2

django-autocomplete-light generic foreign key invalid view function

I am trying to use django autocomplete light to set up Autocompletion for GenericForeignKey
However I am getting this error when I try to view the form:
I have a simple a setup. But because the urls are in an app's namespace, it can't find them.
models.py
class Prereq(IsAPrereqMixin, models.Model):
name = models.CharField(max_length=256, null=True, blank=True)
prereq_content_type = models.ForeignKey(ContentType, related_name='prereq_item',
verbose_name="Type of Prerequisite",
on_delete=models.CASCADE)
prereq_object_id = models.PositiveIntegerField(verbose_name="Prerequisite")
prereq_object = GenericForeignKey("prereq_content_type", "prereq_object_id")
# lots more fields ignored for now
forms.py
from dal import autocomplete
from prerequisites.models import Prereq
class PrereqForm(autocomplete.FutureModelForm):
prereq_object = autocomplete.Select2GenericForeignKeyModelField(
model_choice=[(Prereq, "Prereq"), ]
)
class Meta:
model = Prereq
fields = ['name']
urls.py
from django.urls import path
from prerequisites import views
from prerequisites.forms import PrereqForm
app_name = 'prerequisites'
urlpatterns = [
path('edit/<int:pk>/', views.PrereqUpdateView.as_view(), name='prereq_edit'),
]
# https://django-autocomplete-light.readthedocs.io/en/master/gfk.html#register-the-view-for-the-form
urlpatterns.extend(PrereqForm.as_urls())

Django Rest Framework viewset not returning correct data from queryset

I am pretty new to Django Rest Framework and am trying to build an API that has various viewsets, and almost all are working properly except one.
In my viewset I have 3 ModelViewSet's: one to list all Inspections, one to show all completed (done) inspections and the last one to show all the undone inspections. The problem is that it is returning the list of all inspections correctly, but the other 2 return "detail: not found" even though I have instances of Inspections in my database.
Here is my Inspection Viewset:
from rest_framework.viewsets import ModelViewSet
from inspections.models import Inspection
from .serializers import InspectionSerializer
from rest_framework import generics
class InspectionViewSet(ModelViewSet):
queryset = Inspection.objects.all()
serializer_class = InspectionSerializer
class DoneInspectionsViewSet(ModelViewSet):
serializer_class = InspectionSerializer
def get_queryset(self):
queryset = Inspection.objects.all()
return queryset
class UndoneInspectionsViewSet(ModelViewSet):
serializer_class = InspectionSerializer
def get_queryset(self):
queryset = Inspection.objects.filter(done=False)
return queryset
Here's my Inspection Serializer:
from rest_framework.serializers import ModelSerializer
from inspections.models import Inspection
from properties.api.serializers import PropertySerializer
class InspectionSerializer(ModelSerializer):
property = PropertySerializer(many=False)
class Meta:
model = Inspection
fields = ('id', 'connected_check', 'category', 'property', 'date',
'done_date', 'done_by', 'staff', 'notes', 'done')
Here's the Inspection model:
from django.db import models
from check.models import Check
from properties.models import Property
from django.contrib.auth.models import User
from django.urls import reverse
from django.utils import timezone
class Inspection(models.Model):
connected_check = models.ForeignKey(Check, on_delete=models.DO_NOTHING, null=True, blank=True, related_name='inspection_check')
category = models.ForeignKey(InspectionCategory, on_delete=models.DO_NOTHING)
property = models.ForeignKey(Property, on_delete=models.DO_NOTHING, related_name='inspection_property')
date = models.DateField()
done_date = models.DateField(blank=True, null=True)
done_by = models.ForeignKey(User, max_length=25, blank=True, null=True, related_name='inspection_done_by', on_delete=models.DO_NOTHING)
staff = models.ForeignKey(User, max_length=25, null=True, blank=True, related_name='inspection_staff', on_delete=models.DO_NOTHING)
notes = models.TextField(max_length=500, blank=True)
done = models.BooleanField(default=False)
def __str__(self):
return self.category.name
def get_absolute_url(self):
return reverse("inspections:details",kwargs={'pk':self.pk})
def get_category_name(self):
return self.category
def is_past_due(self):
return timezone.now() > self.date
def is_done(self):
self.done = True
self.done_date = timezone.now()
self.save()
And here are the urlpatterns and router:
router = routers.DefaultRouter(trailing_slash=False)
router.register(r'inspection', InspectionViewSet)
router.register(r'inspection/done', DoneInspectionsViewSet, basename='done-inspection')
router.register(r'inspection/undone', UndoneInspectionsViewSet, basename='undone-inspection')
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^admin/', admin.site.urls),
url(r'^inspections/', include(('inspections.urls','inspections'), namespace='inspections')),
]
urlpatterns += [
path('api/', include(router.urls)),
path('api/schema/', get_schema_view(
title = "DAPIMS",
description = "API for DAPIMS",
version = "1.0.0"
), name='openapi-schema'),
]
I have already tried to change the queryset and noticed that even if I just want to return all Inspection objects it still returns "detail: not found" even though if I run the interactive shell and execute the same queryset it returns the correct objects.
Here's an example of the return from the interactive shell
And this is what my Browsable API is returning
Thanks in advance!

Django - How to make multiple objects dynamic in the same page

Problem statement: Unable to make multiple elements dynamic in the same index page. Can you suggest me how to do it? I have almost 5 elements to be made dynamic in the same page.
I am using the following code
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index_a, name='index'),
path('', views.index_b, name = 'lunch')
]
views.py
from django.shortcuts import render
from . models import breakfast, lunch
# Create your views here.
def index_a(request):
brkfstn = breakfast.objects.all()
return render(request, "index.html",{'brkfstn':brkfstn})
def index_b(request):
lunchn = lunch.objects.all()
return render(request, "index.html",{'lunchn':lunchn})
models.py
from django.db import models
# Create your models here.
class breakfast(models.Model):
name = models.CharField(max_length=100)
ingrdnt = models.TextField()
image = models.ImageField(upload_to='images')
price = models.IntegerField()
discount = models.BooleanField(default=False)
offer_price = models.IntegerField()
class lunch(models.Model):
name = models.CharField(max_length=100)
ingrdnt = models.TextField()
image = models.ImageField(upload_to='images')
price = models.IntegerField()
discount = models.BooleanField(default=False)
offer_price = models.IntegerField()
Got my mistake.
Can add more elements in the dictionary in views.py
So updated my views.py as below:
from django.shortcuts import render
from . models import breakfast, lunch
# Create your views here.
def index_a(request):
brkfstn = breakfast.objects.all()
lunchn = lunch.objects.all()
return render(request, "index.html",{'brkfstn':brkfstn, 'lunchn':lunchn'})

django tutorial stuck

So I am doing the Django Practical Projects Tutorial and came very far.
I have this code:
def get_absolute_url(self):
return ('coltrane_entry_detail', (), {'year': self.pub_date.strftime("%Y"),
'month': self.pub_date.strftime("%b").lower(),
'day': self.pub_date.strftime("%d"),
'slug': self.slug })
get_absolute_url = models.permalink(get_absolute_url)
I get an Indentation Error.
If I indent than I get a working /weblog/ url but if I click on the "Read more" Links I always land on the same page /weblog/ and not /weblog/date/article.
If you know the tutorial, maybe you know the error if not here is all the files:
urls project:
from django.conf.urls.defaults import *
from Myproject.views import *
from django.views.generic.simple import direct_to_template
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
#Coltrane Project URlpatterns:
(r'^search/$', 'MyProject.search.views.search'),
(r'^weblog/$', include('coltrane.urls')),
Urls Coltrane:
from django.conf.urls.defaults import *
from coltrane.models import Entry
entry_info_dict = {
'queryset': Entry.objects.all(),
'date_field': 'pub_date',
}
#Coltrane Project URlpatterns:
urlpatterns = patterns('django.views.generic.date_based',
(r'^$', 'archive_index', entry_info_dict, 'coltrane_entry_archive_index'),
(r'^(?P<year>\d{4})/$', 'archive_year', entry_info_dict, 'coltrane_entry_archive_year'),
(r'^(?P<year>\d{4})/(?P<month>\w{3})/$', 'archive_month', entry_info_dict, 'coltrane_entry_archive_month'),
(r'^(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{2})/$', 'archive_day', entry_info_dict, 'coltrane_entry_archive_day'),
(r'^(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{2})/(?P<slug>[-\w]+)/$', 'object_detail', entry_info_dict, 'coltrane_entry_detail'),
)
Model:
import datetime
from django.contrib.auth.models import User
from django.db import models
from markdown import markdown
from tagging.fields import TagField
class Category(models.Model):
title = models.CharField(max_length=250, help_text='Maximum 250 characters.')
slug = models.SlugField(unique=True, help_text='This is the shortname that is created. Must be unique!')
description = models.TextField()
class Meta:
ordering = ['title']
verbose_name_plural = "Categories"
def __unicode__(self):
return self.title
def get_absolute_url(self):
return "/categories/%s/" %self.slug
class Entry(models.Model):
LIVE_STATUS = 1
DRAFT_STATUS = 2
HIDDEN_STATUS = 3
STATUS_CHOICES = (
(LIVE_STATUS, 'Live'),
(DRAFT_STATUS, 'Draft'),
(HIDDEN_STATUS, 'Hidden'),
)
#Core Fields.
title = models.CharField(max_length=250, help_text='Maximum 250 characters.')
excerpt = models.TextField(blank=True, help_text='A short summary of the entry. Optional!')
body = models.TextField()
pub_date = models.DateTimeField(default=datetime.datetime.now)
#Fields to store generated HTML.
excerpt_html = models.TextField(editable=False, blank=True)
body_html = models.TextField(editable=False, blank=True)
#Metadata
author = models.ForeignKey(User)
enable_comments = models.BooleanField(default=True)
featured = models.BooleanField(default=False)
slug = models.SlugField(unique_for_date='pub_date')
status = models.IntegerField(choices=STATUS_CHOICES, default=LIVE_STATUS, help_text="Only entries with live status will be publicly displayed")
#Categorization
categories = models.ManyToManyField(Category)
tags = TagField(help_text="Separate tags with spaces.")
class Meta:
ordering = ['pub_date']
verbose_name_plural = "Entries"
def __unicode__(self):
return self.title
def save(self, force_insert=False, force_update=False):
self.body_html = markdown(self.body)
if self.excerpt:
self.excerpt_html = markdown(self.excerpt)
super(Entry, self).save(force_insert, force_update)
def get_absolute_url(self):
return ('coltrane_entry_detail', (), {'year': self.pub_date.strftime("%Y"),
'month': self.pub_date.strftime("%b").lower(),
'day': self.pub_date.strftime("%d"),
'slug': self.slug })
get_absolute_url = models.permalink(get_absolute_url)
See the comments above, I found my error. I think the only way to close my own question is to answer it.