Would like to simplely show multiple pictures from my model data that I inputted via the Admin in my template file between the UL tag. I am having trouble rendering the data to show the image. I dont need to route anything in URL.py yet, just need to pollute the images on my homepage first. Can someone please help troubleshoot my issue? Thank you!
Models.py
class Product(models.Model):
name = models.CharField(max_length=254, blank=True, null=True)
description = models.TextField(blank=True, null=True)
color_name = models.CharField(max_length=254, null=True, blank=True)
size_types = models.CharField(max_length=7, null=True, blank=True)
product_price = models.DecimalField(max_digits=9,decimal_places=2)
old_price = models.DecimalField(max_digits=9,decimal_places=2, blank=True,default=0.00) #To show original price if, new price has been added
product_tags = models.CharField(max_length=254, null=True, blank=True, help_text='Comma-delimited set of SEO keywords for product tag area')
novelty = models.CharField(max_length=254, null=True, blank=True)
product_website = models.URLField(max_length=200, null=True, blank=True) #To show other sites to Users, where they can purchase the particular product
image = models.ImageField(upload_to='images/products/main',max_length=100, null=True) #For the argument upload_to, will add to the static folder and generated image will be stored in suing that path specified
slug = models.SlugField(max_length=255, unique=True, help_text='Unique value for product page URL, created from name.')
#This shows when each item was uploaded & by who, to the User
uploaded_by = models.CharField(max_length=254, blank=True, null=True)
uploaded_at = models.DateTimeField(auto_now=True)
#For Admin Purposes, to track and see which if still active by for administrative users only
is_active = models.BooleanField(default=True)
#Foreign Keys & other relationships
designer = models.ForeignKey(Designer)
boutique = models.ForeignKey(Boutique)
category = models.ForeignKey(ProductCategory)
#Metadata
class Meta:
verbose_name = _("Product")
verbose_name_plural = _("Products")
#Helps return something meaningful, to show within the admin interface for easy interaction
def __unicode__(self):
return "{0}".format(self.name)
Forms.py
from __future__ import unicode_literals
from django import forms
from django.forms import extras, ModelForm
from products.models import Designer, Product, ProductCategory, Boutique
class DesignerForm(ModelForm):
class Meta:
model = Designer
class ProductForm(ModelForm):
class Meta:
model = Product
class BoutiqueForm(ModelForm):
class Meta:
model = Boutique
class ProductCategoryForm(ModelForm):
class Meta:
model = ProductCategory
Views.py
from __future__ import unicode_literals
from django.http import Http404, HttpResponseForbidden
from django.shortcuts import redirect, get_object_or_404
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from django.views.generic import DetailView
from django.contrib import auth, messages
from django.contrib.sites.models import get_current_site
from django.shortcuts import render
from products.forms import ProductForm, ProductCategoryForm
from products.forms import BoutiqueForm
from products.forms import DesignerForm
from products.models import Boutique, Product, ProductCategory, Designer
class ProductView(DetailView):
model = Product
context_object_name = "task"
Template
{% extends "site_base.html" %}
{% load i18n %}
{% block body %}
<div id="main" role="main">
<ul id="tiles">
<li>
{% for task in products %}
<img src="{{MEDIA_URL}}images/product/main {{task.image.url}}" />
{% endfor %}
</li>
</ul>
</div>
{% endblock %}
There are some odd things in this code.
Firstly, you want to do something with all products. So why are you using a DetailView, which is for selecting and displaying a single item? You need to use a ListView, which will pass a list of products.
Secondly, for some reason you override context_object_name to be "task". But then in the template, you iterate through "products" - a name that is not provided. If you've called the context object "task", that's what you should be iterating over.
Figured out what I was doing wrong!
Apparently I needed to go within my urls and change my already existing TemplateView in the first url tuple:
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
from django.views.generic import TemplateView
from django.contrib import admin
urlpatterns = patterns('',
url(r"^$", TemplateView.as_view(template_name="homepage.html"), name="home"),
url(r'^admin/', include(admin.site.urls)),
url(r"^account/", include("account.urls")),
url(r'^likes/', include('likes.urls')),
)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
and change the URL tuple to a ListView, to generate the image from my django models.
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
from django.views.generic import ListView
from products.models import Product
from django.contrib import admin
urlpatterns = patterns('',
url(r"^$", ListView.as_view(
template_name="homepage.html",
model = Product,
context_object_name = "products",
), name="home"),
url(r'^admin/', include(admin.site.urls)),
url(r"^account/", include("account.urls")),
url(r'^likes/', include('likes.urls')),
)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Related
Hello everyone I have just started developing my blog with django but I don't get to display my posts individually. DetailView doesn't work, please help!
here is my url
from django.urls import path
from .views import Home, ArticleDetailView
urlpatterns = [
path('', Home.as_view(), name='home'),
path('article/<int:pk>', ArticleDetailView.as_view(), name='article_details'),
]
Here is my view.
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from .models import Article
# Create your views here.
class Home(ListView):
model = Article
template_name = 'home.html'
class ArticleDetailView(DetailView):
model = Article
template_name = 'article_detail_view.html'
My model
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Article(models.Model):
title = models.CharField(max_length=255)
author = models.ForeignKey(User, on_delete=models.CASCADE)
body = models.TextField()
def __str__(self):
return self.title + '|' + str(self.author)
class Meta:
verbose_name = 'Article'
verbose_name_plural = 'Articles'
Home.html
<h2>Post</h2>
<ul>
{% for post in object_list %}
<li>{{post.title}} by {{ post.author }}</br>
<p>{{post.body}}</p></li>
{% endfor %}
</ul>
article_detail_view.html
<h2>Article Detail View</h2>
<h2>{{post.title}} By {{ post.author }}</h2></br>
<p>{{post.body}}</p>
Thanks for updating the question.
First add the get_absolute_url method to the model as follows:
class Article(models.Model):
title = models.CharField(max_length=255)
author = models.ForeignKey(User, on_delete=models.CASCADE)
body = models.TextField()
def __str__(self):
return self.title + '|' + str(self.author)
class Meta:
verbose_name = 'Article'
verbose_name_plural = 'Articles'
def get_absolute_url(self):
return reverse("article_details", kwargs={"pk": self.pk})
In your article_detail_view.html, you can access the article using the article instance:
<h2>Article Detail View</h2>
<h2>{{article.title}} By {{ article.author }}</h2></br>
<p>{{article.body}}</p>
in your article_detail_view.html
you can access the article by: {{object.title}}
you can also specify what to return in template and how you wanna name it by overriding get_context_data
check this
in models.py
class Meta:
managed = True
verbose_name = 'Article'
verbose_name_plural = 'Articles'
I'm trying to display a basic form in django but does not render the form once I run the server, I would appreciate if you could help me with these, here my code.
models.py
STATUS_OPTIONS =(
('OP', 'OPEN'),
('CL', 'CLOSED')
)
class Employee(models.Model):
id = models.AutoField(primary_key=True)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
email = models.EmailField(max_length=200)
status = models.CharField(max_length=50, choices=STATUS_OPTIONS)
password = models.CharField(max_length=100)
def __str__(self):
return self.first_name
forms.py
from django import forms
from .models import Employee
class EmployeeForm(forms.Form):
class Meta:
model = Employee
fields = "__all__"
urls.py
from django.urls import include, path
from . import views
urlpatterns = [
path('', views.create_employee),
]
views.py
from .forms import EmployeeForm
# Create your views here.
def create_employee(request):
form = EmployeeForm()
return render(request, 'employee/create_employee.html', {'form':form})
create_employee.html
<h1>Formu</h1>
<form action="" method='POST'>
{{form.as_p}}
<input type="submit">
</form>
When I run the program the only thing rendered is the tag, any idea?
In order to create forms out of models you need to use ModelForm not Form. Otherwise you end up with a regular form without any field.
from django.forms import ModelForm
from .models import Employee
class EmployeeForm(ModelForm):
#...
More about ModelForm here
Short Story: I have made two apps. Properties and Tenants within a django project. First I started rendering data from Property model to property_detail.html template and it works fine, but after I created & migrated the Tenants model, and I try to render data from there to property_detail.html it doesn't work. Yet it doesn't give me any errors. It just doesn't show up.
Models.py
import arrow
import uuid
from django.db import models
from django_countries.fields import CountryField
from django.urls import reverse
from django.conf import settings
from properties.models import Property
class Tenant(models.Model):
id = models.UUIDField( # new
primary_key=True,
default=uuid.uuid4,
editable=False)
full_name = models.CharField("Full Name", max_length=255, null=True)
email = models.EmailField(unique=True, null=True)
phone = models.CharField(max_length=20, unique=True, null=True)
description = models.TextField("Description", blank=True)
country_of_origin = CountryField("Country of Origin", blank=True)
creator = models.ForeignKey(
settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL)
created_on = models.DateTimeField(
"Created on", auto_now_add=True, null=True)
is_active = models.BooleanField(default=False)
apartment = models.ForeignKey(
Property,
on_delete=models.CASCADE,
related_name='reviews',
)
rent_tenant = models.CharField(
"Rent he/she pays", max_length=10, blank=True)
def __str__(self):
return self.full_name
def get_absolute_url(self):
""""Return absolute URL to the Contact Detail page."""
return reverse('tenant_detail', kwargs={'pk': str(self.pk)})
urls.py
from django.urls import path
from .views import TenantListView, TenantDetailView
urlpatterns = [
path('', TenantListView.as_view(), name='tenant_list'),
path('<uuid:pk>', TenantDetailView.as_view(), name='tenant_detail'), # new
]
views.py
from django.views.generic import ListView, DetailView
from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin # new
from .models import Tenant
class TenantListView(LoginRequiredMixin, ListView): # new
model = Tenant
context_object_name = 'tenant_list'
template_name = 'tenants/tenant_list.html'
login_url = 'account_login' # new
class TenantDetailView(LoginRequiredMixin, PermissionRequiredMixin, DetailView): # new
model = Tenant
context_object_name = 'tenant'
template_name = 'tenants/tenant_detail.html'
login_url = 'account_login' # new
permission_required = 'books.special_status' # new
and here is the html template section where I need it to be rendered.
<li class="list-group-item">
{% if tenant.full_name %}
<b>Layout</b> <a class="float-right">{{ tenant.full_name }}</a>
{% endif %}
</li>
<li class="list-group-item">
{% if property.usable_sqm %}
<b>SQM</b> <a class="float-right">{{ property.usable_sqm }}</a>
{% endif %}
</li>
The other app is EXACTLY the same. Basically I copy-pasted everything from there and then just changed the fileds and renamed all the fields from Property to Tenant (By that I mean all the functions and urls ... ) What seems to be the problem? Because by my logic this should work.
The views.py document you have provided doesn’t have property_details.html template, instead it has tenant templates( you trying to render tenant objects into property template right?). I am not sure how you trying passing tenant model to property template from the code provided.
Why don’t you import tenant model into property views and pass whatever tenant objects you want to the property template?
I've issue related with displaying image from Model.I have caption instead of picture. I don't know what is the cause of that .
from django.db import models
class Games(models.Model):
name = models.CharField(max_length=250)
platform = models.CharField(max_length=500)
genre = models.CharField(max_length=100)
language = models.CharField(max_length=100)
image = models.ImageField(upload_to='Images_game',default='' )
# def __str__ (self):
# return self.Name
class Game_detail(models.Model):
game = models.ForeignKey(Games,on_delete=models.CASCADE)
subcryption = models.TextField()
publisher = models.CharField(max_length=250)
date_of_publish = models.DateField()
class Order(models.Model):
person_name = models.CharField(max_length=24)
person_surname = models.CharField(max_length=24)
street = models.CharField(max_length=45)
city= models.CharField(max_length=45)
views.py
from django.shortcuts import render
from .models import Games,Game_detail,Order
from django.shortcuts import render,get_object_or_404,redirect
from django.views.generic import ListView,DetailView,CreateView
class IndexView(ListView):
template_name ='games/list.html'
context_object_name = 'all_games'
model = Games
def get_queryset(self):
return Games.objects.all()
class Item_Detail (DetailView):
context_object_name = 'object'
template_name ='games/detail.html'
model = Games # tu jest wazna zmiana
def get_context_data(self, **kwargs):
context = super(DetailView,self).get_context_data(**kwargs)
context['Game_detail']=Game_detail.objects.all()
return context
class Create_order (CreateView):
template_name ='games/create.html'
model= Order
fields = ['person_name','person_surname','street','city']
settings.py
from django.conf.urls import include,url
from django.conf.urls import url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^games/',include("games.urls")),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
list.html template
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
{% for obj in all_games%}
<a href ='{%url "detail" pk=obj.pk%}'>{{obj.name}}</a>
{{obj.image}}
{{obj.platform}}
{{obj.genre}}
{{obj.language}}
{% endfor %}
</body>
</html>
I think it would be problem with right track to the picture . I added the picture in database and image upload to folder
You will need to specify in your template
<img src="{{obj.image.url}}" />.
You are storing the upload path in the database, so in the src you can have the obj.image entered and should be able to see the image just fine.
I have a project where I wish to upload an image with the Django auto generated class-based views, and it works on the admin side, but I don't know what I'm missing to make it work from an HTML page. I've searched the web with a little luck or not enough clarification.
So maybe someone can tell me what I'm missing. Here is my code:
settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'project/app/media_cdn')
models.py
from django.db import models
from django.core.urlresolvers import reverse
class Article(models.Model):
title = models.CharField(max_length = 200)
...
thumbnail = models.FileField(null = True, blank = True)
...
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('articles_detail', kwargs={'pk': self.pk})
class Meta:
ordering = ['-pk']
views.py
from django.shortcuts import render
from app.models import Article
from django.views.generic import *
from django.core.urlresolvers import reverse_lazy
from django.contrib.auth.mixins import LoginRequiredMixin
# Create your views here.
def index(request):
return render(request, 'index.html')
class ArticleList(ListView):
model = Article
class ArticleDetail(DetailView):
model = Article
class ArticleCreate(LoginRequiredMixin, CreateView):
model = Article
fields = ['title', 'description', 'abstract', 'thumbnail', 'author', 'category', 'publishDate']
class ArticleUpdate(LoginRequiredMixin, UpdateView):
model = Article
fields = ['title', ..., 'thumbnail', ...]
class ArticleDelete(LoginRequiredMixin, DeleteView):
model = Article
success_url = reverse_lazy('articles_list')
urls.py
from django.conf.urls import url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from app import views, auth
urlpatterns = [
url(r'^admin/',admin.site.urls),
...
url(r'^articles/(?P<pk>[0-9]+)/$', views.ArticleDetail.as_view(), name = 'articles_detail'),
url(r'^articles/create/$', views.ArticleCreate.as_view(), name = 'articles_create'),
url(r'^articles/update/(?P<pk>[0-9]+)/$', views.ArticleUpdate.as_view(), name = 'articles_update'),
url(r'^articles/delete/(?P<pk>[0-9]+)/$', views.ArticleDelete.as_view(), name = 'articles_delete'),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
article_form.html
{% extends 'layout.html' %}
{% block content %}
<form method="post" action="" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
{% endblock %}
As much as I was able to gather, I managed to follow all the steps but I still can't get the thumbnail to update when uploading from articles/create/ and articles/update/.../
Thanks in advance.