Display data from a database in a HTML page using django views - django

I have a problem with creating a view with data from the database. I created a view that should download data from videos (var films) and display them, unstable
views.py
from .models import Films
def index(request):
filmy = Films.objects
return render(request, 'films/index.html',{'filmy':filmy})
index.html
<h1>Films</h1>
{% for film in films.all %}
{{filmy.summary}}
<br>
{% endfor %}
models.py
class Films(models.Model):
image = models.ImageField(upload_to='images/')
summary = models.CharField(max_length=200)
def __str__(self):
return self.summary
I only have a blank page.

Your views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Films
# Create your views here.
def index(request):
films = Films.objects.all()
return render(request, 'films/index.html',{'films':films})
In index.html
{% for film in films %}
<p> {{film.summary}} </p>
{% endfor %}
I hope that helps.

Related

How can i have same html for multiple categories or pages and then add specific or different data from database to them in django restframework?

In this program i have these two functions in my views.py:
def home(request):
p=product.objects.all()
return render(request,'home.html',{'p':p})
def foods(request):
p=product.objects.all()
return render(request,'foods.html',{'p':p})
They both have access to the same data from database i mean if i want to post some json with django restframework then foods and home will have the same data because they have the same html:
<div class="grid">
{% for i in p%}
<div class='card'>
<img src="{{i.image}}"></img>
<p id="id">{{i.description}}</p>
<a href="{{i.buy}}" target='_blank' rel='noopener noreferrer'>
<button><span class="price"> ${{i.price}}</span> buy</button>
</a>
</div>
{%endfor%}
</div>
it is good for me to have just one html for multiple pages and then access to different data from database but if i add some json both of them will contain the same data(for some reason data of foods is empty but it will generate the same number of products based on json like home)
I want to know how can you have same html for multiple categories or pages and then add specific or different data from database to them?
More details:
models.py:
from django.db import models
# Create your models here.
class product(models.Model):
image=models.CharField(max_length=500)
description=models.CharField(max_length=500)
price=models.CharField(max_length=50)
buy=models.CharField(max_length=100)
serializers.py:
from rest_framework import serializers
from .models import product
class productSerializer(serializers.ModelSerializer):
class Meta:
model= product
fields="__all__"
views.py:
from django.shortcuts import render
from .models import *
from rest_framework import viewsets,status
from .serializers import productSerializer
from rest_framework.parsers import JSONParser
from django.http import HttpResponse,JsonResponse
from rest_framework.response import Response
from rest_framework.decorators import action
class productviewset(viewsets.ModelViewSet):
queryset=product.objects.all()
serializer_class = productSerializer
def create(self, request):
serialized = productSerializer(data=request.data, many=True)
if serialized.is_valid():
serialized.save()
return Response(serialized.data, status=status.HTTP_201_CREATED)
return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)
#action (detail=False , methods=['post'])
def delete(self,request):
product.objects.all().delete()
return Response('success')
def home(request):
p=product.objects.all()
return render(request,'home.html',{'p':p})
def foods(request):
p=product.objects.all()
return render(request,'foods.html',{'p':p})
If i have 20 categories with 20 different pages i will never create 20 different databases if there is a way for those categories to access specifically from the same database.
If I understand the question correctly and you will have a certain amount of goods divided into 20 categories, then I somehow used this
You need to create a separate model for the categories, and in the product model add a foreign key to the category
models.py
class Category(models.Model):
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True, unique=True)
def get_absolute_url(self):
return reverse('shop:product_list_by_category',
args=[self.slug])
def __str__(self):
return self.name
class Product(models.Model):
category = models.ForeignKey(Category, related_name='products')
available = models.BooleanField(default=True)
...
views.py
def product_list(request, category_slug=None):
category = None
categories = Category.objects.all()
products = Product.objects.filter(available=True)
if category_slug:
category = get_object_or_404(Category, slug=category_slug)
products = products.filter(category=category)
return render(request,
'shop/product/list.html',
{'category': category,
'categories': categories,
'products': products})
urls.py
from django.urls import path
from . import views
app_name = 'shop'
urlpatterns = [
path('', views.product_list, name='product_list'),
path('<category_slug>', views.product_list, name='product_list_by_category'),
]
html
{% block content %}
<div id="main" class="product-list">
<h1>{% if category %}{{ category.name }}{% else %}Products{% endif %}</h1>
{% for product in products %}
<div class="item">
<img src="{% if product.image %}{{ product.image.url }}{% else %}{% static "img/no_image.png" %}{% endif %}">
</div>
{% endfor %}
</div>
{% endblock %}

