Retrieve polygon from Django postgis database and display it to the browser - python

I tried to retrieve the polygon which I saved into postgis database. (all polygons)
Here is my code:
models.py
from django.contrib.gis.db import models
class MyMap(models.Model):
name = models.CharField(max_length=50, blank=True, null=True)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
geom = models.GeometryCollectionField(srid=4326, null=True)
objects = models.GeoManager()
def __unicode__(self):
return self.name
forms.py
from django.contrib.gis import forms
from .models import MyMap
class MyMapForm(forms.ModelForm):
class Meta:
model = MyMap
fields = ['geom']
views.py
from django.shortcuts import render
from django.http import HttpResponse
from .forms import MyMapForm
from .models import MyMap
def map(request):
map_info = MyMap.objects.all()
map_data = {
"map_detail": map_info
}
return render(request, 'mymap.html', map_data)
def ajax(request):
if request.POST.has_key('geom'):
form = MyMapForm(request.POST or None)
...
mymap.html
<form action="" method="POST">
{%csrf_token%}
<div id="map_canvas"></div> // I use google map api
</form>
<div>
{% for details in map_detail %}
{{detail.geom}}
{% endfor %}
</div>
I don't know where is my problem which I can not show the polygons in the html file !
EDIT#1
EDIT#2

Related

How can I solve ValueError in django. Exception Value: ModelForm has no model class specified

This is my code:
django.models. my model.py file
from django.db import models
class Product(models.Model):title = models.CharField(max_length=150)
description = models.TextField(blank=True, null=True)
price = models.DecimalField(decimal_places=2, max_digits=100000)
summary = models.TextField(blank=True, null=False)
featured = models.BooleanField(default=False)
forms.py That's my full form.py file
from django import forms
from .models import Product
class ProductForm(forms.ModelForm):
class Meta:
model = Product
fields = [
'title',
'description',
'price',
]
class RawProductForm(forms.ModelForm):
title = forms.CharField()
description = forms.CharField()
price = forms.DecimalField()
django.views my django.views file
from django.shortcuts import render
from .models import Product
from .forms import ProductForm, RawProductForm
def product_create_view(request):
my_form = RawProductForm()
if request.method == 'POST':
my_form = RawProductForm(request.POST)
if my_form.is_valid():
print(my_form.cleaned_data)
Product.objects.create(**my_form.cleaned_data)
else:
print(my_form.errors)
context = {'form': my_form}
return render(request, "products/product_create.html", context)
products_create.html this is my html file
{% extends 'base.html' %}
{% block content %}
<form action="." method="POST">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Save" />
</form>
{% endblock %}
In his code I'm trying to make a form but when I run python manage.py runserver at http://127.0.0.1:8000/create/ I'm getting ValueError
This is a screenshot of my full error messagae
You need to specify your model class in your form :
class RawProductForm(forms.ModelForm):
class Meta:
model = Product
fields = ["price","description" ,"title"]
view :
def product_create_view(request):
my_form = RawProductForm()
if request.method == 'POST':
my_form = RawProductForm(request.POST)
if my_form.is_valid():
print(my_form.cleaned_data)
Product.objects.create(**my_form.cleaned_data)
else:
print(my_form.errors)
context = {'form': my_form}
return render(request, "products/product_create.html", context)

Django version 3.1.3 form not saving to model

