Value Error when submitting form in Django mysql - python

I am getting a value error when submitting a form in Django. I have successfully connected the MySQL database in XAMPP. I can not find a solution to this.Here is my form code,
<form class="user" method="POST">
{% csrf_token %}
<div class="form-group">
<input type="text" class="form-control form-control-user" id="Cus_name" name="Cus_name" placeholder="Enter Customer Name...">
</div>
<div class="form-group">
<input type="text" class="form-control form-control-user" id="Cus_address" name="Cus_address" placeholder="Enter Address... ">
</div>
<div class="form-group">
<input type="email" class="form-control form-control-user" id="Cus_email" placeholder="Enter Email Address...">
</div>
<div class="form-group">
<input type="text" class="form-control form-control-user" id="Purpose" placeholder="Enter Purpose...">
</div>
<div class="form-group">
<input type="date" class="form-control form-control-user" id="Date" placeholder="Enter Date...">
</div>
<div class="form-group">
<input type="time" class="form-control form-control-user" id="Time" placeholder="Enter Time...">
</div>
<div class="form-group">
<input type="text" class="form-control form-control-user" id="Venue" placeholder="Enter Venue...">
</div>
<button name="submit" type="submit" class="btn btn-success">Submit</button>
<hr>
</form>
Here is my Views.py
from django.shortcuts import render
from .models import AppointmentDet
from django.contrib import messages
def InsertDetails(request):
if request.method == 'POST':
if request.POST.get('Cus_name') and request.POST.get('Cus_address') and request.POST.get('Cus_email') and request.POST.get('Purpose') and request.POST.get('Date') and request.POST.get('Time') and request.POST.get('Venue'):
saverecord = AppointmentDet()
saverecord.Cus_name = request.POST.get('Cus_name')
saverecord.Cus_name = request.POST.get('Cus_address')
saverecord.Cus_name = request.POST.get('Cus_email')
saverecord.Cus_name = request.POST.get('Purpose')
saverecord.Cus_name = request.POST.get('Date')
saverecord.Cus_name = request.POST.get('Time')
saverecord.Cus_name = request.POST.get('Venue')
saverecord.save()
messages.success(request, "details saved successfully!")
return render(request, "appform.html")
else:
return render(request, "appform.html")
Here is the error I am getting when running the server.
ValueError at /
The view Management.views.InsertDetails didn't return an HttpResponse object. It returned None instead.
I tried some solutions but did not work.

