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.
Related
I am a django beginner even programming beginner this issue I have found one day still can not work out
views.py
from django.shortcuts import render, redirect
from django.template import loader
from .models import Topic
from django.contrib.auth.models import User
from .forms import TopicForm
# Create your views here.
def home(request):
q = request.Get.get('q')
topics = Topic.objects.filter(name__icontains=q)
context = {'topics':topics}
template = loader.get_template('home.html')
return render(request, 'home.html', context)
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Topic(models.Model):
name = models.CharField(max_length=200)
description = models.TextField()
home.html
<body>
{% include 'navbar.html' %}
<div>
<div>
<h3>Topic</h3>
{% for topic in topics %}
{{topic.name}}
{% endfor %}
</div>
</div>
</body>
I tried if statment still not work
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
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.
I'm new in Django, I researched how to create drop-down. I tried everything, but still, the dropdown is not showing in HTML view.
My sample script is this.
This is the model.py
from django.db import models
class samplemodel(models.Model):
list = (
('sample1','SAMPLE1'),
('sample2','SAMPLE2'),
)
list_choices = models.CharField(max_length=6, choices=list)
The forms.py
from .models import samplemodel
from django.forms import ModelForm
class sampleForm(ModelForm):
class Meta:
model = samplemodel
fields = ['list_choices']
This is the views.py
from django.shortcuts import render
from .models import samplemodel
from .forms import sampleForm
from django.views.generic import CreateView
class sampleView(CreateView):
model = samplemodel
form_class = sampleForm
template_name = 'home/sample.html'
This is the home.html
{% extends 'base.html' %}
{% block head %}
<title>Home</title>
{% endblock %}
{% block body %}
<div class="container">
<form class="post">
{% csrf_token %}
{{ form.as_p }}
</form>
</div>
{% endblock %}
I tried everything that I saw on the internet. But I can't still show the drop-down. I don't know if the imports are the issue or not.
you model should be like this
from django.db import models
class SampleModel(models.Model):
list = (
('sample1','SAMPLE1'),
('sample2','SAMPLE2'),
)
list_choices = models.CharField(max_length=6, choices=list)
in your urlconf
from django.views.generic import CreateView
from app.models import Samplemodel
from django.forms import ModelForm
url(r'^sample_form$',CreateView.as_view(model=SampleModel, template_name='home/sample.html', success_url='index', name='sample_form'))
thats all you don't need forms.py . django will take care of everything
i am just a beginner and starting with some tutorials on web, i can not understand why this isn't working for me:
my views.py
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext
from django.core.context_processors import csrf
class MainPage(View):
def get(self, request):
return render_to_response("helloworld.html")
class TestHandler(View):
def post(self, request):
q = {}
q.update(csrf(request))
#return render_to_response('test.html', q)
return render_to_response('test.html', {'q':q}, context_instance=RequestContext(self.request))
def get(self, request):
q = self.request.GET.get('q')
return HttpResponse(q)
and my urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from views import MainPage, TestHandler
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^hello$', MainPage.as_view(), name='home'),
url(r'^testform/', TestHandler.as_view()),
url(r'^admin/', include(admin.site.urls)),
helloworld.html
>->-<html>
>->->-<head>
>->->->-<title>Hello, World!</title>
>->->-</head>
>->->-<body>
>->->->-<form method="post" action="/testform/" >
{% csrf_token %}
>->->-<input name="q">
<input type="submit">
</form>
>->->-</body>
>->-</html>
test.html
>-<body>
>-Hello {{q}}
>-</body>
This is running on django 1.6, I read most of post and still can't figure it out.
Unfortunately what you have pasted is a bit of a mess, you are using Class Based Views but yet you have mixed them with function based views (also half of the declarations are missing).
Enable the CSRF Middlware in your settings.py
MIDDLEWARE_CLASSES = (
...
'django.middleware.csrf.CsrfViewMiddleware',
...
)
Fix your views to proper Class Based Views, what you have pasted is totally wrong:
from django.views.generic import CreateView, TemplateView
from django.core.urlresolvers import reverse_lazy
# Create the form in your forms.py
from .forms import (
MyTestForm,
)
class MainPage(TemplateView):
template_name = "test.html"
class TestHandler(CreateView):
form_class = MyTestForm
template_name = "helloworld.html"
success_url = reverse_lazy('home')
Create your form template:
<html>
<head>
<title>Hello, World!</title>
</head>
<body>
<form method="post" action="/testform/">
{% csrf_token %}
<input name="q">
<input type="submit">
</form>
</body>
</html>