Can't retrieve field from my model

I need to show fields title and text in separate text area in my template. I can't access them cause I am new in django here are my models.py
class Banner(models.Model):
title = models.CharField(max_length=100)
text = models.CharField(max_length=500)
def __str__(self):
return self.title
and views.py
def home(request):
context = {}
return render(request, 'home/home.html', context)
First import the model and use queryset to get all the data and then return it to view using render and use the pass content wherever you want in view
from .models import Banner
def home(request):
queryset = Banner.objects.all()
context = {
'object_list': queryset
}
return render(request, 'home/home.html', context)
In you views html file you can use following:
{% for obj in object_list %}
{{ obj.title }}
{% endfor %}
Your views is lack of information, you should import and call your objects
from .models import Banner
def home(request):
context = {}
context['banners'] = Banner.objects.all()
return render(request, 'home/home.html', context)
In your html you can call
{% for banner in banners %}
{{ banner.title }}
{% endfor %}

Check if User is in Many2Many field

I have the following model with a m2m field where logged in Users can show interest in a publication:
models.py
from django.db import models
class Publication:
title = models.CharField(max_lenth=512)
users_interested = models.ManyToManyField(User)
views.py
from django.shortcuts import render
from django.views import View
from .models import Publication
class listPublicationView(View):
def get(self, request, *args, **kwargs):
publications = Publication.objects.all()
return render(request, "base.html", {'publications': publications})
Now i try to produce a "i am already interested" in the template when a logged in user is already interested in the publication:
base.html
{% for publication in publications %}
{{publication.title}}
{% if currently logged in User is interested in publication (check users_interested) %}
i am already interested
{% endif %}
{% endfor %}
I think about something like this:
{% if user.id in publication.users_interested__id %}
Try like this:
{% if request.user in publication.users_interested.all %}
request.user property holds the current logged in user
Then you use the in operator with publications.users_interested.all() (Note that there are no parenthesis on .all() in template
This seems to look like a good solution:
models.py
from django.db import models
class Publication:
title = models.CharField(max_lenth=512)
#added a reverse accessor
users_interested = models.ManyToManyField(User, related_name='users_interested')
view.py
from django.shortcuts import render
from django.views import View
from .models import Publication
class listPublicationView(View):
def get(self, request, *args, **kwargs):
publications = Publication.objects.all()
# create a set of group IDs that this user is a part of
current_user = request.user
user_publication_set = set(current_user.users_interested.values_list('id', flat=True))
#pass set to template
return render(request, "base.html", {'publications': publications, 'user_publication_set': user_publication_set})
base.html
{% for publication in publications %}
{{publication.title}}
{% if publication.id in user_publication_set %}
i am already interested
{% endif %}
{% endfor %}
Found this solution in Django: check for value in ManyToMany field in template

Django Tutorail - Part 3 - Cannot Access Model Values

I did the entire django site tutorial and I am now trying to redo it without consulting the tutorial, to see which parts I remembered and which I did not.
I can successfully load a template when I go to the correct url.
post_list.html
<h1>The Blogs Index Page</h1>
<h2> Posts </h2>
{% for post in latest_post_list %}
<p> {{ post.title }}<p>
{% endfor %}
models.py
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=100)
body = models.TextField()
pub_date = models.DateTimeField()
def __str__(self):
return self.title
Relevant views.py
from django.shortcuts import render
from django.core.urlresolvers import reverse
from .models import Post
def index(request):
latest_post_list = Post.objects.order_by('pub_date')
context = {'latest_post_list': latest_post_list}
return render(request, 'blog/index.html', context)
The page only displays the H1 and H2 tag information, everything else is just blank. I have a suspicion that latest_post_list does not exist.
When using the shell, I am able to...
>>> from blog.models import Post
>>> Post.objects.all()
[<Post: First Post>, <Post: Second Post>, <Post: Third Post>]
So the titles exist. I am at a loss to why I can not access my post.titles from the Template.

