Why value is not Inserting in the database using django - python

I want to insert value in the database from checklist. it print me the value but does't show anything in the database. it's empty. sample output what I'm getting if ISMS(which is on the third place) is checked [00100] the zero changes accordingly but this data is not inserting in the data base
below is my code::
Views.py
from collections import Counter
from .models import details
from django.shortcuts import render
from .forms import CheckBoxForm
# Create your views here.
def home(request):
return render(request, 'home.html', {"text": "hello home"})
def about(request):
return render(request, 'about.html', {"text": "hello about"})
def checkbox(request):
if request.method == 'POST':
exec_summary = request.POST.get('Executive_summary')
scope = request.POST.get('Scope')
isms = request.POST.get('ISMS')
methodology = request.POST.get('Methodology')
recommendation = request.POST.get('Recommendation')
print(f'{exec_summary}{scope}{isms}{methodology}{recommendation}')
return render(request, 'checkbox.html')
def form_checkbox(request):
if request.method == 'POST':
form = CheckBoxForm(request.POST or None)
if form.is_valid():
print(form.cleaned_data)
prod = form.save(commit=False) # error here in save
prod.save()
else:
form = CheckBoxForm()
context = {'form': form}
return render(request, 'checkbox.html', context)
urls.py:
from django.contrib import admin
from django.urls import path, include
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home),
path('about/', views.about),
path('checkbox/', views.checkbox)
]
forms.py
from django import forms
from .models import details
class CheckBoxForm(forms.ModelForm):
exec_summary = forms.BooleanField(required=False)
scope = forms.BooleanField(required=False)
isms = forms.BooleanField(required=False)
methodology = forms.BooleanField(required=False)
recommendation = forms.BooleanField(required=False)
class Meta:
model = details
fields = ('exec_summary', 'scope', 'isms', 'methodology', 'recommendation')
widgets = {
'exec_summary': forms.BooleanField(),
'scope': forms.BooleanField(),
'isms': forms.BooleanField(),
'methodology': forms.BooleanField(),
'recommendation': forms.BooleanField(),
}
models.py:
from django.db import models
from django.db.models import Model
class details(models.Model):
exec_summary = models.BooleanField('exec_summary', default=False)
scope = models.BooleanField('scope', default=False)
isms = models.BooleanField('isms', default=False)
methodology = models.BooleanField('methodology', default=False)
recommendation = models.BooleanField('recommendation', default=False)
checkbox.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Checkbox</title>
</head>
<body>
<form action="" method="post">
{%csrf_token%}
<div class="form-check">
<h5>Checkbox_report</h5>
<input type="hidden" name="Executive_summary" value="0" />
<input type="checkbox" name="Executive_summary" value="1" id="Executive_summary" />
<label for="Executive_summary"> Executive summary &nbsp</label>
<input type="hidden" name="Scope" value="0" />
<input type="checkbox" name="Scope" value="1" id="Scope" />
<label for="Scope"> Scope &nbsp</label>
<input type="hidden" name="ISMS" value="0" />
<input type="checkbox" name="ISMS" value="1" id="ISMS" />
<label for="ISMS"> ISMS &nbsp</label>
<input type="hidden" name="Methodology" value="0" />
<input type="checkbox" name="Methodology" value="1" id="ISMS" />
<label for="Methodology"> Methodology &nbsp</label>
<input type="hidden" name="Recommendation" value="0" />
<input type="checkbox" name="Recommendation" value="1" id="Recommendation" />
<label for="Recommendation"> Recommendation &nbsp</label>
</div>
<button type="submit">submit</button>
</form>
</body>
</html>
I did some changes in the above code like. in forms.py file I change the forms.Form to forms.ModelForm. so now data is inserting in the database but everything is 0. mean that whenn I check the checkbox the data is not inserting accordingly mean that value need to be 1 but it still insert 0 and output is now like this:: {'exec_summary': False, 'scope': False, 'isms': False, 'methodology': False, 'recommendation': False}

There is an error in your urls. You do not set the good view for posting the form.
from django.contrib import admin
from django.urls import path, include
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home),
path('about/', views.about),
path('checkbox/', views.form_checkbox) # <-- Here
]
You have to changed too your html. your input name need to be same as the form field :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Checkbox</title>
</head>
<body>
<form action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">submit</button>
</form>
</body>
</html>

Related

Can't be redirected after form action in Django

