Django floppyforms OSMPointWidget does not display a map - python

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

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 basic ModelForm not showing choices

Using Django tutorial, I built a basic ModelForm with choice fields:
One field (Shirt size) - is not showing choices
Second field - not showing at all
I can't find the reason, anywhere I checked it seems like I'm doing things right, but obviously I'm not.
Thank you.
The Result Form
views.py
def person(request):
if request.method == 'POST':
form = forms.PersonForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('/thanks/')
else:
form = forms.PersonForm()
return render(request, 'development/form_template.html', {'form': form})
forms.py
class PersonForm(ModelForm):
class Meta:
model = models.Person
fields = '__all__'
models.py
class Person(models.Model):
SHIRT_SIZES = (
('S', 'Small'),
('M', 'Medium'),
('L', 'Large'),
)
name = models.CharField(max_length=60, default='Anonymous', help_text='Type your name.')
shirt_size = models.CharField(max_length=1, choices=SHIRT_SIZES)
medal_type = models.TextChoices('MedalType', 'GOLD SILVER BRONZE')
form_template.html
{% extends 'development/development_template.html' %}
{% block content %}
<div class="container">
<form action="/your-name/" method="post">
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<input type="submit" value="Submit">
</form>
</div>
{% endblock content %}
CSS files I'm using
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.css" type="text/css" rel="stylesheet" media="screen,projection"/>
<link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<link type="text/css" rel="stylesheet" href="{% static 'css/style.css' %}">
The problem was 100% the support of Materializecss design in select - for some reason it's not supporting select anymore.
I used bootstrap4 to execute the form pages:
(1) install: pip install django-bootstrap4
(2) add to INSTALLED_APPS = [..., 'bootstrap4',]
(3) edit your HTML form
Here's html for example:
{% extends 'adolim/adolim_template.html' %}
{% block content %}
{% load bootstrap4 %}
{# Load CSS and JavaScript #}
{% bootstrap_css %}
{% bootstrap_javascript jquery='full' %}
{# Display django.contrib.messages as Bootstrap alerts #}
{% bootstrap_messages %}
<div class="container" style="width:100%;" dir="rtl">
<div class="col s3 right">
</div>
<div class="col s6 right" dir="rtl">
<div class="container">
<div class="row"><br></div>
<h4 class="right">{{ page_title }}</h4>
<div class="row"><br></div>
<form dir="rtl" action="{% url 'adolim:add_order' %}" method="post" >
{% csrf_token %}
{% bootstrap_form form %}
<div class="col center">
{% buttons %}
<button class="btn-large waves-effect waves-light blue darken-1" type="submit" name="action">{{ page_title }} למערכת
<i class="material-icons right">send</i>
</button>
{% endbuttons %}
</div>
</form>
</div>
</div>
</div>
{% endblock content %}

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 template language extends doesn't work

Hi guys I am studying django framework using "django by example" book. The problem I am facing is that the template language does not work even I copy and pasted source code from book and/or github.
A blog application that has post model and is inside the mysite project.
You can see the code in picture and the result too:
Inside blog\templates\blog .
blog\templates\blog\base.html
<!-- its base.html -->
{% load staticfiles %}
<!DOCTYPE HTML>
<html>
<head>
<title>{% block title %}{% endblock %}</title>
<link href="{% static "css/blog.css" %}" rel="stylesheet">
</head>
<body>
<div id="content">
{% block content %}
{% endblock %}
</div>
<div id="sidebar">
<h2>My blog</h2>
<p>This is my blog.</p>
</div>
</body>
</html>
Its the list that extends base.html and located in blog\template\blog\post:
{% extends "blog/base.html" %}
{% block title %}My Blog{% endblock %}
{% block content %}
<h1>My Blog</h1>
{% for post in posts %}
<h2>
<a href="{{ post.get_absolute_url }}">
{{ post.title }}
</a>
</h2>
<p class="date">
Published {{ post.publish }} by {{ post.author }}
</p>
{{ post.body|truncatewords:30|linebreaks }}
{% endfor %}
{% endblock %}
Here is views.py
from django.shortcuts import render, get_list_or_404
from .models import Post
def post_list(request):
posts=Post.published.all()
return render(request,'blog/post/list.html',{'posts':posts})
def post_detail(request, year, month, day, post):
post=get_list_or_404(Post, slug=post,
status='published',
publish__year=year,
publish__month=month,
publish__day=day)
return render(request,'blog/post/detail.html',
{'post':post})

Django variable not visible in header section

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

Categories