I am following this tutorial
I have gone back and written the code to match exactly. I have another form that works called category_add which is exactly the same as this form. But for the life of me I cannot figure out why bookmark_add doesn't update the database with the form entries.
Models.py
from django.db import models
from django.contrib.auth.models import User
class Category(models.Model):
title = models.CharField(max_length=255)
description = models.TextField(blank=True, null=True)
created_by = models.ForeignKey(User, related_name='categories', on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name_plural = 'Categories'
def __str__(self):
return self.title
class Bookmark(models.Model):
category = models.ForeignKey(Category, related_name='bookmarks', on_delete=models.CASCADE)
title = models.CharField(max_length=255)
description = models.TextField(blank=True, null=True)
url = models.CharField(max_length=255, blank=True)
created_by = models.ForeignKey(User, related_name='bookmarks', on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
View.py
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from .forms import BookmarkForm
#login_required
def bookmark_add(request, category_id):
if request.method == 'POST':
form = BookmarkForm(request.POST)
if form.is_valid():
bookmark = form.save(commit=False)
bookmark.created_by = request.user
bookmark.category_id = category_id
bookmark.save()
return redirect('category', category_id=category_id)
else:
form = BookmarkForm()
context = {
'form': form
}
return render(request, 'bookmark/bookmark_add.html', context)
Forms.py
from django.forms import ModelForm
from .models import Bookmark
class BookmarkForm(ModelForm):
class Meta:
model = Bookmark
fields = ['title', 'description', 'url']
Urls.py
path('', dashboard, name='dashboard'),
path('categories/', categories, name='categories'),
path('categories/add/', category_add, name='category_add'),
path('categories/<int:category_id>/', category, name='category'),
path('categories/<int:category_id>/add_bookmark', bookmark_add, name='bookmark_add')
]
bookmark_add.html
{% extends 'core/base.html' %}
{% block content %}
<div class="container">
<h1 class="title">Add link</h1>
<form method="post" action=".">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="button is-primary">Submit</button>
</form>
</div>
{% endblock %}
Solved this!
This was a dumb issue and an oversight on my end. Thanks to the content creator on youtube. I just needed to append "/" to the url path for add_bookmark.
Problem:
path('categories/<int:category_id>/add_bookmark', bookmark_add, name='bookmark_add')
The Fix:
path('categories/<int:category_id>/add_bookmark/', bookmark_add, name='bookmark_add')

How to send multiple model from a classbased view in django

I made a booklist where cover image can be uploaded inside Booklist class. For more image I added another class called Bookcover. Now in Views.py how can I send both Booklist and Bookcover's by using BookListView
models.py file is below
from django.db import models
from django.utils import timezone
class Booklist(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length = 100)
cover = models.ImageField(null=True, blank=True, default='default-book.jpg')
description = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
price = models.DecimalField(decimal_places=3, max_digits=100)
def __str__(self):
return self.title
class Bookcover(models.Model):
post = models.ForeignKey(Booklist, default=None, on_delete=models.CASCADE)
covers = models.ImageField(upload_to = 'images/')
def __str__(self):
return self.post.title
here is views.py file
from django.shortcuts import render
from django.views.generic import ListView
from .models import Booklist, Bookcover
def home(request):
return render(request, template_name='home/index.html')
class BookListView(ListView):
model = Booklist
template_name = 'home/index.html'
context_object_name = 'books'
ordering = ['-date_posted']
If you make a ForeignKey, Django automatically will generate a relation in reverse to access - in this case - the related BookCovers for a specific Book. Since you did not specify the related_name=… parameter [Django-doc], the name of this relation is modelname_set, so in this case, bookcover_set.
In the template you can access the book covers of a book with:
{% for book in books %}
{{ book.title }}
{% for cover in book.bookcover_set.all %}
<img src="{{ cover.covers.url }}">
{% endfor %}
{% endfor %}
This will result in an N+1 problem however. You can avoid that by using .prefetch_related(…) [Django-doc]:
class BookListView(ListView):
queryset = Booklist.objects.prefetch_related('bookcover_set')
template_name = 'home/index.html'
context_object_name = 'books'
ordering = ['-date_posted']

dropdown box empty in django when trying to populate values from database

I am new to Django and I was unable to find a fix for this. I am trying to populate a dropdown box with the database values.
Here are my files
models.py file
from django.db import models
# Create your models here.
class Page(models.Model):
title = models.CharField(max_length=60)
permalink = models.CharField(max_length=12, unique=True)
update_date = models.DateTimeField('Last Updated')
bodytext = models.TextField('Page Content', blank=True)
def __str__(self):
return self.title
class Item(models.Model):
itemId = models.AutoField(primary_key=True)
itemName = models.CharField(max_length = 100, unique=True)
itemPrice = models.IntegerField()
def __str__(self):
return self.itemName
forms.py file
from django import forms
from .models import Item
class OrderListForm(forms.Form):
itemNames = forms.queryset = Item.objects.all().order_by('itemName')
urls.py file
from django.urls import path
from . import views
urlpatterns =[
path('',views.OrderListView.as_view(),name ='hello'),
]
views.py file
from django.views.generic.edit import FormView
from .forms import OrderListForm
# Create your views here.
class OrderListView(FormView):
template_name = "myapp/orderlist.html"
form_class = OrderListForm
context_object_name = 'itemNames'
orderlist.html file
<form action="" method = "post">
{% csrf_token %}
<label for="Items">Choose an Item:</label>
<select id = items >
{% for item in itemNames %}
<option value = "">{{item.itemName}}</option>
{% endfor %}
</form>
Changed the view to listview. I am not sure why I used Formview
Here's the code
views.py
from django.views.generic import ListView
from .models import Item
class OrderListView(ListView):
template_name = "myapp/orderlist.html"
context_object_name = 'itemNames'
def get_queryset(self):
return Item.objects.all()
The other answer is to change the html file to
<form action="" method = "post">
{% csrf_token %}
<label for="Items">Choose an Item:</label>
{{form.as_p}}
</form>

Dropdownlist not displayed in Django

I am trying to implement a dropdownlist from my models into an HTML using Django. The form is working perfectly, but the dropdownlist is not displayed, it only displays "languages:" but not a dropdownlist or any options.
Any ideas?
add_page.html
{% extends 'main/header.html' %}
{% block content %}
<br>
<form method="POST">
{% csrf_token %}
{{form.as_p}}
<button style="background-color:#F4EB16; color:blue"
class="btn btn-outline-info" type="submit">Add Page</button>
</form>
{% endblock %}
forms.py
from django import forms
from django.forms import ModelForm
from main.models import Pages
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.db import models
class NewUserForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ("username", "email", "password1", "password2")
def save(self, commit=True):
user = super(NewUserForm, self).save(commit=False)
user.email = self.cleaned_data["email"]
if commit:
user.save()
return user
class PagesForm(ModelForm):
class Meta:
model = Pages
fields = ["title","language","content"]
models.py
from django.db import models
from datetime import datetime
#from django.forms import ModelForm
# Create your models here.
LANGUAGE_CHOICES = (
('english','ENGLISH'),
('spanish', 'SPANISH'),
('german','GERMAN'),
('french','FRENCH'),
('chinese','CHINESE'),
)
#Pages son entradas del diario
class Pages(models.Model):
title = models.CharField(max_length=300)
content = models.TextField()
author = models.CharField(max_length=50)
published_date = models.DateTimeField("Published: ", default=datetime.now())
language = models.CharField(max_length=7, choices=LANGUAGE_CHOICES, default='english')
def __str__(self):
return self.title
views.py
#/pages/my_pages/add_page
#login_required
def add_page(request):
if request.method == "POST":
form = PagesForm(request.POST)
if form.is_valid():
model_instance = form.save(commit=False)
model_instance.author = request.user.username
model_instance.timestamp = timezone.now()
messages.success(request, f"New page created, thank you: {model_instance.author}")
model_instance.save()
return redirect('/')
else:
form = PagesForm()
return render(request, "main/add_page.html", {'form': form})
I've got nothing else to say, but the editor wont let me edit unless I write more text...

Categories