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'})
Related
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
So i need to post on page price-row like: name: medicalservice --> contains this prices --->
1# --- name --- price --- quantity
2# --- 2name --- 2price --- 2quantity
And i want to post them in one page
i need to take price rows exactly declared for this medical service
I cant get the idia how to get it done through admin panel (i dont know how to insert quantity value quantity into it)
I created an intermidiate model (services_count) but i think its not best idea :0
from django.db import models
from tinymce import models as tiny_models
from django.urls import reverse
class Medservices(models.Model):
public = 'pub'
private = 'priv'
status_post = [(public,'public'),(private,'private')]
position = models.IntegerField(default=1, verbose_name="Позиція")
status = models.CharField(max_length=10,default=public,choices=status_post, verbose_name="Статус показу")
photo = models.ImageField(verbose_name='Фото послуги або акції', upload_to='services_images', max_length=None)
date_start = models.DateField(verbose_name='Дата початку', auto_now=False, auto_now_add=False)
date_expire = models.DateField(verbose_name='Дата початку', auto_now=False, auto_now_add=False)
title = models.CharField(verbose_name='Назва послуги або акції', max_length=300)
text = text = tiny_models.HTMLField()
slug = models.SlugField(max_length=255,unique=True,verbose_name="URL",db_index=True)
def __str__(self):
return f"{self.price.all} - to {self.status}"
def get_absolute_url(self):
return reverse('service_page', kwargs={'post_slug': self.slug})
class services_count(models.Model):
quantity = models.IntegerField(verbose_name='Кількість цієї послуги у сервісі')
service = models.ForeignKey("medservices.Medservices", verbose_name='Послуга або акція', on_delete=models.CASCADE)
prices = models.ManyToManyField("price.Price", verbose_name='Ціни')
admin panel:
from django.contrib import admin
from medservices.models import Medservices, services_count
# Register your models here.
class MedservicesAdmin(admin.ModelAdmin):
list_filter = ('status','date_expire',)
list_display = ('title','date_start','date_expire')
prepopulated_fields = {"slug": ("title",)}
admin.site.register(Medservices, MedservicesAdmin)
class ServicesCountAdmin(admin.ModelAdmin):
list_display = ('quantity',)
admin.site.register(services_count, ServicesCountAdmin)
views.py :
from django.shortcuts import render
from . import models
# Create your views here.
def services_page(request):
services_list = models.Medservices.objects.filter(status__contains='pub').order_by('position').all()
services_list_dict = {
'service_rows':services_list,
'title': 'Послуги МЦ "Сторожик"'
}
return render(request, 'medservices/index.html', context=services_list_dict)
def service_page(request):
pass
Model Price from other app
from django.core import validators
from django.db import models
# Create your models here.
class Price(models.Model):
price_all_menu = 'Загальні'
doc_cons = 'Консультації'
analises = 'Аналізи'
UZD = 'УЗД'
Urology = 'Урологія'
Gynekology = 'Гінекологія'
price_menu = [(price_all_menu,'Загальні'),(doc_cons,'Консультації'),(analises,'Аналізи'),(UZD, 'УЗД'), (Urology, 'Урологія'), (Gynekology, 'Гінекологія')]
public = 'pub'
private = 'priv'
status_post = [(public,'public'),(private,'private')]
code = models.CharField(max_length=10)
name = models.CharField(max_length=300)
price = models.CharField(max_length=40)
position = models.IntegerField(default=1)
status = models.CharField(max_length=10,default=public,choices=status_post)
menu = models.CharField(max_length=100,default=price_all_menu,choices=price_menu)
def __str__(self):
return f"{self.code} -- {self.name} -- {self.price} - [{self.position}] - [{self.status}]"
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!
I want to create a song list for eg "movie name Titanic and it contains all its songs" but I don't know to add more than one song in a movie, can some one help me here?
Here is what I am doing
views.py
from django.shortcuts import render_to_response
from .models import Songs
def Songs(request):
songs = Songs.objects.all()
return render_to_response('profile_page.html',{'songs':songs})
models.py
from django.db import models
class Movie(models.Model):
name= models.CharField(max_length = 100)
class Songs(models.Model):
movie = models.ForeignKey(Movie, default= 1)
song_title = models.CharField(max_length=20)
song_poster = models.FileField()
song_list = models.FileField()
urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^',views.Songs),
]
create a model called Movie
class Movie(models.Model):
name= models.CharField(max_length = 100)
// other fields as needed
class Songs(models.Model):
movie = models.ForeignKey(Movie)
song_title = models.CharField(max_length=20)
song_poster = models.FileField()
song_list = models.FileField()
then add songs according to movie and query according to movie id
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'),
]