Django variable not visible in header section - python

I have a basic start to a blog, it lists out blog articles from the database in post_list.html that extends from header.html. I am trying also to get a variable in the header as a slogan but this is not working.
header.html - this renders without the "propaganda.slogan" which is entered from the admin pages and has content:
<!DOCTYPE html>
<html lang="en">
<head>
<title>hey!</title>
<meta charset="utf-8" />
{% load staticfiles %}
<link rel="stylesheet" href="{% static 'blog/css/bulma.css' %}" type="text/css"/>
</head>
<body>
<section class="hero is-success is-bold">
<div class="hero-body">
<div class="container">
{% block slogan %}
<ul>
{% for propaganda in propagandas %}
<li>{{ propaganda.slogan }}</li>
{% endfor %}
</ul>
{% endblock %}
<h1 class="title">
My weblog
</h1>
</div>
</div>
</section>
{% block content %}
{% endblock %}
</body>
</html>
post_list.html extends header.html and displays a list of posts from models.py:
{% extends "blog/header.html" %}
{% block content %}
{% for post in posts %}
<section class="section">
<div class="container">
<h1 class="title">{{ post.title }}</h1>
<p>{{ post.summary|linebreaksbr }}</p>
<p>published: {{ post.last_edited }}</p>
</div>
</section>
{% endfor %}
{% endblock %}
models.py looks like this:
from django.db import models
from django.utils import timezone
# Create your models here.
class Propaganda(models.Model):
slogan = models.CharField(max_length=140, blank=True, null=True)
def __str__(self):
return self.slogan
class Post(models.Model):
title = models.CharField(max_length=140, blank=False, null=False)
content = models.TextField()
summary = models.CharField(max_length=500)
created_date = models.DateTimeField()
last_edited = models.DateTimeField()
def __str__(self):
return self.title
finally, views.py is:
from django.shortcuts import render
from .models import Post, Propaganda
# Create your views here.
def post_list(request):
posts = Post.objects.all()
return render(request, 'blog/post_list.html', {'posts': posts})
def header(request):
propagandas = Propaganda.objects.all()
return render(request, 'blog/header.html', {'propagandas': propagandas})
So why can I get the list of post titles, summary and date in the post_list.html but I can't get a list of propagandist slogans in the header?
to me it looks like the same code, almost?
I get no error from the dev server or in the browser :(

You'll need to pass the list of propagnadas to the context of the current template; including a template has little or nothing to do with the associated (if this makes any sense in the first place) view of the included template:
def post_list(request):
posts = Post.objects.all()
propagandas = Propaganda.objects.all()
return render(request, 'blog/post_list.html', {'posts': posts, 'propagandas': propagandas})

Related

Load Django Objects Quicker

so I'm working on a Django news aggregator project. A main aspect of the project involves me fetching reddit and twitter posts through their respective APIs, saving the post data to a post model, then loading those model objects onto the page.
This is what I would prefer to do over fetching the data and displaying it directly through the response objects.
Right now, I have two separate timelines of reddit posts, and twitters posts, adjacent to each other on the page. Last time I loaded the page, it took a really long time. This is what the page looks like btw:
I was hoping someone could explain to me how I can get my page to load faster, and also how to integrate timeline/newsfeed functionality well. Lets say I have over 1500 post objects in my database, I don't want to load all 1500 on the page at one time. I'd like to load like the first 100, then if someone scrolls down the page enough, the next 100 become loaded, etc. Is there an easy/efficient way to go about this?
Thanks
EDIT 6/30/21
Here is my code:
views.py
from .models import Post
from news import services
from django.http import HttpResponse
from django.shortcuts import render, get_object_or_404
def mainpage(request):
all_posts=Post.objects.all()
context={'posts': all_posts}
return render(request, "mainpage.html", context)
models.py
from django.db import models
class Post(models.Model):
# Reddit, Twitter, Youtube
post_type = models.CharField(
max_length=20, null=True, blank=True)
root_url = models.CharField(max_length=200, default="")
html = models.TextField(default="")
created_at = models.DateTimeField(auto_now_add=True)
template
{% extends 'base.html' %} {% block content %} {% autoescape off %} {% load red_attempt %} {% load tweet_tags %}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
<div class="container">
<div class="row">
<div class="col-6">
<h3 class='text-center'>Twitter News</h3>
{% for post in posts %}
{% if post.post_type == 'Twitter' %}
<div class="mdl-card__media" id="timeline"></div>
{{ post.html }}
{% endif %}
<br>
{% endfor %}
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
</div>
<div class="col-6">
<h3 class='text-center'>Reddit News</h3>
{% for post in posts %}
{% if post.post_type == 'Reddit' %}
<div class="mdl-card__media" id="timeline"></div>
{{ post.html }}
{% endif %}
<br>
{% endfor %}
<script async src="//embed.redditmedia.com/widgets/platform.js" charset="UTF-8"></script>
</div>
</div>
</div>
{% endautoescape %}{% endblock %}
<script async src="//embed.redditmedia.com/widgets/platform.js" charset="UTF-8"></script>
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf" crossorigin="anonymous"></script>

Django: Problem with Separating the Two User Names

I am learning Django by building an application, called TravelBuddies. It will allow travelers to plan their trip and keep associated travel items (such as bookings, tickets, copy of passport, insurance information, etc), as well as create alerts for daily activities. The application will also able to update local information such as weather or daily news to the traveler. Travelers can also share the travel information with someone or have someone to collaborate with them to plan for the trip.
I am facing a problem. When I go to http://127.0.0.1:8000/triplist/, I see this page:
When I click on Trip Name: Kuala Lumpur and taken to activity.html through this link: http://127.0.0.1:8000/triplist/kuala-lumpur/:
"john" and "williams" are two separate user names. They need to be separated by a comma (,). So it will look like this: Co-traveller: john, williams. How can I do it?
Here are my codes in models.py:
from django.contrib.auth.models import User
from django.db import models
from django.template.defaultfilters import slugify
# Create your models here.
class Trip(models.Model):
trip_name = models.CharField(max_length=100)
date = models.DateField()
planner_name = models.CharField(max_length=100)
add_coplanner = models.ManyToManyField(User)
slug = models.SlugField(max_length=150, default='null')
def __str__(self):
return self.trip_name
def save(self, *args, **kwargs):
self.slug = slugify(self.trip_name)
super().save(*args, **kwargs)
class Activity(models.Model):
trip = models.ForeignKey(Trip, on_delete=models.CASCADE)
activity_name = models.CharField(max_length=100)
date = models.DateField(auto_now=True)
time = models.TimeField(auto_now= True)
location = models.CharField(max_length=100)
item_type = models.CharField(max_length=100)
item_number = models.CharField(max_length=100)
add_cotraveller = models.ManyToManyField(User)
slug = models.SlugField(max_length=150, default='null')
def __str__(self):
return self.activity_name
def save(self):
super(Activity, self).save()
self.slug = '%i-%s' % (
self.id, slugify(self.trip.trip_name)
)
super(Activity, self).save()
Here are my codes in views.py:
from django.views import generic
from .models import Trip, Activity
class TripListView(generic.ListView):
template_name = 'trips/triplist.html'
context_object_name = 'all_trips'
def get_queryset(self):
return Trip.objects.all()
class ActivityView(generic.DetailView):
model = Trip
template_name = 'trips/activity.html'
Here are my codes in urls.py:
from . import views
from django.urls import path
app_name = 'trips'
urlpatterns = [
path('triplist/', views.TripListView.as_view(), name='triplist'),
path('triplist/<slug:slug>/', views.ActivityView.as_view(), name='activity'),
]
Here are my codes in apps.py:
from django.apps import AppConfig
class TripsConfig(AppConfig):
name = 'trips'
Here are my codes in triplist.html:
<!DOCTYPE html>
{% extends 'trips/base.html' %}
{% load static %}
<html lang="en">
<link rel="stylesheet" type="text/css" href="{% static "css/style.css" %}">
<head>
<meta charset="UTF-8">
{% block title%}Trip list{% endblock %}
<title>Trip list</title>
</head>
<body>
{% block content %}
<!--Page content-->
<h1>This is Trip List Page</h1>
<ol>
{% for trip in all_trips %}
<ol>
<li>Trip name: {{ trip.trip_name }}</li>
Date: {{ trip.date }}<br>
Planner: {{ trip.planner_name }}<br>
Coplanners:
{% for user in trip.add_coplanner.all %}
{{user.username}}
{% endfor %}<br>
<!-- Co-planner: {{ trip.add_coplanner.all }}<br>-->
</ol>
{% endfor %}
</ol>
<img src="{% static "images/botanical-garden.jpg" %}" alt="Botanical Garden" />
<!-- New line -->
{% endblock %}
</body>
</html>
Here are my codes in activity.html:
{% extends 'trips/base.html' %}
{% block title%}
Detail
{% endblock %}
{% block content %}
<h3>Activities for {{trip.trip_name}} </h3>
{% for trip_item in trip.activity_set.all %}
<!--<p>Activity name: {{ trip_item.activity_name }}</p>-->
<ol>
<li>Activity name: {{ trip_item.activity_name }}</li>
Date: {{ trip_item.date }}<br>
Time: {{ trip_item.time }}<br>
Location: {{ trip_item.location }}<br>
Item Type: {{ trip_item.item_type }}<br>
Item No: {{ trip_item.item_number }}<br>
Co-traveller:
{% for user in trip_item.add_cotraveller.all %}
{{user.username}}
{% endfor %}<br>
<!-- Co-traveller: {{ trip_item.add_cotraveller.all }}-->
</ol>
{% endfor %}
{% endblock %}
Do I have to make any change in models.py?
Co-traveller:
{% for user in trip_item.add_cotraveller.all %}
{% if forloop.last %}
{{user.username}}
{% else %}
{{user.username}} ,
{% endif %}
{% endfor %}<br>
you can use this. do give a space after ,
You can separate user with comma like this:
Co-traveller:
{% for user in trip_item.add_cotraveller.all %}
{{user.username}}{% if not forloop.last %}, {% endif %}
{% endfor %}<br>
One more way is to create a instance method and return a string from your model.
For eg.
class Activity(models.Model):
#fields
add_cotraveller = models.ManyToManyField(User)
def __str__(self):
return self.activity_name
def get_cotravellers(self):
return ", ".join(u.username for u in self.add_coplanner.all())
and in template you can access it like:
Coplanners: {{ trip_item.get_cotravellers }}

Django: Getting NoReverseMatch Error While Attempting to Use Slug in URLs

I am a beginner learning Django through building an app, called PhoneReview. It will store reviews related to the latest mobile phone. It will also display phone brands, along with the associated phone models and their reviews.
I have already created models, views and the template files. Right now, I am facing a problem. While attempting to use slug, I am getting NoReverseMatch Error. It looks like this:
NoReverseMatch at /index
Reverse for 'modellist' with arguments '('',)' not found. 1 pattern(s) tried: ['phonemodel/(?P<slug>[-a-zA-Z0-9_]+)$']
However, I didn't face any problem with while using primary key in urls.py. The problem is occurring when I attempt to use slug in the URLs.
Here are my codes of models.py located inside PhoneReview folder:
from django.db import models
from django.template.defaultfilters import slugify
# Create your models here.
class Brand(models.Model):
brand_name = models.CharField(max_length=100)
origin = models.CharField(max_length=100)
manufacturing_since = models.CharField(max_length=100, null=True, blank=True)
slug = models.SlugField(max_length=150, null=True, blank=True)
def __str__(self):
return self.brand_name
def save(self, *args, **kwargs):
self.slug = slugify(self.brand_name)
super().save(*args, **kwargs)
class PhoneModel(models.Model):
brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
model_name = models.CharField(max_length=100)
launch_date = models.CharField(max_length=100)
platform = models.CharField(max_length=100)
slug = models.SlugField(max_length=150, null=True, blank=True)
def __str__(self):
return self.model_name
def save(self, *args, **kwargs):
self.slug = slugify(self.model_name)
super().save(*args, **kwargs)
class Review(models.Model):
phone_model = models.ManyToManyField(PhoneModel, related_name='reviews')
review_article = models.TextField()
date_published = models.DateField(auto_now=True)
slug = models.SlugField(max_length=150, null=True, blank=True)
link = models.TextField(max_length=150, null=True, blank=True)
def __str__(self):
return self.review_article
Here are my codes of urls.py located inside PhoneReview folder:
from . import views
from django.urls import path
app_name = 'PhoneReview'
urlpatterns = [
path('index', views.BrandListView.as_view(), name='brandlist'),
path('phonemodel/<slug:slug>', views.ModelView.as_view(), name='modellist'),
path('details/<slug:slug>', views.ReviewView.as_view(), name='details'),
]
Here are my codes of views.py located inside PhoneReview folder:
from django.shortcuts import render, get_object_or_404
from django.views import generic
from .models import Brand, PhoneModel, Review
class BrandListView(generic.ListView):
template_name = 'PhoneReview/index.html'
context_object_name = 'all_brands'
def get_queryset(self):
return Brand.objects.all()
class ModelView(generic.ListView):
template_name = 'PhoneReview/phonemodel.html'
context_object_name = 'all_model_name'
def get_queryset(self):
self.brand = get_object_or_404(Brand, slug=self.kwargs['slug'])
return PhoneModel.objects.filter(brand=self.brand)
class ReviewView(generic.DetailView):
model = Review
template_name = 'PhoneReview/details.html'
Here are my codes of apps.py located inside PhoneReview folder:
from django.apps import AppConfig
class PhonereviewConfig(AppConfig):
name = 'PhoneReview'
Here are my codes of index.html located inside templates folder:
{% extends 'PhoneReview/base.html' %}
{% load static %}
{% block title%}
Brand List
{% endblock %}
{% block content %}
<!--Page content-->
<h1>This is Brand List Page</h1>
<h2>Here is the list of the brands</h2>
<ul>
{% for brand in all_brands %}
<!-- <li>{{ brand.brand_name }}</li>-->
<li>{{ brand.brand_name }}</li>
{% endfor %}
</ul>
<img src="{% static "images/brandlist.jpg" %}" alt="Super Mario Odyssey" /> <!-- New line -->
{% endblock %}
Here are my codes of phonemodel.html located inside templates folder:
{% extends 'PhoneReview/base.html' %}
{% load static %}
{% block title%}
Phone Model Page
{% endblock %}
{% block content %}
<!--Page content-->
<h1>This is Phone Model Page</h1>
<h2>Here is the phone model</h2>
<ul>
{% for phonemodel in all_model_name %}
<li>{{ phonemodel.model_name }}</li>
{% endfor %}
</ul>
<img src="{% static "images/brandlist.jpg" %}" alt="Super Mario Odyssey" /> <!-- New line -->
{% endblock %}
Here are my codes of details.html located inside templates folder:
{% extends 'PhoneReview/base.html' %}
{% load static %}
<html>
<link rel="stylesheet" type="text/css" href="{% static "css/style.css" %}">
<html lang="en">
{% block title%}Details{% endblock %}
{% block content %}
<h1>This is the Details Page</h1>
<h2>Review:</h2>
<p>{{ review.review_article }}</p>
<h2>News Link:</h2>
<p>{{ review.link }}</p>
{% endblock %}
</html>
Am I doing anything wrong in index.html and phonemodel.html?
In your index.html instead of phonemodel.slug it should be brand.slug
{% for brand in all_brands %}
<!-- <li>{{ brand.brand_name }}</li>-->
<li>{{ brand.brand_name }}</li>
{% endfor %}
Same with your phonemodel.html
{% for phonemodel in all_model_name %}
<li>{{ phonemodel.model_name }}</li>
% endfor %}

