I have the following form
{% for key in keys %}
<th>
<div class="card-body">
<label for="{{ key }}">Should We import this column?</label>
<input id="{{ key }}" name="import[]" value="{{ key }}" type="checkbox">
</div>
</th>
{% endfor %}
which renders like this
<input id="name" name="import[]" value="name" type="checkbox">
<input id="name" name="import[]" value="email" type="checkbox">
<input id="name" name="import[]" value="category" type="checkbox">
what I expect is when the checkboxes are selected the value should be present in the import[] array. but after the form is posted, what I get is,
# from request.POST array
'import[]' = 'email' # whichever I selected last
where what i expect is the following,
import = [
'email',
'name'
]
how can i achieve this in django, i am not using any forms so far.
Django 2, Python 3.5
Related
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">
I have a list of articles.
After I press Edit, I am redirected to another page containing in the url the id of the article that wants to be edited.
Edit
This is where I am redirected:
And I want the inputs to be filled with the title and the body text of the respective article.
This is my backend function:
#app.route('/edit_article/<string:id>', methods=['POST', 'GET'])
def edit_article(id):
conn = mysql.connect()
cursor = conn.cursor()
result = cursor.execute("SELECT * from articles where id=%s", [id])
data = cursor.fetchone()
if result < 0:
flash("Article does not exist!")
cursor.close()
conn.close()
return render_template("edit_article.html", data=data)
How can I use data to fill those inputs? Please help. Thank you.
I will put also the edit_article.html
{% extends 'layout.html' %}
{% block body %}
<div class="container">
<div class="jumbotron">
<h1>Bucket List App</h1>
<form class="form-addArticle">
<label for="inputTitle" class="sr-only">Title</label>
<input type="name" name="inputTitle" id="inputTitle" class="form-control" placeholder="Title" required autofocus>
<label for="inputBody" class="sr-only">Body</label>
<input type="text" name="inputBody" id="inputBody" class="form-control" placeholder="Body" required autofocus>
<button id="btnEditArticle" class="btn btn-lg btn-primary" type="button">Update article</button>
</form>
<p class="text-center" style="color:red" id="message"></p>
</div>
</div>
{% endblock %}
You can just need to add value="{{ ... }}" to your inputs:
<input type="name" value="{{ data[0] }}" name="inputTitle" id="inputTitle" class="form-control" placeholder="Title" required autofocus>
<input type="text" value="{{ data[1] }}" name="inputBody" id="inputBody" class="form-control" placeholder="Body" required autofocus>
But it's recommended to name the values:
name, text = cursor.fetchone()
return render_template("edit_article.html", name=name, text=text)
and then
<input type="name" value="{{ name }}" name="inputTitle" id="inputTitle" class="form-control" placeholder="Title" required autofocus>
<input type="text" value="{{ text }}" name="inputBody" id="inputBody" class="form-control" placeholder="Body" required autofocus>
But I'd personally recommend WTForms module instead of rendering forms manually - it can for example help to validate your inputs properly.
I saw all the conversations about this issue, but I can't solve it. I am new in this Python-Django programming so if anyone can help me? :)
This is my views.py:
class HistoryProjectCreate(CreateView):
template_name = 'layout/create_proj_history.html'
model = ProjectHistory
project = Project.objects.latest('id')
user = User.id
fields = ['user', 'project', 'user_start_date']
success_url = reverse_lazy('git_project:index')
Var project has to return latest project ID from database, and I have to use it ID in my html form:
<form class="form-horizontal" action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<label for="user"></label>
<input id="user" type="text" name="user" value="{{ user.id }}" ><br>
<label for="project">Project title: </label>
<input id="project" type="text" name="project" value="{{ project.id }}" ><br>
<!--Here - "project.id" I need latest project ID-->
<label for="user_start_date">Start date: </label>
<input id="user_start_date" type="date" name="user_start_date" value="{{ projectHistory.user_start_date }}" ><br>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>
I am not sure if project = Project.objects.latest('id') is correct statement for getting the latest ID from Project table.
If you want the last Id of project, you need to order by id, and use last() function available on queryset
project = Project.objects.order_by('id').last()
Order_by doc
Last function doc
I am trying to submit form with array fields and process on Django view. Also, I want to compare the submitted form data with correct answer table data.
question.html:
<form method="post" class="form-inline">
{% csrf_token %}
{% for question in questions %}
<h3>{{ question.title }}</h3>
<div class="radio">
<label class="radio-inline">
<input type="radio" name="ans{{ question.id }}" value="{{ question.option.0 }}">
{{ question.option.0 }}
</label>
</div>
<div class="radio">
<label class="radio-inline">
<input type="radio" name="ans{{ question.id }}" value="{{ question.option.1 }}">
{{ question.option.1 }}
</label>
</div>
<div class="radio">
<label class="radio-inline">
<input type="radio" name="ans{{ question.id }}" value="{{ question.option.2 }}">
{{ question.option.2 }}
</label>
</div>
{% endfor %}
<button type="submit" class="btn btn-success" name="ans_submit">Submit</button>
</form>
view.py:
if request.method == 'POST':
if(request.POST.get('ans_submit')):
temp_context["submitted_answers"] = request.POST.get("ans", "") # Receive as an array?
Expecting to get expert advice.
Thanks
Actually what is posted to you is ans0, ans1, ..., ansN.
So what you want to do is something like this:
answer_fields = [field for field in request.POST if field.startswith('ans')]
for field in answer_fields:
# Do something with `field`...
print(request.GET[field])
Additionally, you might want to check that the latter part is numeric, like so:
[field for field in request.POST
if field.startswith('ans') and field[3:].isnumeric()]
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