I created a form for creating a new item in Django. The app should be redirected to item_new but it's not working. This below error occurs.
Page not found
http://127.0.0.1.8000/item/new
show.html
<form
action="{% url 'item_new' %}"
method="POST"
enctype="multipart/form-data"
>
{% csrf_token %}
<div class="formItem">
<label>Name</label>
<input type="name" name="name" />
</div>
<div class="formBtn">
<input type="submit" class="btn btnPrimary" value="Submit" />
</div>
</form>
urls.py
urlpatterns = [
path('item/<slug:slug>/', views.item_detail, name='item_detail'),
path('item/new/', views.item_new, name='item_new'),
]
views.py
def item_detail(request, slug):
item = get_object_or_404(Item, slug=slug)
return render(request, 'item/show.html', {'item': item})
def item_new(request):
return redirect('home')
In your urls.py file, change the order of lines. Like this:
urlpatterns = [
path('item/new/', views.item_new, name='item_new'),
path('item/<slug:slug>/', views.item_detail, name='item_detail'),
]
The order of urls, does matter. In your current situation, requests made to http://127.0.0.1.8000/item/new will be sent to item_detail view function instead of item_new.

Django My form is not saving in django db ?

I am newbie and after reading documentation of django . i made forms but my form is not saving to my db and not showing in my db . please help me i tried so many ways but still its not saving . i have drivers for this purpose i want to register them . but its not saving to my db . and I think its not posting data to my db.
please help me .
Views.py
def driver_form(request):
args = {}
template = Template.objects.get(template_default__exact=1)
template_page = template.template_alias + str("/rentacar/rentacar_driver_form.html")#sir this ?
return render(request, template_page, args)
def driver_save(request):
args = {}
if request.POST:
driver_firstname = request.POST.get('driver_firstname')
driver_lastname = request.POST.get('driver_lastname')
driver_save_form = DriverForm(request.POST)
if driver_save_form.is_valid():
new_driver = driver_save_form.save(commit=False)
new_driver.driver_firstname = driver_firstname
new_driver.driver_lastname = driver_lastname
new_driver.save()
template = Template.objects.get(template_default__exact=1)
template_page = template.template_alias + str("/rentacar/rentacar_driver_form.html")
return render(request, template_page, args)
else:
return HttpResponseRedirect('/')
else:
return HttpResponseRedirect('/')
rentacar_driver_form
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div class="container">
<form method="POST" action="/rentacar/driver-save/">
{% csrf_token %}
<label>
First Name<br>
<input type="text" name="driver_firstname" required>
</label>
<br>
<label>
Last Name<br>
<input type="text" name="driver_lastname" required>
</label>
<br>
<input type="submit" class='btn btn-primary' value="Submit">
</form>
</div>
</body>
</html>
Forms.py
from __future__ import unicode_literals
from django import forms
from rentacar.models import *
class DriverForm(forms.ModelForm):
class Meta:
model = BookingApproval
exclude = (
'driver_firstname',
'driver_lastname',
)
just change
if request.POST:
...
inside of the driver_save view to
if request.method == "POST":
...
Try changing:
driver_firstname = request.POST.get('driver_firstname')
driver_lastname = request.POST.get('driver_lastname')
to:
driver_firstname = request.POST['driver_firstname']
driver_lastname = request.POST['driver_lastname']

Django trying to update a specific item that has an id but then also edit other items if need be

