why my added layers are not displayed by leaflet.ajax.js - django

I am developing a web map app using django, leaflet and postgis. My web app could display the OSM (openstreetmap) as background map but my added layer (from QGIS) and point data model (constructed in geodjango) could not be displayed in the web app. please give me a help. [Ofcourse I can see the text format (as json) in my added layer as follows:
https://i.stack.imgur.com/qYnWe.jpg
The code of index.html:
<!DOCTYPE html>
<html>
{% load static %}
{% load leaflet_tags %}
<head>
{% leaflet_js %}
{% leaflet_css %}
<title>Service Maps for Tourism</title>
<style type="text/css">
#gis {width: 80%; height: 800px;}
</style>
<script type="text/javascript" src= "{% static 'dist/leaflet.ajax.js' %}"> </script>
</head>
<body>
<h1> سامانه نقشه گردشگری</h1>
<br/>
<script type="text/javascript">
function our_layers(map,options){
var datasets = new L.GeoJSON.AJAX("{% url 'name' %}",{
});
datasets.addTo(map);
}
</script>
{% leaflet_map "gis" callback="window.our_Layers" %}
</body>
</html>
The views.py is as follows:
from django.shortcuts import render
from django.views.generic import TemplateView
from django.core.serializers import serialize
from django.http import HttpResponse
from .models import Provinces
# Create your views here.
class HomePageView(TemplateView):
template_name= 'index.html'
def province_dataSets (request):
provinces= serialize('geojson', Provinces.objects.all())
return HttpResponse(provinces, content_type= 'json')
The models.py is as follows:
from __future__ import unicode_literals
from django.db import models
from django.contrib.gis.db import models
from django.db.models import Manager
# Create your models here.
class TourismPoints(models.Model):
name= models.CharField(max_length= 50)
location= models.PointField(srid= 4326)
objects= models.Manager()
def __unicode__(self):
return self.name
class Meta:
verbose_name_plural= "Tourism points"
class Provinces(models.Model):
name = models.CharField(max_length=50)
english_name = models.CharField(max_length=40)
geom = models.MultiPolygonField(srid=4326)
def __unicode__(self):
return self.name
class Meta:
verbose_name_plural= "Provinces"
The urls.py is as follows:
from django.conf.urls import include, url
from .views import HomePageView, province_dataSets
from django.urls import path
urlpatterns = [
path ('', HomePageView.as_view (), name='home'),
path('province_data/', province_dataSets, name='name'),]

I used version 2.7 of Django and fortunately the added layers could be displayed

Related

Page not foung 404 error - Slug id not displaying (found) : http://127.0.0.1:8000/postscommentapp/6/how-learn-anything-very-easily

Sir, I'm developing a slug project in Django. When I try to print the slug id post it will not display shows 404 error. Tried n number of times. Anyone, please help me to fix this in urls.py.
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/postscommentapp/6/how-learn-anything-very-easily
Using the URLconf defined in postscommentpro.urls, Django tried these URL patterns, in this order:
admin/
postscommentapp/(?P\d+)/(?P[\w-]+)/$ [name='post_detail']
The current path, postscommentapp/6/how-learn-anything-very-easily, didn't match any of these.
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Post(models.Model):
STATUS_CHOICES = (
('draft', 'draft'),
('published', 'published')
)
title = models.CharField(max_length=50)
slug = models.CharField(max_length=50)
author = models.ForeignKey(User, on_delete = models.CASCADE)
body = models.TextField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='draft')
def __str__(self):
return self.title
admin.py
from django.contrib import admin
from .models import Post
# Register your models here.
class AdminPost(admin.ModelAdmin):
list_display = ['title', 'slug', 'body', 'author', 'created', 'updated', 'status']
prepopulated_fields = {'slug':('title',)}
list_editable = ('status',)
admin.site.register(Post, AdminPost)
views.py
from django.shortcuts import render
from .models import Post
# Create your views here.
def post_List(request):
posts = Post.objects.all()
return render(request, 'postscommentapp/post_list.html', {'posts':posts})
def post_detail(request, id, slug):
post = Post.objects.get(id=id)
return render(request, 'postscommentapp/post_detail.html', {'post':post})
url.py - postscommentapp
from django.urls import path
from postscommentapp import views
urlpatterns = [
path('', views.post_List, name=''),
path('postscommentapp/(?P<id>\d+)/(?P<slug>[\w-]+)/$', views.post_detail, name='post_detail'),
]
urls.py
"""postscommentpro URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('postscommentapp.urls')),
]
post_detail.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h2>{{ post.title }}</h2>
</body>
</html>
post_list.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<!-- Bootstrap CDN Lines -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght#600;700&display=swap" rel="stylesheet">
</head>
<style>
.col-md-6{
text-align: justify;
}
.img-thumbnail{
border:1px solid #6b6b47;
}
.title{
font-family: 'Poppins', sans-serif;
}
</style>
<body style="font-family: 'Poppins', sans-serif;">
<div class="container-fluid">
<br>
<h2 class="text-center" style="font-weight:bold; color: #0040ff;">Post Comments Python/Django Project:</h2>
<div class="row">
{% for each_item in posts %}
<div class="col-md-6">
<br>
<div class="img-thumbnail">
⭐ {{ each_item.title }}<small style="float:right">{{ each_item.created }}</small><br>
➟ Author: {{ each_item.author }}<br><br>
{{ each_item.body }}<br>
</div>
<br>
</div>
{% endfor %}
</div>
</div>
</body>
</html>
I solved this error in my own way. In urls.py postscommentapp
from django.urls import path
from postscommentapp import views
urlpatterns = [
path('', views.post_List, name=''),
path('postscommentapp/(?P<id>\d+)/(?P<slug>[\w-]+)/$', views.post_detail, name='post_detail'),
]
change this url code in to this urls.py - postscommentapp
from django.urls import path
from postscommentapp import views
urlpatterns = [
path('', views.post_List, name=''),
path('post/<int:id>/<slug:slug>/', views.post_detail, name='post_detail'),
]
Write this line in views.py
from django.shortcuts import render, get_object_or_404
from .models import Post
# Create your views here.
def post_List(request):
posts = Post.objects.all()
return render(request, 'postscommentapp/post_list.html', {'posts':posts})
def post_detail(request, id, slug):
# post = Post.objects.get(id=id)
post = get_object_or_404(Post, id=id, slug=slug)
return render(request, 'postscommentapp/post_detail.html', {'post':post})

django updateview not showing existing data to form

update is working but template form is not showing existing data. django updateview not showing existing data to form. when update page is showing only existing file is showing but object data is not showing. updateview cannot send existing data to form
view.py
from django.shortcuts import render, redirect
from django.core.files.storage import FileSystemStorage
from .forms import BookForm
from .models import Book
from django.views.generic import TemplateView, ListView, CreateView, UpdateView
from django.urls import reverse_lazy
class BookUpdate(UpdateView):
model = Book
form_class = BookForm
success_url = reverse_lazy('class_book_list')
template_name = 'updatebook.html'
model.py
from django.db import models
from django.urls import reverse
# Create your models here.
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
pdf = models.FileField(upload_to='books/pdfs/')
cover = models.ImageField(upload_to='books/covers/', null=True, blank=True)
def __str__(self):
return self.title
forms.py
from django import forms
from .models import Book
class BookForm(forms.ModelForm):
class Meta:
model = Book
fields = ('title', 'author', 'pdf', 'cover')
urls.py
from django.contrib import admin
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from . import views
urlpatterns = [
path('books/', views.book_list, name='book_list'),
path('books/upload/', views.upload_book, name='upload_book'),
path('books/<int:pk>/',views.delete_book, name='delete_book'),
path('class/books/',views.BookListView.as_view(), name='class_book_list'),
path('class/books/upload/',views.UploadBookView.as_view(), name='class_upload_book'),
path('class/books/update/<int:pk>/',views.BookUpdate.as_view(), name='class_update_book'),'''
updatebook.html
{% load crispy_forms_tags %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h2> Upload Book to Database</h2>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{form | crispy}}
<button type="submit" >Update</button>
</form>
</body>
</html>
html form cannot display existing data from database
please help
Make your method to GET i.e. (method="GET") in the form from where you are requesting the UpdateView page.

YearArchiveView.date_field is required. ImproperlyConfigured

I open up the documentation to Django.
I try to use the (YearArchiveView) view. when I go through the URL index/2020/ I get this error( YearArchiveView.date_field is required. ) what I understand that I have to use the attribute that called date_field and I already use.
so, how can I fix that error?
also, I need to know how can I access on this URL by any link into another page?, like from index.html
views.py
from django.shortcuts import get_object_or_404, Http404, render_to_response
from django.views.generic import ListView, DetailView
from .models import Article, User
from .forms import ContactForm
from django.views.generic.edit import FormView
from django.urls import reverse_lazy
from django.views.generic.dates import ArchiveIndexView, YearArchiveView
class ArticleYearArchiveView(YearArchiveView):
queryset = Article.objects.all()
template_name = 'index/article_archive_year.html'
date_field = "date"
allow_future = True
urls.py
from . import views
from django.urls import path
urlpatterns = [
path("<int:year>/", views.YearArchiveView.as_view(), name="article_archive_year")
]
artcile_archive_year.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Archive year</title>
</head>
<body>
{% for date in date_list %}
<li>{{ date|date }}</li>
{% endfor %}
</body>
</html>
You are not correctly referencing your view object.
Instead of:
urlpatterns = [path("<int:year>/", views.YearArchiveView.as_view(), name="article_archive_year")]
Try:
urlpatterns = [path("<int:year>/", views.ArticleYearArchiveView.as_view(), name="article_archive_year")]
Specifically, note the use of views.ArticleYearArchiveView instead of views.YearArchiveView.

NoReverseMatch at / in django

Hi Everyone i want to go on detail view but i get this error while paste the url
NoReverseMatch at /
Reverse for 'test' with no arguments not found. 1 pattern(s) tried: ['test/(?P<pk>[0-9]+)/$']
Here is my Models.py
from django.db import models
# Create your models here.
class article(models.Model):
Title = models.CharField(max_length=200)
Content = models.CharField(max_length=1000)
Here is my Views.py
from django.shortcuts import render
from django.views.generic import (ListView,DetailView)
from .models import *
# Create your views here.
class Article(ListView):
model = article
class Test(DetailView):
model = article
Here is my Urls.py
from django.contrib import admin
from django.urls import path
from cbs import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.Article.as_view(),name="Article"),
path('test/<int:pk>/', views.Test.as_view(),name="test"),
]
Here is my Article_list.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
{% for article in article_list %}
<h1>{{ article.Title }}</h1>
{% endfor %}
</body>
</html>
in your Article_list.html file you must change the href attribute on a tag to:
<h1>{{ article.Title }}</h1>
to send id as parameter to the below url:
path('test/<int:pk>/', views.Test.as_view(),name="test"),

Displaying django-recurrence in template

I've been banging my head about this for a week or so in my spare time, I currently have in my model
import recurrence.fields
.
.
.
course_recurring = recurrence.fields.RecurrenceField(null=True)
I can add recurrences and retrieve them in the admin console, but this in the template: {{ course.course_recurrence.rrules }} returns nothing.
I was suffering from the same problem, but I solved it.
Please try below steps:
1) Include {{form.media}} in your html head tag.
2) Please include the following before urlpatterns =[...]
-js_info_dict = {'packages': ('recurrence', ),}
3) Then add this url in the urls.py which includes your template:
-url(r'^jsi18n/$', django.views.i18n.javascript_catalog, js_info_dict)
Note: You need to import django library by including following line in your same urls.py file
-import django
This configuration works well for the new Django:
urls.py
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, include
from django.views.i18n import JavaScriptCatalog
urlpatterns = [
path('admin/', admin.site.urls),
# ...
path('jsi18n/', JavaScriptCatalog.as_view(packages=['recurrence']), name='javascript-catalog'),
]
# Connect static files
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
course_form.html
<html>
<head>
<script type="text/javascript" src="{% url 'javascript-catalog' %}">
</script>
</head>
<body>
<form method="post" class="post-form">
{% csrf_token %}
{{ form.media }}
{{ form }}
<button type="submit">Submit</button>
</form>
</body>
</html>
views.py
class CourseCreateView(CreateView):
model = Course
fields = ['title', 'price', 'recurrences']
success_url = reverse_lazy('course-list')
forms.py
from django import forms
from .models import Course
class CourseForm(forms.ModelForm):
class Meta:
model = Course
fields = ('title', 'price', 'recurrences', )
models.py
from django.db import models
from recurrence.fields import RecurrenceField
class Course(models.Model):
title = models.CharField(max_length=255)
price = models.PositiveSmallIntegerField()
recurrences = RecurrenceField()
def __str__(self):
return self.title
class Meta:
verbose_name = 'Course'
verbose_name_plural = 'Courses'