You should read this little tutorial on how to work with forms:
https://docs.djangoproject.com/en/3.1/topics/forms/
When the data is sent, you should first cast the post into a form class object. Then you have to call "is_valid()" on said form.
Only after this method call the post data are in the object.
This is the example from django:
def get_name(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = NameForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/thanks/')
# if a GET (or any other method) we'll create a blank form
else:
form = NameForm()
return render(request, 'name.html', {'form': form})`

Related

POST request to Flask Blueprint api not working

I am trying to execute a form POST request. The request is received at the route api function but the POST condition is not executing.
Code
<form class="pt-2 pb-4" action = "{{ url_for('data_sources_api.testfn') }}" method = "POST">
<div class="row">
<div class="col-md-4 mb-3">
<label for="url" class="form-label">URL</label>
<input type="text" class="form-control" id="url" name="url" aria-describedby="emailHeurllp"
placeholder="Enter new events top domain source url">
</div>
<div class="col-md-4 mb-3">
<label for="name" class="form-label">Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Enter Organization Name">
</div>
<div class="col-md-12">
<button type="button" class="btn btn-secondary mr-2" value="submit" name = "submit">Submit</button>
</div>
</div>
</form>
Flask Code
#data_sources_api.route('/login/test', methods=["GET", "POST"])
def testfn():
# Check if user is loggedin
if loggedin():
# User is loggedin, render the home page
if request.method == 'POST':
print("POST Request Received")
result = request.form
return render_template('users/data-sources.html', role=session['role'])
return redirect(url_for('account_api.login'))
The request received is GET when i click the submit button and not POST :(
Thanks in advance
I think the problem is with button. Replace the button with input type="submit":
<input type="submit" value="Submit">
Here is the example of Django form.

My form gets Submitted but no data is being added in database django

I am trying to make a website's contact page using django where client enters data and it gets submitted in database, the form gets submitted the project runs without errors and yet no data gets added in the db.
Here's my views.py file
from datetime import datetime
from firstapp.models import Contact
# Create your views here.
def index(request):
return render(request,'index.html',)
def apply(request):
return render(request,'apply.html')
def about(request):
return render(request,'about.html')
def socials(request):
return render(request,'social.html')
def contact(request):
if request.method == "POST":
name = request.POST.get("name")
email = request.POST.get("email")
subject = request.POST.get("subject")
message= request.POST.get("message")
contact=Contact(name=name,email=email,subject=subject,message=message,date=datetime.today())
contact.save
return render(request,'contact.html')
here is my contact.html
{% block title %}Contact {% endblock title %}
{% block body %}
<h2 align="center">CONTACT US </h2>
<div class="container-md">
<form method="POST" action="/contact/">
{% csrf_token %}
<div class="form-group">
<label for="exampleFormControlInput1">Name</label>
<input type="text" class="form-control" id="exampleFormControlInput1" name="name" placeholder="John Smith">
</div>
<div class="form-group">
<label for="exampleFormControlInput1">Email address</label>
<input type="email" class="form-control" id="exampleFormControlInput1" name="email" placeholder="name#example.com">
</div>
<div class="form-group">
<label for="exampleFormControlInput1">Subject</label>
<input type="text" class="form-control" id="exampleFormControlInput1" name="subject" placeholder="Business
| Suggestions | Query | Complaint | Other">
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Message</label>
<textarea class="form-control" name="message" id="exampleFormControlTextarea1" rows="3"></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
{% endblock body%}
And here's my models.py
from django.db import models
# Create your models here.
class Contact(models.Model):
name = models.CharField(max_length=50)
email =models.EmailField(max_length=254)
subject=models.CharField(max_length=10)
message=models.CharField(max_length=1000)
date=models.DateField()
As I wrote at the comments before, you have forgotten to type brackets following the save: contact.save() instead of contact.save.
It would be better and more beautiful if you do it like this:
def contact(request):
if request.method == "POST":
Contact.objects.create(**request.POST)
return render(request,'contact.html')

how to access radio button selected value in Django

I am trying to access radio button selected value in my django view but it returns on instead of selected value.
Template form
<form class="col-md-8 mx-auto" action="upload" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group" id="div_id_sample" >
<label for="id_sample" class="col-form-label requiredField">Select File</label><br>
<div class="btn btn-primary">
<input type="file" name="sample" class="clearablefileinput" required id="id_sample" accept=".exe">
</div>
</div>
<div class="form-group">
<label for="radiogroup">Enforce Timeout</label><br>
<div class="btn-group" data-toggle="buttons" id="radiogroup">
<label class="btn btn-secondary">
<input type="radio" name="timeoptions" id="option60" autocomplete="off" value="60"> 60 seconds
</label>
<label class="btn btn-secondary">
<input type="radio" name="timeoptions" id="option120" autocomplete="off" value="120"> 120 seconds
</label>
<label class="btn btn-secondary active">
<input type="radio" name="timeoptions" id="option180" autocomplete="off" checked value="180"> 180 seconds
</label>
</div>
</div>
<div class="form-group">
<label for="radiogroup2">Select Machine:</label><br>
<div class="btn-group" data-toggle="buttons" id="radiogroup2">
<label class="btn btn-secondary">
<input type="radio" name="machineoptions" id="machine1" autocomplete="off" value="0"> Windows XP
</label>
<label class="btn btn-secondary active">
<input type="radio" name="machineoptions" id="machine2" autocomplete="off" value="1" checked> Windows 7
</label>
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
views.py
in my views i am using ModelForm but not in my HTML and the reason behind that is i copied and pasted the htmlcode generated by the ModelForm. Reason is because i need to collect two more items that are not in my data MODEL so that why.
def upload(request):
if request.user.is_authenticated:
if request.method == 'POST':
file = request.FILES['sample']
form = SampleForm(request.POST, request.FILES)
if form.is_valid():
new_sample = form.save(commit=False)
new_sample.file_name = file.name
new_sample.user = request.user
print(request.POST)
TimeOut = request.POST.get('timeoptions')
machine = request.POST.get('machineoptions')
print(TimeOut)
print(machine)
form.save()
return redirect('reports')
else:
messages.info(request,'Invalid Form')
else:
form = SampleForm()
if request.method == 'GET':
return render(request, 'upload2.html', {'form': form})
else:
return redirect(reverse('login'))
Print output
<QueryDict: {'csrfmiddlewaretoken': ['VvAqdOp8RrpKOgwxLD2dpGartPvUrTHTg9AUbqsX6vphxdojTJqn7tsvLCkneWOm'], 'timeoptions': ['on'], 'machineoptions': ['on']}>
on
on
I am just trying to access the selected button value.
I guess this is mostly because you are enclosing the <input> tag inside the <label> tag.Also you must give the for attribute for and put the input element's id in the <label> tag
Try like this:
<label class="btn btn-secondary" for="option60">60 seconds</label>
<input type="radio" name="timeoptions" id="option60" autocomplete="off" value="60">
You can do this for all the radio buttons.Then in your view you can access with TimeOut = request.POST.get('timeoptions')

form.is_valid() not working when using django forms for updating information to the databse

So I wanna be able to update information of a router in the database using a form, I wanna have a form pre-populated with that specific router details. The problem is that form.is_valid() is not working
I tried using {{ form.errors }} {{ form.non_field_errors }} and print(form.errors) but none of them worked
views.py (incomplete)
def info_router(request, pk):
rout = Routers.objects.get(sn=pk)
if request.method == 'GET': # Insert the info in forms
form = UpdateRouter()
rout = Routers.objects.get(sn=pk)
args = {'router': rout}
return render(request, "router_info.html", args)
if request.POST.get('delete'):
# Delete router
rout.delete()
messages.warning(request, 'Router was deleted from the database!')
return redirect("db_router")
if request.method == 'POST':
#Updating the form
form = UpdateRouter(instance=Routers.objects.get(sn=pk))
print(form)
print(form.errors)
if form.is_valid():
data = UpdateRouter.cleaned_data
mac = data['mac']
print(mac)
return HttpResponseRedirect('db_router')
else:
print("Invalid form")
return render(request, "db_router.html", {'form': form})
forms.py
class UpdateRouter(ModelForm):
class Meta:
model = Routers
fields = ['model', 'ip_addr', 'name', 'sn', 'mac']
template
<form class="form-horizontal" action="" method="post">
{% csrf_token %}
<div class="form-group"> <!-- Form with the router details -->
<label class="control-label col-sm-2" for="text">Serial number:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="text" name="sn" value="{{ router.sn }}" readonly>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="text">Model:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="text" value="{{ router.model }}" name="model" readonly>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="text">Ip address:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="text" value="{{ router.ip_addr }}" name="ip_addr">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="text">Name:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="text" value="{{ router.name }}" name="name">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="text">Mac address:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="text" value="{{ router.mac }}" name="mac">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="text">Extra info:</label>
<div class="col-sm-10">
<textarea class="form-control" name="extra_info" id="FormControlTextarea" rows="3">Example of some info</textarea>
</div>
</div>
<div class="form-group" style="margin-top: 20px;">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary">Update</button> <!-- Responsible for updating the router -->
Cancel
<button type="button" class="btn btn-danger" data-toggle="modal" data-target="#myModal" style="float: right"> <!-- Responsible for the delete modal to open -->
Delete
</button>
</div>
</div>
</form>
You never passed request.POST and rquest.FILES. If you want to update the fields and files, you need to form.save() your form:
if request.method == 'POST':
#Updating the form
form = UpdateRouter(request.POST, request.FILES, instance=Routers.objects.get(sn=pk))
print(form)
print(form.errors)
if form.is_valid():
data = form.cleaned_data
mac = data['mac']
form.save()
print(mac)
return redirect('db_router')
else:
print("Invalid form")
If you do not pass request.POST and/or request.FILES, then Django does not consider the form filled in, and it is never considered valid.
If you pass both files and data, then you need to add the enctype="multipart/form-data" to your <form> tag:
<form enctype="multipart/form-data" class="form-horizontal" action="" method="post">
<!-- -->
</form>
you need to create a bound_form
form = UpdateRouter(request.POST)
form = UpdateRouter(request.POST) binds the data to the form class. then validate
the inputs using is_valid().

Django is not taking input from html POST form

I have this html form:
<form method="post" action="">
{% csrf_token %}
<div class="inputText">
<input type="text" name="username" placeholder="Username" value = required />
<br><br>
<input type="email" name="email" placeholder="Email" required />
<br><br>
<input type="password" name="pass1" id="pass1" placeholder="Password" required />
<br><br>
<input type="password" name="pass2" id="pass2" onkeyup="checkPass(); return false;" placeholder="Confirm Password" required />
<br><br>
<span id="confirmMessage" class="confirmMessage"></span>
</div>
<div class="send">
<input type="submit" name="register" value="Register" class="register" />
</div>
This is my forms.py :
class UserForm(forms.ModelForm):
class Meta:
model = User
fields = ('username', 'email', 'password')
And my view
def register(request):
if request.method == "POST":
form = UserForm(request.POST)
if form.is_valid():
form.save
new_user = authenticate(username=request.POST['username'], password =request.POST['password'])
login(request.new_user)
return HttpResponseRedirect(request, '/index')
else:
form = UserForm()
return render(request, 'authen/register.html', {'form': form})
This should be a register system but when I press register it reloads the register page and nothing. When I go to django admin I see no new user so django is not taking input from form fields.
The form is presumably not valid, but you are not displaying any errors in your template. At least do {{ form.errors }} somewhere, although really you should output all the fields and their errors from the Django form directly:
{{ form.username }}
{{ form.username.errors }}
etc.
Also note you are not actually invoking the save method in your is_valid block. You need to do:
form.save()
Be sure to get the input element by its name attribute. This is because request.POST['keyword'] refers to the element identified by the specified html name attribute keyword.
Here's an example:
<form action="/login/" method="POST">
<input type="text" name="keyword" placeholder="Search query">
<input type="number" name="results" placeholder="Number of results">
</form>
In your Python file, where you get the value of the input elements, request.POST['keyword'] and request.POST['results'] will contain the values of keyword and results, respectively.

Categories