Django My form is not saving in django db ? - python

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']

Related

Why value is not Inserting in the database using django

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>

how to create a django app that performs a google search

I want to make a Django app that searches on google a string and then saves the html page.
so far I managed to
create this
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<div class="container text-center">
<h1>my search engine</h1>
<h3>Pressing search will run a google search for 'lallero search', then the code will scrape the first 5 links in that google search and store the corresponding html.</h3>
About page
<br>
<br>
<form action="{% url 'search' %}">
<input type='submit' value='search' class="btn btn-primary">
</form>
</div>
that searches on google a very specific string and it is just a press button.
I would like to add a form where I can write the string I want to search and then pass it as input to my "search" function
so far I came out with this
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<div class="container text-center">
<h1>my search engine</h1>
About page
<br>
<br>
<form action="{% url 'search' %}">
<input type="search" value='lallero search' class="form-control rounded" placeholder="Search" aria-label="Search"
aria-describedby="search-addon" />
<button type="button" class="btn btn-outline-primary">search</button>
</div>
but I do not know how to pass the string I write as input to the function.
any advice?
--------------------update
Following comments, I put the SearchForm into a utils file that I import and then I changed my search function to
def search(request):
form = SearchForm(request.GET)
if form.is_valid(): # this will validate your form
search_text = form.cleaned_data["search"] # now you can access input
urls = searchWeb(num=5, stop=5, query_string=search_text)
threads = [threading.Thread(target=getSavePage, args=(url,)) for url in urls]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
return JsonResponse(urls, safe=False)
I changed my template to
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<div class="container text-center">
<h1>my search engine</h1>
About page
<br>
<br>
<form action="{% url 'search' %}">
{{ form.non_field_errors }}
{{ form.as_p }} <!-- This will create a text input with attributes -->
<input type="submit" value="Submit">
</form>
</div>
I get an error as the form status is unknown
Briefly, in your view that is been invoked by the form can access your form data with request.GET, request.POST. Since its search functionality get method should be used. And your input will be in your querysting something like www.yourdomain.com/search-view?search=input.Instead of accessing it by request.GET["search"], django forms will be a better choice. In your case
from django import forms
class SearchForm(forms.Form):
search = forms.CharField(required=True, max_lenght=255, label="Search")
And you can use it in your template as
<form action="{% url 'search' %}">
{{ form.non_field_errors }}
{{ form.as_p }} <!-- This will create a text input with attributes -->
<input type="submit" value="Submit">
</form>
And you can use it in your view;
from . import SearchForm
form = SearchForm(request.GET)
if form.is_valid(): # this will validate your form
search_text = form.cleaned_data["search"] # now you can access input
Please check out working with forms.
Edit:
def search(request):
if request.method == 'GET':
# create a form instance and populate it with data
form = SearchForm(request.GET)
# check whether it's valid:
if form.is_valid():
print("Form is valid now you can process your data")
# return a response or render a different template
return HttpResponseRedirect('/redirect-url/')
# if not render the form back
return render(request, 'your_template.html', {"form": form})
# Assume post method is not allowed
return HttpResponseNotAllowed()
following #berkeeb answer I changed the code in this way.
I created a forms.py file with:
from django import forms
class SearchForm(forms.Form):
search = forms.CharField(required=True, max_length=255, label="search")
in my template (home.html) I used:
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<div class="container text-center">
<h1>my search engine</h1>
About page
<br>
<br>
<form action="{% url 'search' %}">
<label for="search_text">Your search: </label>
<input id="search_text" type="text" name="search_text">
<input type="submit" value="Search">
</form>
</div>
and finally in the search function I wrote:
def search(request):
form = SearchForm(request.GET)
search_text = form.data["search_text"] # now you can access input
urls = searchWeb(num=5, stop=5, query_string=search_text)
threads = [threading.Thread(target=getSavePage, args=(url,)) for url in urls]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
return render(request, "engine/search.html", {"search": urls})
basically I had to remove the validation part of the form as I kept receiving status unknown.

Forms.ValidationError Not Working, Django,

from django import forms
from django.core import validators
class FormName(forms.Form):
name = forms.CharField()
email = forms.EmailField()
verify_email = forms.EmailField(label = "enter your email Again")
text = forms.CharField(widget = forms.Textarea)
def clean(self):
all_clean_data = super().clean()
email = all_clean_data['email']
vmail = all_clean_data['verify_email']
if email != vmail:
raise forms.ValidationError("Error i Email matching")
views.py
from django.shortcuts import render
from . import form
# Create your views here.
def index(request):
return render(request,'basicapp/index.html')
def form_name_view(request):
forms = form.FormName()
if request.method == "POST":
formObject = form.FormName(request.POST)
if formObject.is_valid():
print("Sucess!!!!!")
print(formObject.cleaned_data['name'])
print(formObject.cleaned_data['email'])
print(formObject.cleaned_data['text'])
return render(request,'basicapp/form_page.html',{'form':forms})
form_page.html
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Forms</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
<div class = "container">
<h1>Fill out the form</h1>
<form method="POST">
{{form.as_p}}
{% csrf_token %}
<input type="submit" class="btn btn-primary" value = "Submit">
</form>
</div>
</body>
</html>
I am Not sure What I am missing,
I have done everything and had done enough research, But could not find the solution.
Am I missing something because of the versioning of django.
I am following one udemy course and didn't get response, Thats y I am posting here.
Thanks in advance
The issue was in your views, you were not rendering the form object properly.
try this,
def form_name_view(request):
if request.method == "POST":
formObject = form.FormName(request.POST)
if formObject.is_valid():
print("Sucess!!!!!")
# do some redirection
else:
# if a GET (or any other method) we'll create a blank form
formObject = form.FormName()
return render(request, 'basicapp/form_page.html', {'form': formObject})

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>

Django forms: integrating a submit button as part of your form

So say I had a django views.py file with the following:
def addauthorView(request):
if request.method == 'POST':
f = ContactForm(request.POST)
if form.is_valid():
first_name = form.cleaned_data['firstname']
last_name = form.cleaned_data['lastname']
user_email = form.cleaned_data['email']
c = Contact(firstname=first_name, lastname=last_name, email=user_email)
else:
form = ContactForm(request.POST)
return render(request, 'addauthor.html', {'form': ContactForm})
else:
return render(request, 'addauthor.html', {'form': ContactForm})
A forms.py file like such
class ContactForm(forms.Form):
firstname = forms.CharField(max_length=50)
lastname =forms.CharField(max_length=50)
email = forms.EmailField()
and a HTML file like such
<html>
<head>
<title>Head</title>
</head>
<body>
<ul>
{{form.as_ul}}
<input type="submit">
</ul>
</body>
How do I make it the case that when the <input type="submit"> button is pressed, my ContactFormview will execute some code. Is there a specific way to group buttons into a forms.py? Or is there any other way to do this. If someone could help me rework this code, that would be great.
Thanks in advance.
Just enclose form.as_ul and submit button into the form tag:
<form action="/your_url_here/" method="post">{% csrf_token %}
{{ form.as_ul }}
<input type="submit" value="Submit" />
</form>
Also see Displaying a form using a template.
Hope that helps.

Categories

Resources