Django forms workaround - python

I'm a bit confused with all the django stuff and forms, I hope you can help me.
I'm migrating a cmd line app to django, and I think I don't need to mess with models (db) atm. I just would like to pass the parameters filled in a form to a python script that use these fields as parameters. I would like to keep my html code and skip render the form with a python form class since it has a lot of css code inside each one.
At the moment I have this form:
<form class="nobottommargin" id="template-contactform" name="template-contactform" action="{% url 'get_data' %}" method="post">
{% csrf_token %}
<div class="col_half">
<label for="name">Project Name <small>*</small></label>
<input type="text" id="name" name="name" value="{{ current_name }}" class="sm-form-control required" />
</div>
<div class="col_half col_last">
<label for="group">Project Group <small>*</small></label>
<input type="text" id="group" name="group" value="{{ current_group }}" class="required sm-form-control" />
</div>
<div class="clear"></div>
<div class="col_half">
<label for="version">Project Version<small>*</small></label>
<input type="text" id="version" name="version" value="{{ current_version }}" class="required sm-form-control" />
</div>
<div class="col_half col_last">
<label for="pType">Project Type<small>*</small></label>
<select id="pType" name="pType" class="required sm-form-control">
<option value="">-- Select One --</option>
<option value="bundle">Bundle</option>
<option value="multiple">Multiple</option>
<option value="git">Git</option>
</select>
</div>
<div class="col_half">
<label for="pPath">Project path<small>*</small></label>
<input type="text" id="pPath" name="pPath" value="{{ current_path }}" class="required sm-form-control" />
</div>
<div class="clear"></div>
<div class="col_full hidden">
<input type="text" id="template-contactform-botcheck" name="template-contactform-botcheck" value="" class="sm-form-control" />
</div>
<div class="col_full" style="margin: 50px 0 0 0 ">
<button class="button button-3d nomargin" type="submit" id="template-contactform-submit" name="template-contactform-submit" value="submit">Create Project</button>
</div>
</form>
So, I want to figure out what's the best way to write the get_data function. I also need some sort of custom validation about some fields that involves other checks that exceeds the basic checks, such as max_chars on each field. That means I need to create some sort of my own form.is_valid() function.
Hope you can help me!
Regards

Related

Python class-based-view updateview not get saved

I am new in programming and trying to make a website for Todo by using Python-django.
I am using Django Class Based Update View to make edit in datas.
But while I am click on submit button its not get saved.
models.py
class Task(models.Model):
name=models.CharField(max_length=25)
details=models.CharField(max_length=750)
priority=models.CharField(max_length=500)
date=models.DateField()
user=models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
def __str__(self):
return self.name
views.py
class TaskUpdateView(UpdateView):
model = Task
fields = "__all__"
template_name = 'update.html'
context_object_name = 'task'
success_url = reverse_lazy('cbvhome')
urls.py
path('update/<pk>',views.TaskUpdateView.as_view(),name='cbvupdate')
update.html
<form method="post" class=" justify-content-center align-items-center mb-4 ps" enctype="multipart/form-data">
{% csrf_token %}
<div class="mb-3">
<label for="task-id" class="form-label me-5">Task</label>
<input type="text" name="name" class="form-control" id="task-id" aria-describedby="emailHelp" style="width: 80%;" placeholder="Enter your Task Here" value="{{task.name}}">
</div>
<div class="mb-3">
<label for="exampleFormControlTextarea1" class="form-label me-5">Enter the details</label>
<textarea class="form-control" name="details" id="task-detail"rows="2" placeholder="Enter the task details" style="width: 80%;">{{task.details}}</textarea>
</div>
<div class="mb-3">
<label for="task-date" class="form-label me-5">Date set curerntly: {{task.date}}</label>
<input type="date" name="date" class="form-control" id="task-date" style="width: 80%;" value="{{task.date}}">
</div>
<div class="mb-3 mt-3">
<label for="task-prio" class="form-label me-5">Select the priority</label>
<select class="form-select" name="priority" aria-label="Default select example" style="width: 80%;" id="task-prio" value="{{task.priority}}">
<option selected>{{task.priority}}</option>
<option value="Very Urgent" class="text-danger">Very Urgent</option>
<option value="Urgent" class="text-warning">Urgent</option>
<option value="Important" class="text-primary">Important</option>
</select>
</div>
<div class="submit pe-5" style="padding-left: 100px; padding-top: 10px;" >
<input type="submit" class="btn btn-outline-success me-5" value="Save">
</div>
</form>
By default if nothing is given in url params, so it is considered as str type, so define it as int:
path('update/<int:pk>/',views.TaskUpdateView.as_view(),name='cbvupdate')
It will be better if you give action="{% url 'cbvupdate' %}" in form tag of HTML although not necessary as Django always takes current page route.
Note: Always add / at the end of every route.