How can I make two models appear on my Django homepage simultaneously?

I can't make my homepage show data from both my HomePage and IconBlurb models. I've been stucked on this problem for two days and couldn't figure it our. Please help me. Thanks.
This is my models.py
class HomePage(models.Model):
heading = models.CharField(max_length=200,
help_text="The heading under the icon blurbs")
subheading = models.CharField(max_length=200,
help_text="The subheading just below the heading")
introduction = models.TextField(help_text="首页的欢迎文字。")
introLink = models.URLField(max_length=200, blank=True)
class Meta:
verbose_name= _("Home page")
verbose_name_plural = _("Home pages")
This is my views.py
from django.shortcuts import get_object_or_404, render
from homepage.models import HomePage, IconBlurb
def index(request):
homepage = get_object_or_404(HomePage)
return render(request, 'homepage/index.html', {'homepage':homepage})
def blurb(request):
latest_iconblurb = IconBlurb.objects.all()
context = {'latest_iconblurb': latest_iconblurb}
return render(request, 'homepage/blurb.html', context)
This is my urls.py
from django.conf.urls import patterns, url
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
)
This is my index.html
{% extends "base.html" %}
{% block all_content %}
<div class="jumbotron">
<div class="container">
<h1>{{ homepage.heading }}</h1>
<p>{{ homepage.introduction }}</p>
<p><a class="btn btn-primary" href="/courses">开始学习</a></p>
</div>
</div>
<div class="container">
<div class="row">
{% block blurb %}{% endblock %}
</div>
</div>
{% endblock %}
This is my blurb.html
{% extends "homepage/index.html" %}
{% block blurb %}
{% if latest_iconblurb %}
{% for blurb in latest_iconblurb %}
<div class="col-md-4">
<h2>{{ blurb.title }}</h2>
<p>{{ blurb.content }}</p>
</div>
{% endfor %}
{% endif %}
{% endblock %}
This is simple. Write both function code in a single function.
def index(request):
homepage = get_object_or_404(HomePage)
latest_iconblurb = IconBlurb.objects.all()
context = {'latest_iconblurb': latest_iconblurb; 'homepage':homepage}
return render(request, 'homepage/blurb.html', context)

