Django - External URL Link - python

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%}

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 :)

Product image loads on all products page, but not on individual product page (Django)

For a little bit of context, when you add a new product to my website, you are required to add an image as well. I can get the product images to load just fine when viewing the main products page, but when you try to view an individual product on a new product details page, the image won't load.
The product image is pulled in via the following code:
<div class="product" style="background-image: url('{{ MEDIA_URL }}{{ product.image }}')"></div>
Here is the HTML used on the main products page:
<div class="album">
<div class="container">
<div class="product-row">
{% for product in products %}
<div class="col-xl-4 col-md-6">
<div class="card mb-4 shadow-sm">
<div class="product" style="background-image: url('{{ MEDIA_URL }}{{ product.image }}')"></div>
<div class="product-card-body">
<p class="product-title">{{ product.name }}</p>
<p class="text-muted">{{ product.category }}</p>
<div class="d-flex justify-content-between align-items-center">
<div class="btn-group">
<form method="post" action="{% url 'add_to_cart' product.id %}">
{% csrf_token %}
<div class="text-center">
<span class="input-group-btn">
<button class="product-btns btn-success" type="submit">Add to Cart</button>
</span>
</div>
</form>
<form class="ml-2" method="post" action="{% url 'product_details' product.id %}">
{% csrf_token %}
<div class="text-center">
<span class="input-group-btn">
<button class="product-btns btn-info" type="submit">Find out more</button>
</span>
</div>
</form>
</div>
<p class="product-price">£{{ product.price }}</p>
</div>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
</div>
Here is the HTML used on the product details page:
<section class="container panel-body-forum-details">
<div class="row">
<div class="col-md-6">
<h3>{{ products.name }}</h3>
<hr>
<p>{{ products.description }}</p>
<br>
</div>
<div class="col-md-6">
<div class="product" style="background-image: url('{{ MEDIA_URL }}{{ product.image }}')"></div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<p><strong>Service Type:</strong> {{ products.category }} </p>
<p><strong>Price:</strong> £{{ products.price }} </p>
Back to Services
{% if request.user == products.prod_creator_id %}
Edit Service
{% endif %}
</div>
</div>
</section>
Here is the product model:
class Product(models.Model):
prod_creator_id = models.ForeignKey(User, null=False, default=1)
name = models.CharField(max_length=38, default='')
category = models.CharField(choices=CATEGORY_CHOICES, max_length=25, default='')
description = models.TextField()
price = models.DecimalField(max_digits=6, decimal_places=2, null=True)
image = models.ImageField(upload_to='images')
tags = models.ManyToManyField(Tag)
def __str__(self):
return self.name
Just an FYI, the product name, description, category and price all populate fine on the product details page. It's only the image that doesn't load.
Please let me know if you need anything else!
Thanks in advance.
It looks like a copy and paste error to me:
details page:
{{ products.name }}
but:
{{ product.image }}
I think it should be "products.image".

Getting error as NOReverseMatch in django?