django form.save() fails to write to disk on model instance update

Ive been Playing around with django to create an asset management app and have hit a wall on the file upload to model instance behaviour.
I am attempting to use the ModelForm class in Forms.py
Basically im pretty certain that form.save() is not writing my uploaded file to disk to update my model instance.
Do I have to write a form.save definition into my AssetForm ? or have I missed something else.
Appreciate any help.
My project is built around the Polls tutorial https://docs.djangoproject.com/en/1.8/intro/tutorial01/ and the minimal file upload tutorial at Need a minimal Django file upload example.
Here is my model .py
class Category(models.Model):
category_text = models.CharField(max_length=200)
def __str__(self): # __unicode__ on Python 2
return self.category_text
class Asset(models.Model):
asset_text = models.CharField(max_length=200)
asset_tag = models.CharField(max_length=200)
asset_category = models.ForeignKey(Category)
cert_date = models.DateTimeField('cert published')
def __str__(self): # __unicode__ on Python 2
return self.asset_text
def was_certed_recently(self):
return self.cert_date >= timezone.now() - datetime.timedelta(days=365)
was_certed_recently.admin_order_field = 'cert_date'
was_certed_recently.boolean = True
was_certed_recently.short_description = 'Certified recently?'
docfile = models.FileField(upload_to='documents')
Here is my forms.py
from django import forms
from django.forms import ModelForm
from polls.models import Asset
class AssetForm(ModelForm):
class Meta:
model = Asset
fields = '__all__'
Here is my views.py
# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.http import HttpResponse
#from django.template import RequestContext, loader
from django.shortcuts import get_object_or_404, render
from django.http import Http404
from polls.models import Asset
from polls.forms import AssetForm
def list(request, asset_id):
# Handle file upload
ID = asset_id
p = get_object_or_404(Asset, pk = asset_id)
if request.method == 'POST':
form = AssetForm(request.POST, request.FILES, instance= p )
if form.is_valid():
form.save()
# Redirect to the document list after POST
return HttpResponseRedirect(reverse('list', args=(p.id,)))
else:
form = AssetForm() # A empty, unbound form
# Load documents for the list page
documents = p
# Render list page with the documents and the form
return render_to_response(
'polls/list.html',
{'documents': documents, 'ID': ID, 'form': form},
context_instance=RequestContext(request )
)
def index(request):
latest_asset_list = Asset.objects.order_by('-cert_date')[:]
context = {'latest_asset_list': latest_asset_list}
return render(request, 'polls/index.html', context)
url.py
from django.conf.urls import url
from . import views
urlpatterns = [
#url(r'^/list/$', 'list', name='list'),
url(r'^$', views.index, name='index'),
# ex: /polls/5/
url(r'^(?P<asset_id>[0-9]+)/$', views.list, name='list'),
# ex: /polls/5/results/
url(r'^(?P<asset_id>[0-9]+)/results/$', views.results, name='results'),
# ex: /polls/5/vote/
url(r'^(?P<asset_id>[0-9]+)/vote/$', views.vote, name='vote'),
]
Finally my list.html template
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Minimal Django File Upload Example</title>
</head>
<body>
<!-- List of uploaded documents -->
{% if documents %}
<ul>
<p>Current Doc.</p>
<li>{{ documents.docfile.name }}</li>
</ul>
{% else %}
<p>No documents.</p>
{% endif %}
<ul>
{{ ID }}
<!-- Upload form. Note enctype attribute! -->
<form action="{% url 'list' ID %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>
<p>
{{ form.docfile.errors }}
{{ form.docfile }}
</p>
<p><input type="submit" value="Upload" /></p>
</form>
</body>
</html>
You're doing various things twice. For example, at the start of your function, you get an Asset into p and then you get the same one into a. Why?
More significantly, in the is_valid() block you create a new Asset object just from the uploaded file, with no other data from the form, but then you save the form itself which should update the existing Asset. This might be the cause of your problem - you should remove the lines with docfile and just save the form.