Django floppyforms OSMPointWidget does not display a map

I am trying to put an OSM-map, similar to the one in the geodjango-admin, into a form on my main site.
I decided to use floppyforms, set everything up like in the documentation and it seems to get recognized, but strangely the map does not appear. Firebug shows that there is just an empty <div id="id_coord_map"></div> instead of the map, but it has all the right dimensions. The debug-textbox and the "Delete all features"-link are there like they should be. But, when I open the site, Firebug does not show any javascript requests in the 'network'-tab, so maybe that is a hint.
I guess I missed something or something isn't correctly included, but I tried for hours and really don't know anymore. Amongst other things I set all the paths for static files and run manage.py collectstatic, I also tried to not use the generic edit views, but it came out the same.
Here are the relevant parts in the code:
#views.py
import floppyforms as forms
...
class OSMPointWidget(forms.gis.PointWidget, forms.gis.BaseOsmWidget):
pass
class LocationCreateView(CreateView):
model = Location
fields = ['name', 'zip', 'coord']
form_class = modelform_factory(Location,
widgets={"coord": forms.gis.PointWidget(attrs = {
'display_wkt': True,
'map_srid': 4326,
'map_width': 700,
'map_height': 500,})})
#models.py
class Location(models.Model):
name = models.CharField(max_length=200)
slug = models.SlugField(max_length=255, blank=True, default='', unique=True)
coord = models.PointField()
zip = models.CharField(max_length=5, default='12345')
objects = models.GeoManager()
def __unicode__(self):
return self.name
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.name)
super(Location, self).save(*args, **kwargs)
#urls.py
urlpatterns = patterns('',
...
url(r"location/$", views.LocationCreateView.as_view(),
name = "locationcreate"),
...
)
#location_form.html
{% extends "_layouts/base.html" %}
{% block page_title %}Enter Location | {% endblock %}
{% block page_content %}
<form action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
{% endblock %}
#base.html
<!doctype html>
<html>
<head>
<title>{% block page_title %}{% endblock %}Calendar</title>
<link rel="stylesheet" href="{{ STATIC_URL }}css/bootstrap.css">
<link rel="stylesheet" href="{{ STATIC_URL }}css/bootstrap-theme.css" >
</head>
<body>
<div class="container theme-showcase" role="main">
<div class="jumbotron">
<h1>EVENTCALENDAR</h1>
</div>
<div class="container">
{% block page_content %}{% endblock %}
</div>
</div>
</body>
</html>
I just had a similar issue and realised that I needed to include a {{ form.media }} tag in the header and then django-floppyforms supplies the relevant javascript files to make the map magically appear.
Somewhere in the head of base.html include a block for extra javascript
{% block extra_js %}{% endblock %}
Then fill in the block in your location_form.html
{% block extra_js %}
{{ form.media }}
{% endblock %}

Categories