I can't figure out why it won't update/edit an item and then add it back to list with the edits. If someone can help me out thanks! If I find my answer before I get a response I will post it. I posted my views.py, urls.py and the html for the edit page confirm_edit.html just so you can see all of what I am dealing with. thanks for the help!
from django.shortcuts import render, redirect, HttpResponse
from .models import Course
def index(request):
context = {
'course' : Course.objects.all()
}
return render(request, 'chp1/index.html', context)
def create(request):
if request.method == "POST":
Course.objects.create(SLA_TYPE_CD=request.POST['Name'],
SLA_TS=request.POST['description'], ACTUAL_COMPLETION_TS=request.POST['description'],
TICKET_NUM=request.POST['description'], NOTE_TXT=request.POST['description'])
return redirect('/')
def edit(request, id):
course_to_edit = Course.objects.get(id=id)
if request.method == "GET":
return render(request, 'chp1/confirm_edit.html', {'course' : course_to_edit})
def update(request, id):
if request.method == "POST":
course_to_edit.update(SLA_TYPE_CD=request.POST['Name'],
SLA_TS=request.POST['description'], ACTUAL_COMPLETION_TS=request.POST['description'],
TICKET_NUM=request.POST['description'], NOTE_TXT=request.POST['description'])
return redirect('/')
def destroy(request, id):
course_to_delete = Course.objects.get(id=id)
if request.method == "GET":
return render(request, 'chp1/confirm_delete.html', {'course' : course_to_delete})
course_to_delete.delete()
return redirect('/')
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index),
url(r'^create$', views.create),
url(r'^(?P<id>\d+)/destroy$', views.destroy),
url(r'^(?P<id>\d+)/edit$', views.edit),
]
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Edit SLA_VARIANCE_NOTE</title>
<link rel="stylesheet" href="{% static 'chp1/css/styles.css' %}">
</head>
<body>
<div id="addcourse">
<h2>Are you sure you want to edit the following post?</h2>
<form action="/{{ course.id }}/edit" method='post'>
SLA_TYPE_CD: <input type="text" name="Name" value=""> <br>
SLA_TS: <textarea name="description" rows="1" cols="40"></textarea> <br>
ACTUAL_COMPLETION_TS: <textarea name="description" rows="1" cols="40"></textarea> <br>
TICKET_NUM: <textarea name="description" rows="1" cols="40"></textarea> <br>
NOTE_TXT: <textarea name="description" rows="1" cols="40"></textarea><br>
{% csrf_token %}
<button>Back</button>
<input name="edit" type="submit" value="update">
</form>
</div>
</body>
</html>

Python Django 1.7 def(request) function- Post request keeps using same function

Here is the code that I am struggling with. (I commented out the try so I could see what is happening).
def foo(request):
#try:
if request.method == "POST":
unique_id = request.POST.get('def_id', '')
password = request.POST.get('pwd', '')
obj = get_object_or_404(Name, pk=unique_id)
pwd = get_object_or_404(BAR, location_id=unique_id, password=password)
return render(request, 'details/person.html', {'obj': obj, 'pwd':pwd})
#except:
# wrong = 'The ID and Password did not return any results'
# return render(request, 'details/index.html', {'wrong':wrong})
else:
return render(request, 'details/index.html')
Here is the person page that I am struggling with.
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'foo/style.css' %}" />
<body id="generic" class>
<div role="banner" id="top">
<h1 align="center"><font size="30">BAZ</font></h1>
</div>
<div role="banner" id="undertop">
<h4 align="center">Effectively Crowd-Sourcing FOO</h2>
</div>
<div align='center'>
<font id="goo" size="20" color="green"><b>FOO</b></font><br>
<font size="20"><b>{{ obj }}</b></font><br><br>
<font id="gar" size="20" color="green"><b>BAR</b></font><br>
<font size="10" color="red">{{ pwd }}</font><br><br>
<hr>
<p><b>If you would like to donate please fill the information found in this form.<br>Feel free to remain anonymous and leave a comment.</b></p><br>
<form action="{% url 'details:donor' %}" method="post">
{% csrf_token %}
First Name<br>
<input type="text" name="first_Name"><br>
Last Name<br>
<input type="text" name="last_Name"><br>
Donation<br>
<input type="number" placeholder="00.00" name="donation"><br>
Comments<br>
<textarea rows="12" cols="60" maxlength="1000" name="first_Name"></textarea><br>
<input type="submit" value="Submit">
</form>
<hr>
Then, when I try to get the data from the donation form the program calls back invalid literal for int() with base 10: ''
and it refers to this line
obj = get_object_or_404(Name, pk=unique_id)
in the foo() function
My question is, why is it calling the same function? I'm trying to get it to call this function instead.
def donor(request):
if request.method == "POST":
first_Name = request.POST.get('first_Name','')
last_Name = request.POST.get('last_Name','')
donation = request.POST.get('donation','')
comments = request.POST.get('comments','')
goodies = Donor(donor_First_Name=first_Name, donor_Last_Name=last_Name, donation_Amount=donation, comment=comments, person_id=obj_id)
goodies.save()
return render(request, 'details/donor.html')
return render(request, 'details/donor.html')
Here is my urls.py for this section of the webpage.
from django.conf.urls import patterns, url
from details import views
urlpatterns = patterns('',
url(r'^', views.foo, name='foo'),
url(r'^pledge/', views.donor, name='donor'),
)
Thank you so much for your attention!
Thanks to karthikr I was able to find the answer.
The problem was in the urls.py modules. I had it originally set up like this.
from django.conf.urls import patterns, url
from details import views
urlpatterns = patterns('',
url(r'^', views.foo, name='foo'),
url(r'^pledge/', views.donor, name='donor'),
)
But had to update a '$' behind the '^' in order to end the url pattern.
urlpatterns = patterns('',
url(r'^$', views.foo, name='foo'),
url(r'^pledge/', views.donor, name='donor'),
)