Django HTML form not populating variables

I am trying to get the input of the forms by just using requests and no actual django form(I do not need to store this data in a database.) So I am trying to use request.GET.get() method, but so far I have had no luck with it. I am pretty sure that it is something wrong with my HTML, but I could be wrong.
Here is my views.py
if request.method == "GET":
lineGraphInp=request.GET.getlist('lineGraphInp')
lineTableInp=request.GET.get('lineTableInp')
print(lineGraphInp)
print(lineTableInp)
Also, here are my forms
<form method="GET">
<h3>Choose: </h3>
<select class="custom-select" name="lineTableInp">
<option value="myPosition">My Position</option>
<option value="myCompetitors">My Competitors</option>
<option value="top100">Top 100</option>
<option value="bottom100">Bottom 100</option>
</select>
</form>
and
<form method="GET">
<h3>Choose: </h3>
<div style="margin-left:15px;">
<div class="form-check form-check-inline">
<input name="lineGraphInp" class="form-check-input" type="checkbox" value="myPosition">
<label class="form-check-label" for="inlineCheckbox1">My Position</label>
</div>
<div class="form-check form-check-inline">
<input name="lineGraphInp" class="form-check-input" type="checkbox" value="myCompetitors" >
<label class="form-check-label" for="inlineCheckbox2">My Competitors</label>
</div>
<div class="form-check form-check-inline">
<input name="lineGraphInp" class="form-check-input" type="checkbox" value="top100">
<label class="form-check-label" for="inlineCheckbox3">Top 100</label>
</div>
<div class="form-check form-check-inline">
<input name="lineGraphInp" class="form-check-input" type="checkbox" value="bottom100">
<label class="form-check-label" for="inlineCheckbox3">Bottom 100</label>
</div>
</div>
</form>
You have not specified form acion
Eg.
<form method="GET" action="/">
Content Here
</form>
Please make sure that you mention that action it will not work unless you will mention it
I think these only a issue..!!!
Thank You

I want to update my student record in the database, but its not working

