How to display Django model content into html template? - python

I have a problem with displaying content from Model in Django. I was created example model with one field which is "title"
class Post(models.Model):
title = models.CharField(max_length=100)
def __str__(self):
return self.title
Then I am trying to create function in views.py which allow me to get objects from this field created in Django admin field, like this:
def post_title(request):
title = Post.objects.all()
context = {'titles': title}
return render(request, 'home.html', context)
And I am trying to display it in html file using template:
{% extends "base.html" %}
{% block content %}
<div class="container">
<div class="row">
<p>{{ titles.title }}</p>
<div class="row">
<div class="col col-sm-3">col 2</div>
<div class="col col-sm-3">col 2</div>
<div class="col col-sm-3">col 2</div>
<div class="col col-sm-3">col 2</div>
</div>
<div class="row">
<div class="col col-sm-3">col 3</div>
<div class="col col-sm-3">col 3</div>
<div class="col col-sm-3">col 3</div>
<div class="col col-sm-3">col 3</div>
</div>
</div>
{% endblock %}
I would like to achieve displaying single string containt name of title in html.

When you use all() it returns a QuerySets which is a list. You need to iterate through it and display.
{% for title in titles %}
<p> {{ title }} </p>
{% endfor %}
So the above for loop is going to iterate through all your elements in the query.

Related

Django double curly braces tag not loading in html templates

I am new here so I may have worded the title wrong I apologize if I did so.
So I created a checkout page in my django project for the user to purchase coins but it wont render the variable attribute on the browser it just shows up empty.
Here's the coinpack model.py code.
`
class Coinpack (models.Model):
amount= models.CharField(max_length=50)
price= models.FloatField()
image_url= models.CharField(max_length=3000)
`
Here's the coinpack views.py code.
`
def buycoins (request):
buycoins = Coinpack.objects.all
return render(request, 'buycoins.html', {'buycoins': buycoins})
`
Here's the html template code
`
{% extends 'base.html' %}
{% block content %}
<div class="row">
{% for Coinpack in buycoins %}
<div class="col">
<div class="card" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">{{ Coinpack.amount }} coins</h5>
<p class="card-text"> ${{ Coinpack.price}}</p>
Buy Now
</div>
</div>
</div>
{% endfor %}
</div>
{% endblock %}
`
After this the coipack page works well
but when I add the checkout page the attributes are not rendered, here's what I did.
checkout page views.py
`
def checkout(request, pk):
checkout = Coinpack.objects.get(id=pk)
context = {'checkout':checkout}
return render(request, 'checkout.html', context)
`
checkout page url.py
`
path('checkout/<int:pk>/', views.checkout, name="checkout"),
`
checkout page html template
`
<body>
<div class="container">
<div class="row">
<div class="col-lg">
<br>
<img src="{{Coinpack.image_url}}">
</div>
<div class="col-lg">
<br>
<div class="card card-body">
<h3> {{coinpack.amount}} </h3>
<hr>
<h4>Total: $ {{Coinpack.price}} </h4>
<hr>
</div
</div>
</div>
</div>
</body>
`
This is the result in the browser
So I have no idea why it ends up empty pls help, thank you.
You used the different variables in the template. Try this,
<body>
<div class="container">
<div class="row">
<div class="col-lg">
<br>
<img src="{{checkout.image_url}}">
</div>
<div class="col-lg">
<br>
<div class="card card-body">
<h3> {{checkout.amount}} </h3>
<hr>
<h4>Total: $ {{checkout.price}} </h4>
<hr>
</div
</div>
</div>
</div>
</body>

Can not save form with CreateView (Django, Python)

