inside of the views.py
def book_detail(request, pk):
book = get_object_or_404(Library, pk=pk)
return render(request, 'book_detail.html', context={'book': book})
def admin_book_detail(request, pk):
book = get_object_or_404(Library, pk=pk)
return render(request, 'admin_book_detail.html', context={'book': book})
Hello, I am new to Django. I have two views like this. One of them is for normal user and the other one is for admin. But the template of admin takes it's information from the other one. Like, If I change the book_detail, admin_book_detail changes too. But if i change admin_book_detail's information, nothing happens.
inside of admin_book_detail.html
{% block content %}
{{ block.super }}
<div style="margin:0 auto;width:1200px;">
<h1 class="page-header" style="color:black;">{{ book.title }}</h1>
<h2> This book is <b>{{ book.availability }}</b> to borrow</h2>
<br>
<h3>Author of the Book = <b>{{ book.author }}</b></h3>
<br>
<h3>Publish Year = <b>{{ book.year }}</b></h3>
<br>
<h3> Category = <b>{{ book.category }}</b></h3>
<div style="padding: 10px 5px;">
<div style="background-color: white;padding: 10px 30px; width:175px;border: 3px solid black;text-align:center;">
<a style="color:black; font-size:19px;" href="{% url 'adminbook' %}"><b>Go Back</b></a>
</div>
</div>
</div>
{% endblock %}
inside of book_detail.html
{% block content %}
{{ block.super }}
<div style="margin:0 auto;width:1200px;">
<h1 class="page-header" style="color:black;">{{ book.title }}</h1>
<h2> This book is <b>{{ book.availability }}</b> to borrow</h2>
<br>
<h3>Author of the Book = <b>{{ book.author }}</b></h3>
<br>
<h3>Publish Year = <b>{{ book.year }}</b></h3>
<br>
<h3> Category = <b>{{ book.category }}</b></h3>
<div style="padding: 10px 5px;">
<div style="background-color: white;padding: 10px 30px; width:175px;border: 3px solid black;text-align:center;">
<a style="color:black; font-size:19px;" href="{% url 'book' %}"><b>Go Back</b></a>
</div>
</div>
{% endblock %}
inside of the url
urlpatterns = [
path('request_book/', request_book, name='request_book'),
re_path(r'book_detail/(?P<pk>[0-9]+)/', book_detail, name='book_detail'),
re_path(r'admin_book_detail/(?P<pk>[0-9]+)/', admin_book_detail, name='admin_book_detail'),
path('add_book/', add_book, name='add_book')
]
Edit : Ok I fixed it.
What I can see is that both of your views does the same thing. So it really won't matter whichever view you call.
It's different on the HTML page on basis of how you want to represent that information.
They both access the same object without any specific filter, so they're going to return the same object. If you are looking to display different filtered results, you need to change the query.
Related
My name is arslan chaudhry, currently i am working with django. In my django project i have made some filters to filter the product category wise.i have successfully display the category of products. But when i click on the category image i recived an empity page no error is dispalyed.
I think data are not passing from view.py to html template.How i can fix this?
the code is given below.
views.py
def collectionsview(request, slug):
if(Category.objects.filter(slug=slug, status=0)):
products=Product.objects.filter(category__slug=slug)
category_name=Category.objects.filter(slug=slug).first()
contex={products:"products",category_name:"category_name"}
print(products)
return render(request, "store/product/index.html", contex)
else:
return HttpResponse('This is not a valid product')
html template
{% extends 'store/layouts/main.html' %}
{% block title %}Home{% endblock title %}
{% block body %}
<div class="container mt-3">
<div class="row">
<div class="col-md-12">
<h4>{{category_name}}</h4>
<div class="row">
{% for item in products %}
<div class="col-md-2">
<div class="card">
<a href="#">
<div class="card-body ">
<div class="card-image">
<img src="{{item.imge.url}}" alt="" width="100%" height="100%">
<h4 class="text-center mt-1" style="font-size: medium; font-weight: 600;">{{item.name}}</h4>
</div>
<span>{{item.original_price}}</span>
<span>{{item.selling_price}}</span>
</div>
</a>
</div>
</div>
{% endfor %}
</div>
</div>
</div>
</div>
{% endblock body %}
I am a student who wants to be good at Django. The button does not work. If you press the button in detail.html, I want to save the product in DB as if I purchased it. My goal is to get the buyer, date, and product code as written on views.py. However, even if you press the button now, you can't save it in DB. What's the problem?
model.py
class Join(models.Model):
join_code = models.AutoField(primary_key=True)
username = models.ForeignKey(Member, on_delete=models.CASCADE, db_column='username')
product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code')
part_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.join_code)
class Meta:
ordering = ['join_code']
Join/views
from datetime import timezone
from django.shortcuts import render
from zeronine.models import *
def join_detail(request):
product = Product.objects.all()
if request.method == "POST":
join = Join()
join.product_code = product
join.username = request.user
join.part_date = timezone.now()
join.save()
return render(request, 'zeronine/detail.html', {'product': product})
detail.html
{% extends 'base.html' %}
{% block title %} 상품 상세보기 {% endblock %}
{% block content %}
<div class="container">
<div class="row">
<div class="col-4">
<img src="{{product.image.url}}" width="190%" style="margin-top: 35px;">
</div>
<div class="text-center col" style="margin-top:150px; margin-left:200px;">
<b><h4 class="content" style="margin-bottom: -5px;"><b>{{product.name}}</b></h4></b>
<br>
<div>
<!-- <span>주최자 : <b>{{ product.username }}</b></span><br>-->
<span style="color: #111111">모집기간 : <b>{{ product.start_date }} ~ {{ product.due_date }}</b></span>
</div>
<hr style="margin-top: 30px; margin-bottom: 30px;">
<p><span class="badge badge-dark">가격</span>
{% load humanize %}
{% for designated in designated_object %}
{% if designated.product_code.product_code == product.product_code %}
{{designated.price | floatformat:'0' | intcomma }}원
{% endif %}
{% endfor %}</p>
<span class="badge badge-dark">목표금액</span> {{ product.target_price | floatformat:'0' | intcomma }}원 <br><br>
<p class="badge badge-dark">공동구매 취지
{{product.benefit|linebreaks}}</p>
<p class="badge badge-dark">상세설명
{{product.detail|linebreaks}}</p>
<br>
<form action="" method="post">
{% csrf_token %}
<a onclick="alert('{{ product.name }} 공동구매 참여가 완료되었습니다.');" style="cursor:pointer;">
<form method="POST" action ="{% url 'zeronine:join_detail' %}">
{% csrf_token %}
<div class="form-group">
<button type="submit" action="{% url 'zeronine:join_detail' %}" class="btn btn-primary" style="float: right; background: #637B46; border: white">업로드</button>
</div>
</form>
</a>
</form>
</div>
</div>
</div>
{% endblock %}
I am not sure but you have a form inside a form in your template. maybe that is causing the problem.
also
in the POST section. it is best practice to use
join = Join.objects.create(product_code=product, ....)```
I am unable to access the user context data for my view in the associated template file.
views.py
def userprofile(request,username):
user=User.objects.filter(username=username)
if user:
user=user[0]
profile=Profile.objects.get(user=user)
post=getPost(user)
bio=profile.bio
conn=profile.connection
follower=profile.follower
following=profile.following
user_img=profile.userImage
print(user)
print(bio)
print(conn)
print(follower)
print(following)
print(user_img)
print(user)
data={
'user':user,
'bio':bio,
'conn':conn,
'follower':follower,
'following':following,
'userImg':user_img,
'posts':post
}
print(data)
return render(request,'userview/userProfile.html')
else:
return HttpResponse(" 404 No Such User exist")
My data is printed in the console after runserver, so can you tell me why it is not accessible in the template file below.
profile.html
{% extends 'base.html' %}
{% block title %}profile{% endblock title %}
<style>
.pst{
width: 350px;
height: 200px;
margin-bottom: 30px;
}
</style>
{% block body %}
<div class="container my-4">
<div class="media">
<img src="{{userImg.url}}"class="align-self-start mr-3 userImage" alt=".......">
<div class="media-body-info">
<h4 class="mt-4" >{{user.get_username}}</h4>
<p>Follower : {{follower}} Following : {{followin}} </p>
<p><b>{{bio}}</b></p>
</div>
</div>
<hr>
<!-- <h3> Username:{{user.get_username}}</h3>
<h3> FirstName:{{user.first_name}}</h3>
<h3> lastname:{{user.last_name}}</h3>
<h3> Email:{{user.email}}</h3> -->
<!-- <h3> country:{{user.country}}</h3> sss -->
<div class="row">
{% for i in posts %}
{% for j in i %}
<div class="col-md--4 ">
<img src="{{j.image.url}}" alt="" class="pst">
</div>
{% endfor %}
{% endfor %}
</div>
</div>
{% endblock body %}
You are not passing the context data to your template. You need to change your render call to return render(request,'userview/userProfile.html', data).
Also, make sure the path to your template file is correct.
I would take a look at Django Getting Started guide as your code could generally be tidied up a bit.
views.py
from django.shortcuts import render, get_object_or_404
from library.models import Game
from .models import Post
from django.views.generic import (
ListView
)
from django.template import context
# Create your views here.
def home(request):
context = {
'recent': Game.objects.all().order_by('post__date_posted')[:5],
'posts': Post.objects.all()
}
return render(request, 'main/home.html', context)
class TitlePostListView(ListView):
model = Post
template_name = 'main/title_posts.html'
context_object_name = 'posts'
def get_queryset(self):
title = get_object_or_404(Game, title=self.kwargs.get('title'))
return Post.objects.filter(game=title).order_by('-date_posted')[:5]
title_posts.html
{% extends "main/base.html" %}
{% load static %}
{% block styles %}
<link rel="stylesheet" type="text/css" href="{% static 'main/title_posts.css' %}">
{% endblock styles %}
{% block content %}
<style>
body {
background-image: url("{{ game.cover_display.url }}");
background-repeat: no-repeat;
background-size: 100% 1000px;
background-color: #171717;
}
</style>
<div class="container margin-top-300">
<div class="row justify-content-center">
<div class="col-3 text-center">
<img src="{{ game.cover.url }}">
</div>
<div class="col">
<p>{{ game.description| safe }}</p>
</div>
</div>
<hr>
{% for post in posts %}
<div class="row">
<div class="col-4 article-column-height text-center">
<img class="article-image-height" src="{{ post.article_image.url }}">
</div>
<div class="col-8 article-column-height">
<h2><a class="article-title" href="#">{{ post.article_title }}</a></h2>
</div>
</div>
<hr>
</div>
{% endfor %}
{% endblock content %}
models.py
class Post(models.Model):
article_title = models.CharField(max_length=60, default="Article Title Place Holder")
content = HTMLField(default="Article Content Pace Holder")
date_posted = models.DateTimeField(default=timezone.now)
game = models.ForeignKey('library.Game', on_delete=models.CASCADE)
article_image = models.ImageField(default='/media/default.png')
class Game(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
cover = models.ImageField()
cover_display = models.ImageField(default='default.png')
developer = models.CharField(max_length=100)
Edit: I have a page that displays posts/articles for a certain video game. Currently my query returns the posts from the Post model for that video game. However, I am unsure of how to also display the video games description and images on that same page. The {{game.cover.url}}, ((game.description}}, and {{game.cover_display.url}} do not show up when I load the page because I am unsure how to also get that specific games objects from the Game model.
{% for post in posts %}
{% with post.game.set.all|first as game %}
<style>
body {
background-image: url("{{ game.cover_display.url }}");
background-repeat: no-repeat;
background-size: 100% 1000px;
background-color: #171717;
}
</style>
<div class="container margin-top-300 black">
<div class="row justify-content-center">
<div class="col-3 text-center">
<img src="{{ game.cover.url }}">
</div>
<div class="col">
<p>{{ game.description| safe }}</p>
</div>
</div>
{% endwith %}
<hr>
<div class="row">
<div class="col-4 article-column-height text-center">
<img class="article-image-height" src="{{ post.article_image.url }}">
</div>
<div class="col-8 article-column-height">
<h2><a class="article-title" href="#">{{ post.article_title }}</a></h2>
</div>
</div>
<hr>
</div>
{% endfor %}
You are using ForeignKey. So use like this in loop
{% with post.game_set.all|first as game %}
<img src="{{ game.url }}" />
{% endwith %}
As you are already filtering by game then only add the game in your get_context_data() method
def get_context_data(self, **kwargs):
context = super(TitlePostListView, self).get_context_data(**kwargs)
context['game'] = get_object_or_404(Game, title=self.kwargs.get('title'))
return context
I am trying to edit the details I gathered using a form with POST method now I want to edit those details. I tried it but it is not working can you guys tell what am I doing wrong ?
View of edit post
#login_required()
def edit_product(request, product_id):
form = NewPro()
edit = get_object_or_404(Product, product_id)
if request.method == 'POST':
form = NewPro(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('product')
else:
form = NewPro()
return render(request, "default/edit.html", {'form': form, 'edit': edit})
Url pattern
path('<int:product_id>/edit_product', views.edit_product, name='edit_product')
Html where I am trying to add the button
{% extends 'default/dashboard.html' %}
{% block content %}
<h1>Products Details </h1>
<p>These are the details of your product, {{ user.username }}</p>
<ul>
<li>{{ product_details.name }}</li>
<li>{{ product_details.price }}</li>
<li>{{ product_details.category }}</li>
<li>{{ product_details.store }}</li>
<li>{{ product_details.user }}</li>
</ul>
<a href={% url 'edit_product' edit.id %}>
<button>Edit Product</button>
</a>
{% endblock %}
Html where I am trying to show the form
{% extends 'default/dashboard.html' %}
<html>
<head><title>E-Commerce App</title></head>
{% block content %}
<h2>Edit Product</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">submit</button>
</form>
{% endblock %}
</html>
I want to used this card instead of the one you gave me.
<div class="card-deck">
<div class="card">
<img class="card-img-top" src=".../100px200/" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">Card title</h5>
<p class="card-text">This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
<p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>
</div>
</div>
<div class="card">
<img class="card-img-top" src=".../100px200/" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">Card title</h5>
<p class="card-text">This card has supporting text below as a natural lead-in to additional content.</p>
<p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>
</div>
</div>
<div class="card">
<img class="card-img-top" src=".../100px200/" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">Card title</h5>
<p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.</p>
<p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>
</div>
</div>
</div>
You have to pass the instance of the product you want to edit to your form.
#login_required()
def edit_product(request, product_id):
product_to_edit = get_object_or_404(Product, pk=product_id)
form = NewPro(instance=product_to_edit)
if request.method == 'POST':
form = NewPro(request.POST, request.FILES, instance=product_to_edit)
if form.is_valid():
form.save()
return redirect('product')
else:
form = NewPro(instance=product_to_edit)
return render(request, "default/edit.html", {'form': form, 'product': product_to_edit})
On the comments you asked how to display all products inside cards so that there are 4 products per row. Try this out!
<div class="container">
<div class="row">
{% for product in products %}
<div class="col-sm-3">
<div class="card" style="width: 18rem;">
<img class="card-img-top" src="..." alt="Card image cap">
<div class="card-body">
<h5 class="card-title">{{ product.title }}</h5>
<p class="card-text">{{ product.description }}</p>
Edit Product
</div>
</div>
</div>
{% endfor %}
</div>
</div>
For the issue you raise about using a card deck instead, This is how I would do it.
Please Note: I haven't tested it.
views.py:
def all_products(request):
products = Product.objects.all()
grouped_products = []
temp = []
for i in range(len(products)):
if (i+1) % 3 == 0:
grouped_products.append(temp)
temp = []
temp.append(products[i])
return render(request, 'products.html', {'products': grouped_products})
templates:
<div class="container">
{% for product_list in products %}
<div class="row">
<div class="card-deck">
{% for product in product_list %}
<div class="card">
<img class="card-img-top" src=".../100px200/" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">Card title</h5>
<p class="card-text">This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
<p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>
</div>
</div>
{% endfor %}
</div>
</div>
{% endfor %}
</div>