The first problem is that when the update form is appeared date-of-birth field is not getting data from the database.
The Second thing is that whenever i click on the submit button it will not update my values in the databse.
The Third thing is after i click on the update or submit button it will automatically redirect to me in the insertion form which i don't want to be there (and i not even give the link or render to that page and i don't understand what is going on here beacause instead of it it will need to show my editstudent.html page not insertstudent.html page)
and YES!!! MY UPDATE IS ALSO NOT WORKING......
PLEASE HELP ME OUT AT THIS.......
editstudent.html PAGE:-
{% extends 'student/index.html' %}
{% block content %}
<div class="col-md-6">
<!-- general form elements -->
<div class="card card-primary">
<div class="card-header">
<h3 class="card-title">Update Student Here</h3>
</div>
<!-- /.card-header -->
<!-- form start -->
<form action="{% url 'studentinsert' %}" role="form" method="POST">
{% csrf_token %}
<div class="card-body">
<div class="form-group">
<label for="exampleInputEmail1">Student ID</label>
<input type="text" class="form-control" name="id" placeholder="Enter Student ID" value="{{ student.sid }}">
</div>
<div class="form-group">
<label for="exampleInputPassword1">First Name</label>
<input type="text" class="form-control" name="firstname" placeholder="Enter First Name" value="{{ student.first_Name }}">
</div>
<div class="form-group">
<label for="exampleInputFile">Last Name</label>
<div class="input-group">
<div class="custom-file">
<input type="text" class="form-control" name="lastname" placeholder="Enter Last Name" value="{{ student.last_name }}">
</div>
</div>
</div>
<div class="form-group">
<label for="exampleInputFile">Major</label>
<div class="input-group">
<div class="custom-file">
<input type="text" class="form-control" name="major" placeholder="Enter Major" value="{{ student.major }}">
</div>
</div>
</div>
<div class="form-group">
<label for="exampleInputFile">Phone Number</label>
<div class="input-group">
<div class="custom-file">
<input type="text" class="form-control" name="phonenumber" placeholder="Enter the Phone Number" value="{{ student.phone }}">
</div>
</div>
</div>
<div class="form-group">
<label for="exampleInputFile">GPA</label>
<div class="input-group">
<div class="custom-file">
<input type="text" class="form-control" name="gpa" placeholder="Enter GPA" value="{{ student.gpa }}">
</div>
</div>
</div>
<div class="form-group">
<label for="exampleInputFile">Date-of-Birth</label>
<div class="input-group">
<div class="custom-file">
<select name="DOBMonth" value="{{ student.date_of_birth }}">
<option>- Month -</option>
<option value="January">January</option>
<option value="Febuary">Febuary</option>
<option value="March">March</option>
<option value="April">April</option>
<option value="May">May</option>
<option value="June">June</option>
</select>
<select name="DOBDay" value="{{ student.date_of_birth }}>
<option>- Day -</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
<select name="DOBYear" value="{{ student.date_of_birth }}>
<option>- Year -</option>
<option value="2020">2020</option>
<option value="2019">2019</option>
<option value="2018">2018</option>
<option value="2017">2017</option>
<option value="2016">2016</option>
<option value="2015">2015</option>
</select>
</div>
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
<!-- /.card -->
</div>
{% endblock %}
My Views.py Page:-
def upstudent(request,pk):
obj=Student.objects.get(id=pk)
if request.method=="POST":
iid=request.POST['id']
firstname=request.POST['firstname']
lastname=request.POST['lastname']
major=request.POST['major']
phonenumber=request.POST['phonenumber']
gpa=request.POST['gpa']
birth=request.POST['DOBDay']
month=request.POST['DOBMonth']
year=request.POST['DOBYear']
d = Date()
d.day = birth
d.month = month
d.year = year
d.save()
s=Student(Student.objects.get(id=obj))
s.date_of_birth = d
s.sid=iid
s.first_Name=firstname
s.last_name=lastname
s.major=major
s.phone=phonenumber
s.gpa=gpa
s.save()
return HttpResponse("Data is updated")
else:
student = Student.objects.get(id=pk)
return render(request,"student/editstudent.html",{"student":student})
My Models.py Page:-
class Date(models.Model):
month=models.CharField(max_length=200)
day=models.CharField(max_length=200)
year=models.CharField(max_length=200)
class Student(models.Model):
sid=models.CharField(max_length=200)
first_Name=models.CharField(max_length=200)
last_name=models.CharField(max_length=200)
major=models.CharField(max_length=200)
phone=models.CharField(max_length=200)
gpa=models.CharField(max_length=200)
date_of_birth = models.ForeignKey(Date,on_delete=models.CASCADE)
MY Urls.py Page:-
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path("index",views.index,name="index"),
path("studentinsert",views.studentinsert,name='studentinsert'),
path("studentdata",views.studentdata,name="studentdata"),
path("upstudent/<int:pk>",views.upstudent,name="upstudent")
]
There are a lot of issues in your code:
Why is your date_of_birth linked via ForeignKey instead of OneToOneField? Can Student has more than 1 date of birth? Following changes will work if you swap it to one-to-one relation.
The first problem is that when the update form is appeared date-of-birth field is not getting data from the database.
Happens because there is no value attribute of select tag - you have to put selected attribute on option tag. Change your code to something like:
<select name="DOBMonth">
<option>- Month -</option>
<option value="January"{% if student.date_of_birth.month == 'January' %} selected="selected"{% endif %}>January</option>
<option value="Febuary"{% if student.date_of_birth.month == 'Febuary' %} selected="selected"{% endif %}>Febuary</option>
<option value="March"{% if student.date_of_birth.month == 'March' %} selected="selected"{% endif %}>March</option>
<option value="April"{% if student.date_of_birth.month == 'April' %} selected="selected"{% endif %}>April</option>
<option value="May"{% if student.date_of_birth.month == 'May' %} selected="selected"{% endif %}>May</option>
<option value="June"{% if student.date_of_birth.month == 'June' %} selected="selected"{% endif %}>June</option>
</select>
Same goes to day and year.
The Third thing is after i click on the update or submit button it will automatically redirect to me in the insertion form
It redirects you because form tag action attribute points to incorrect view. Currently it's action="{% url 'studentinsert' %}" and should be action="{% url 'upstudent' pk=student.pk %}"
The Second thing is that whenever i click on the submit button it will not update my values in the databse.
As #Mehran said, you should not refetch Student. Just do this:
obj.date_of_birth = d
obj.sid=iid
obj.first_Name=firstname
obj.last_name=lastname
obj.major=major
obj.phone=phonenumber
obj.gpa=gpa
obj.save()
Learn django forms - it will simplify your code greatly.
Alright, from the latest comment I think I understand what's going on. Here you are creating a NEW student or showing the already CREATED student data. I'll update the model and view.
Models
class Student(models.Model):
sid=models.CharField(max_length=200)
first_Name=models.CharField(max_length=200)
last_name=models.CharField(max_length=200)
major=models.CharField(max_length=200)
phone=models.CharField(max_length=200)
gpa=models.CharField(max_length=200)
date_of_birth = models.DateField(blank=True, null=True)
Viiews
def upstudent(request,pk):
student=Student.objects.filter(id=pk).first()
if request.method=="POST":
iid=request.POST['id']
firstname=request.POST['firstname']
lastname=request.POST['lastname']
major=request.POST['major']
phonenumber=request.POST['phonenumber']
gpa=request.POST['gpa']
datefield = request.post['datefield']
# depending on your datefield input, which will be a string
# this needs to be converted to a date object
# use .strptime() function for this
if not student:
student = Student() # creating a new student object
student.sid=iid
student.first_Name=firstname
student.last_name=lastname
student.major=major
student.phone=phonenumber
student.gpa=gpa
student.date_of_birth = datefield
student.save()
return HttpResponse("Data is updated")
else:
return render(request,"student/editstudent.html",{"student":student})
EDIT Date type input in form: ​<input type="date" value="2010-12-16;">
You'r using wrong url name in form action
use <form action="{% url 'upstudent' %}" role="form" method="POST"> instead of using <form action="{% url 'studentinsert' %}" role="form" method="POST">