I am a newbie in django learning django with a online course by creating a realestate project.In this project I am having listings app which shows some of the listings in the web page from the database But I am getting an error of Reverse for 'listing' with arguments '('',)' not found. 1 pattern(s) tried: ['listings/listings/$']
My listings urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='listings'),
url(r'^listings/<int:listing_id>$', views.listing, name='listing'),
url('search', views.search,name='search')
]
My listings views.py
from django.shortcuts import get_object_or_404, render
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from .models import Listing
def index(request):
listings = Listing.objects.order_by('-list_date').filter(is_published=True)
paginator = Paginator(listings, 6)
page = request.GET.get('page')
paged_listings = paginator.get_page(page)
context = {
'listings': paged_listings
}
return render(request, 'listings/listings.html', context)
def listing(request, listing_id):
listing = get_object_or_404(Listing, pk=listing_id)
context = {
'listing': listing
}
return render(request, 'listings/listing.html', context)
def search(request):
queryset_list = Listing.objects.order_by('-list_date')
# Keywords
if 'keywords' in request.GET:
keywords = request.GET['keywords']
if keywords:
queryset_list = queryset_list.filter(description__icontains=keywords)
# City
if 'city' in request.GET:
city = request.GET['city']
if city:
queryset_list = queryset_list.filter(city__iexact=city)
# State
if 'state' in request.GET:
state = request.GET['state']
if state:
queryset_list = queryset_list.filter(state__iexact=state)
# Bedrooms
if 'bedrooms' in request.GET:
bedrooms = request.GET['bedrooms']
if bedrooms:
queryset_list = queryset_list.filter(bedrooms__lte=bedrooms)
# Price
if 'price' in request.GET:
price = request.GET['price']
if price:
queryset_list = queryset_list.filter(price__lte=price)
context = {
'state_choices': state_choices,
'bedroom_choices': bedroom_choices,
'price_choices': price_choices,
'listings': queryset_list,
'values': request.GET
}
return render(request, 'listings/search.html', context)
My listings template
{% extends 'pages/base.html' %}
{% load humanize %}
{% block title %} | Browse Property Listings {% 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">Browse Our Properties</h1>
<p class="lead">Lorem ipsum dolor sit, amet consectetur adipisicing elit. Sunt, pariatur!</p>
</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"> Browse Listings</li>
</ol>
</nav>
</div>
</section>
<!-- Listings -->
<section id="listings" class="py-4">
<div class="container">
<div class="row">
{% if listings %}
{% for listing in listings %}
<div class="col-md-6 col-lg-4 mb-4">
<div class="card listing-preview">
<img class="card-img-top" src="{{ listing.photo_main.url }}" alt="">
<div class="card-img-overlay">
<h2>
<span class="badge badge-secondary text-white">${{ listing.price | intcomma }}</span>
</h2>
</div>
<div class="card-body">
<div class="listing-heading text-center">
<h4 class="text-primary">{{ listing.title }}</h4>
<p>
<i class="fas fa-map-marker text-secondary"></i> {{ listing.city }} {{ listing.state }}, {{ listing.zipcode }}</p>
</div>
<hr>
<div class="row py-2 text-secondary">
<div class="col-6">
<i class="fas fa-th-large"></i> Sqft: {{ listing.sqft }}</div>
<div class="col-6">
<i class="fas fa-car"></i> Garage: {{ listing.garage }}</div>
</div>
<div class="row py-2 text-secondary">
<div class="col-6">
<i class="fas fa-bed"></i> Bedrooms: {{ listing.bedrooms }}</div>
<div class="col-6">
<i class="fas fa-bath"></i> Bathrooms: {{ listing.bathrooms }}</div>
</div>
<hr>
<div class="row py-2 text-secondary">
<div class="col-12">
<i class="fas fa-user"></i> {{ listing.realtor }}</div>
</div>
<div class="row text-secondary pb-2">
<div class="col-6">
<i class="fas fa-clock"></i> {{ listing.list_date | timesince }}</div>
</div>
<hr>
More Info
</div>
</div>
</div>
{% endfor %}
{% else %}
<div class="col-md-12">
<p>No Listings Available</p>
</div>
{% endif %}
</div>
<div class="row">
<div class="col-md-12">
{% if listings.has_other_pages %}
<ul class="pagination">
{% if listings.has_previous %}
<li class="page-item">
«
</li>
{% else %}
<li class="page-item disabled">
<a class="page-link">«</a>
</li>
{% endif %}
{% for i in listings.paginator.page_range %}
{% if listings.number == i %}
<li class="page-item active">
<a class="page-link">{{i}}</a>
</li>
{% else %}
<li class="page-item">
{{i}}
</li>
{% endif %}
{% endfor %}
{% if listings.has_next %}
<li class="page-item">
»
</li>
{% else %}
<li class="page-item disabled">
<a class="page-link">»</a>
</li>
{% endif %}
</ul>
{% endif %}
</div>
</div>
</div>
</section>
{% endblock %}
You are using django 3, and url patterns from django 1. Try this:
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='listings'),
path('listings/<int:listing_id>', views.listing, name='listing'),
path('search', views.search, name='search')
]
in template
More Info
If you are using a Django version 2+, you could use path instead:
path('listings/<int:listing_id>/', views.listing, name='listing'),
If your using lower django version than 2
url(r'^listings/(?P<listing_id>[0-9]+)/$', views.listing, name='listing'),
Now in the template
<a href="{% url 'listing' listing.pk %}">

How to display Django model content into html template?

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.

Categories

Resources