I am trying to save data that fill out with form to database but it doesn't work as well. when i click on Submit button nothing change, the webpage just refresh!
These are my codes.
Views.py
class HotelAdCreate(AuthorsAccessMixin,CreateView):
model = HotelBookingAd
form_class = HotelBookingAdForm
template_name = "account/article-create-update.html"
def form_valid(self,form):
form.save()
return super(HotelAdCreate).form_valid(form)
Forms.py
class HotelBookingAdForm(forms.ModelForm):
class Meta:
model = HotelBookingAd
fields = '__all__'
def clean_sales_price(self):
sales_price = self.cleaned_data["sales_price"]
purchase_price = self.cleaned_data["purchase_price"]
if sales_price > purchase_price:
raise forms.ValidationError("error.")
print("error")
return sales_price
Edit :
i just added template file codes to debaug clearly.
Template File
{% extends 'account/base.html' %}
{% load crispy_forms_tags %}
{% block title %}{% endblock %}
{% block title-meta %} آگهی{% endblock %}
{% block main %}
<div class="col-md-12">
<div class="card card-primary">
<div class="card-header">
<h3 class="card-title- mb-0">ایجاد آگهی </h3>
</div>
<div class="card-body">
<form method="post" enctype="multipart/form-data">{% csrf_token %}
<div class="row">
<div class="col-6">
{{form.title|as_crispy_field}}
</div>
<div class="col-6">
{{form.hotel_name|as_crispy_field}}
</div>
<div class="col-12">
{{form.sale_reason|as_crispy_field}}
</div>
<div class="col-6">
{{form.check_in_date|as_crispy_field}}
</div>
<div class="col-6">
{{form.check_out_date|as_crispy_field}}
</div>
<div class="col-6">
{{form.purchase_price|as_crispy_field}}
</div>
<div class="col-6">
{{form.sales_price|as_crispy_field}}
</div>
<div class="col-6">
{{form.city_name|as_crispy_field}}
</div>
<div class="col-6">
{{form.room_type|as_crispy_field}}
</div>
<div class="col-6">
{{form.confirm|as_crispy_field}}
</div>
{% if user.is_superuser %}
<div class="col-6">
{{form.slug_generator|as_crispy_field}}
</div>
{% endif %}
</div>
<button class="btn btn-success">ارسال مقاله</button>
{% if user.is_superuser and request.resolver_match.kwargs.pk %}
<a class="btn btn-danger "href="{% url 'account:hotelad-delete' request.resolver_match.kwargs.pk %}">
حذف مقاله
</a>
<a target="_blank" class="btn btn-dark "href="{% url 'primary:preview' request.resolver_match.kwargs.pk %}">
پیش نمایش
</a>
{% endif %}
</form>
</div>
</div>
</div>
{% endblock %}
I've tried different options, but I don't have enough skills to handle this problem.
Can anyone help me?
UPDATE (FIXED)
I found problem by my self, here it is :
As you see in forms.py, i am using __all__ for fields but in template i am not using all the fields, so form will not be valid.
To fix the bug completely i just added Exclude option and added the fields that i didn't use in template. finally everything works fine :)

reduce line of code while fetching data from object to object?

I am creating a printing ordering service website in Django and I am stuck on the order page.
I have three tables named "product" ,"size", and "sizeProductMap" table.
views.py
products = Product.objects.get(prod_ID=id)
print(products.prod_Name)
sizesmap = SizeProductMapping.objects.filter(prod_id=id)
sizeslist = []
for data in sizesmap:
sizes = data.size_id
sizeslist.append(sizes.prod_size) # Here I am getting all the sizes I needed.
print(sizes.prod_size)
return render(request, "GalaxyOffset/product.html", {'products': products, 'sizeslist': sizeslist})
product.html
{% extends 'GalaxyOffset\basic.html' %}
{% block title%}Products{% endblock %}
{% block body%}
<div class="card my-2 mx-0 auto">
<div class="mx-4 my-2">
<h1>{{ products.prod_Name }}</h1>
</div>
<div class="row">
<div class="col-3">
<img class="border border-secondary my-4 mx-4" height="200"
src="{{products.prod_img.url}}"
width="200"/>
</div>
<div class="col-8 my-4">
<p> {{products.prod_Desc}}</p>
</div>
<div class="dropdown-divider"></div>
</div>
</div>
<div class="row">
<div class="col-4">
<div class="card mx-2 my-2 border border-secondary">
<div class="mx-2 mt-4">
{% for category in categories %}
<a id="{{ category.prod_ID }}" class="dropdown-item" href="{% url 'product' category.prod_ID%}">
{{ category.prod_ID }}. {{ category.prod_Name }}</a>
<div class="dropdown-divider"></div>
{% endfor %}
</div>
</div>
</div>
<div class="col-8">
<div class="card mx-2 my-2">
<div class="my-2">
<!-- How can I reduce Number of Line of code here. -->
{% for s in sizeslist %}
<input type="radio" name="sizes">{{s}}
</br>
{% endfor %}
</div>
</div>
</div>
</div>
{% endblock %}
Can you help me here to reduce the Numer of Lines in my views.py for fetching sizes and displaying in product.html?
You can use a list comprehension here.
sizesmap = SizeProductMapping.objects.filter(prod_id=id)
sizeslist = [data.size_id.prod_size for data in sizesmap]
or use .values()
Ex:
sizeslist = SizeProductMapping.objects.filter(prod_id=id).values('size_id__prod_size')

Django - External URL Link