How to configure HTML form to work with django models?

I am trying to configure HTML formto work with Django Models rather than using built-in Forms in the framework. I have made the form using Html below and have pasted the code for Model, View and Urls.py. The problem is when I click the submit button, it doesn't perform any action. I am able to view the form but it doesn't serves the purpose. I know the question is very lame, but how would configure the HTML to work with the django model so that the data can be saved to the database?
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body style="font-family:Courier New">
<h1>Add / Edit Book</h1>
<hr/>
<form id="formHook" action="/istreetapp/addbook" method="post">
<p style="font-family:Courier New">Name <input type="text" placeholder="Name of the book"></input></p>
<p style="font-family:Courier New">Author <input type="text" placeholder="Author of the book"></input></p>
<p style="font-family:Courier New"> Status
<select>
<option value="Read">Read</option>
<option value="Unread">Unread</option>
</select>
</p>
<input type="submit" id="booksubmit" value="Submit"></input>
</form>
</body>
</html>
View
from django.shortcuts import HttpResponse
from istreetapp.models import bookInfo
from django.template import Context, loader
from django.shortcuts import render_to_response
def index(request):
booklist = bookInfo.objects.all().order_by('Author')[:10]
temp = loader.get_template('app/index.html')
contxt = Context({
'booklist' : booklist,
})
return HttpResponse(temp.render(contxt))
Model
from django.db import models
class bookInfo(models.Model):
Name = models.CharField(max_length=100)
Author = models.CharField(max_length=100)
Status = models.IntegerField(default=0) # status is 1 if book has been read
def addbook(request, Name, Author):
book = bookInfo(Name = Name, Author=Author)
book.save
return render(request, 'templates/index.html', {'Name': Name, 'Author': Author})
Urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('app.views',
url(r'^$', 'index'),
url(r'^addbook/$', 'addbook'),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
You forgot to define name in each of your input
<form id="formHook" action="/addbook/" method="post">
{% csrf_token %}
<p style="font-family:Courier New">
Name <input type="text" name="name" placeholder="Name of the book"></input>
</p>
<p style="font-family:Courier New">
Author <input type="text" name="author" placeholder="Author of the book"></input>
</p>
<p style="font-family:Courier New">
Status
<select name="status">
<option value="Read">Read</option>
<option value="Unread">Unread</option>
</select>
</p>
<input type="submit" id="booksubmit" value="Submit"></input>
</form>
Your addbook must be in the views.py not in your models.py.
You don't have to define templates/index.html in your render, it is understood in your settings
def addbook(request):
if request.method == 'POST':
name = request.POST['name']
author = request.POST['author']
bookInfo.objects.create(Name = name, Author=author)
return render(request, 'index.html', {'Name': name, 'Author': author})
main urlconf
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'project_name.views.index'),
url(r'^addbook/$', 'project_name.views.addbook'),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
You need to add name attributes to your html form then process the form submission in the view. Something like -
from django.http import HttpResponseRedirect
from django.shortcuts import render
def book_view(request):
if request.method == 'POST':
name = request.POST['name']
author = request.POST['author']
book = BookInfo(name=name, author=author)
if book.is_valid():
book.save()
return HttpResponseRedirect('your_redirect_url')
else:
return render(request, 'your_form_page.html')
Have a look at the docs on the request.POST dictionary.
However you really would be better off doing this with a django ModelForm -
class BookForm(ModelForm):
class Meta:
model = BookInfo # I know you've called it bookInfo, but it should be BookInfo
then in your view -
from django.http import HttpResponseRedirect
from django.shortcuts import render
def book_view(request, pk=None):
if pk:
book = get_object_or_404(BookInfo, pk=pk)
else:
book = BookInfo()
if request.method == 'POST':
form = BookForm(request.POST, instance=book)
if form.is_valid():
book = form.save()
return HttpResponseRedirect('thanks_page')
else:
form = BookForm(instance=book)
return render(request, 'your_form_page.html', {'form': form)
And your_form_page.html can be as simple as -
<form action="{% url book_view %}" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
Have a look at the docs on working with forms.

Categories

Resources