Python Flask Request Form: How to Access the val attribute of the option child element of a select element

I was searching the web, but could not find an answer.
I have the following HTML form:
<form action="/funcation_create_call" method="post">
<div class="form-group">
<label for="user1">Select a Provider</label>
<select name="user1" class="form-control" id="user1">
<option val="3">MCI MCI</option>
</select>
</div>
<div class="form-group">
<label for="user2">Select a Receiver</label>
<select name="user2" class="form-control" id="user2">
<option val="2">Sam San</option>
</select>
</div>
<button class="btn btn-primary btn-lg btn-block" type="submit">Call!</button>
</form>
and the following Python code:
Code: request.form.get('user1')
My goal is to be able to extract the val attribute (e.g. 3) from the option element, but instead, i always get the element text (e.g. MCI MCI)
Any help will be much appreciated!

How to submit a form in Python requests?

I want to submit a form in Python requests. I'm trying to get the list of all members of my organisation from the website.
I've tried the following code:
searchparams={'name':'smith', 'grade':'0', 'format':'html'}
r=requests.post('http://www.thewebsite.co.uk/members/dir/search', data=searchparams)
but it just returns the HTML of the search screen, not the results.
There are also a bunch of other options I could select, but these are the only ones I care about - do I need to submit values for them all?
The form HTML is below, for you information.
<form method="post" action="/members/dir/search" class="col-md-8">
<div class="form-group">
<label for="phone">Surname:</label>
<input type="text" name="name" value="" class="form-control" />
<div class="note">Leave blank to search for all surnames</div>
</div>
<div class="form-group">
<label for="grade">Grade:</label>
<select name="grade" class="form-control">
<option value="0">ALL</option>
<option value="G6">Grade 6</option>
<option value="G7">Grade 7</option>
</select>
</div>
<label>Results format:</label>
<div class="radio">
<label for="format">HTML</label> <input class="tick" type="radio" name="format" value="html" checked="checked" />
</div>
<div class="radio">
<label for="format">Excel</label> <input class="tick" type="radio" name="format" value="excel" />
</div>
<div class="radio">
<label for="format">CSV</label> <input class="tick" type="radio" name="format" value="csv" />
</div>
<div class="form-group">
<button type="submit" name="" class="btn btn-danger">Search</button>
</div>
</form>

Categories

Resources