I am new to Python and Django, and I have just created a website.
Basically I would like to have a page on the website that displays our company partners.
I have created an app 'partners' and in the model, I have 'website' as one of the fields.
On the partners html file, I have a button that users can click and this will take them to the partner's website in a new tab.
I tried to link the website in the following way:
{{ partner.website }}
However this ends up like:
www.mydomain.com/partners/www.partnerwebsite.com
I just want the partner website (www.partnerwebsite.com) to open in a new tab.
Any help appreciated. If there is already another post on this, please redirect me.
views.py
from django.shortcuts import render, redirect
from .models import Partner
def index(request):
partners = Partner.objects.order_by('-date_added').filter(is_published=True)
context = {
'partners': partners,
}
return render(request, 'partners/partners.html', context)
models.py
from django.db import models
from datetime import datetime
class Partner(models.Model):
name = models.CharField(max_length=200)
description = models.TextField()
website = models.CharField(max_length=100)
email = models.CharField(max_length=200)
contact_person = models.CharField(max_length=200)
phone = models.CharField(max_length=100)
mobile = models.CharField(max_length=100)
address = models.CharField(max_length=200)
photo_main = models.ImageField(upload_to='photos/partners/%Y/%m/%d/')
promo_code = models.CharField(max_length=20, blank=True)
is_published = models.BooleanField(default=True)
date_added = models.DateTimeField(default=datetime.now, blank=True)
def __str__(self):
return self.name
partners.html
{% extends 'base.html' %}
{% block title %} | Partners {% endblock %}
{% block content %}
<section id="showcase-inner" class="py-5 text-white">
<div class="container">
<div class="row text-center">
<div class="col-md-12">
<h1 class="display-4">Partners</h1>
</div>
</div>
</div>
</section>
<!-- Breadcrumb -->
<section id="bc" class="mt-3">
<div class="container">
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item">
<a href="{% url 'index' %}">
<i class="fas fa-home"></i> Home</a>
</li>
<li class="breadcrumb-item active"> Partners</li>
</ol>
</nav>
</div>
</section>
<!-- Partners -->
<section id="partners" class="py-4">
<div class="container">
<div class="row">
{% if partners %}
{% for partner in partners %}
<!-- Partner 1 -->
<div class="col-md-6 col-lg-6 mb-4">
<div class="card listing-preview">
<img class="card-img-top-project" src="{{ partner.photo_main.url }}" alt="">
<div class="card-body">
<div class="listing-heading text-center">
<h4 class="text-primary">{{ partner.name | title }}</h4>
<p><i class="fas fa-map-marker text-secondary"></i>   {{ partner.address }}</p>
</div>
<hr>
<div class="row py-2 text-secondary">
<div class="col-12 text-center">
{{ partner.description }}
</div>
</div>
{% if partner.promo_code %}
<hr>
<div class="row py-2 text">
<div class="col-12 text-center">
Use the following code to obtain 10% discount: {{ partner.promo_code }}
</div>
</div>
{% endif %}
<div class="container">
<hr>
<button class="btn btn-secondary btn-block">Visit Website</button>
</div>
</div>
</div>
</div>
{% endfor %}
{% else %}
<div class="container">
<p><h5 class="text-center">No Partners Available</h5></p>
</div>
{% endif %}
</div>
</div>
</section>
{% endblock %}
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('',views.index, name='partners'),
]
I was able to deduce the below solution from your views file. Add the below code in your template "partners.html"
{% for value in partners %}
<button>my button </button>
{% endfor%}

I want to create a website where users will be posting to the site, How would I make each post appear in a separate card?

Am creating a website where user will be posting information in the site, but when I post in the site, all post appear in a single card while I want each post to appear in a separate card, How would I do this?? would I have to use Javascript in the front end or python in the back end to accomplish this, and how?
Am using python 3.6.8, and django 2.1.8, I have written a code but all post appear in single materialize card
views
def homepage(request):
return render(request=request,
template_name="main/home.html",
context={"documents":Documents.objects.all}
models
class Documents(models.Model):
docs_name = models.CharField(max_length=200)
police_station = models.CharField(max_length=200)
docs_details = models.TextField()
docs_pic = models.ImageField()
def __str__(self):
return self.docs_name
Home template
{% extends 'main/base.html' %}
{% block content %}
<a class="waves-effect waves-light btn" href="">button</a>
<div class="row">
<div class="col s12 m9" >
<div class="card">
<div class="card-image">
{% for Doc in documents %}
<p>{{Doc.docs_name}}</p>
<p>{{Doc.police_station}}</p>
<p>{{Doc.docs_details}}</p>
<p>{{Doc.docs_pic}}</p>
{% endfor %}
</div>
</div>
</div>
</div>
{% endblock %}
Try:
{% extends 'main/base.html' %}
{% block content %}
<a class="waves-effect waves-light btn" href="">button</a>
<div class="row">
<div class="col s12 m9" >
{% for Doc in documents %}
<div class="card">
<div class="card-image">
<p>{{Doc.docs_name}}</p>
<p>{{Doc.police_station}}</p>
<p>{{Doc.docs_details}}</p>
<p>{{Doc.docs_pic}}</p>
</div>
</div>
{% endfor %}
</div>
</div>
{% endblock %}
You can achieve what you desire by simply adding the looping construct outside the <div class="card"> like this :
{% extends 'main/base.html' %}
{% block content %}
<a class="waves-effect waves-light btn" href="">button</a>
<div class="row">
<div class="col s12 m9" >
{% for Doc in documents %}
<div class="card">
<div class="card-image">
<p>{{Doc.docs_name}}</p>
<p>{{Doc.police_station}}</p>
<p>{{Doc.docs_details}}</p>
<p>{{Doc.docs_pic}}</p>
</div>
</div>
{% endfor %}
</div>
</div>
{% endblock %}
This way your card section alone repeats multiple times.
Earlier since the loop was within the card you got all the items within the same card.

Categories

Resources