django form multiple fields dynamically - python

So I want to create a member form with Education part that will contain 3 elements:
Foreign Key to Academic_Background (which has High School, BC degree, master degree, etc..),
Charfield - Name of school
Charfield - Field of studies
No problem doing one, or two... but how can I make several "Education" fields (by adding a button of "Add another" and using JS&Jquery to display the new Education to the user.
What should I put in my Model, and in my Form? and how will it be saved in the DB?
It seems like something that probably happened to someone before, yet I couldn't find a solution for that...
Please help !
Thanks

i did this without using django forms .. just using html forms to upload multiple as many as user wishes..
this is my template.html file which has normal form without any input file field initially
the js method adds a new input file field to the form when clicked on "add new item" href
<form action="{{request.path}}" method="post" enctype="multipart/form-data" id="upload_form">
{%csrf_token%}
<input type="text" name="name" id="name" value="{{request.POST.name}}" placeholder="Person Name"/>
<input type="text" name="categorie" id="categorie" value="{{request.POST.categorie}}" placeholder="Categorie"/>
<div class="file_inputs" id="file_inputs">
<!-- <-- field where im adding multiple files initially empty -->
</div>
<input type="submit" value="Upload">
</form>
<!-- link to add new file input box when clicked on it -->
<a href="#" onClick="addformelement()" >add new item</a>
<script type="text/javascript">
// method to add an file input box when clicked on add new item link
function addformelement(){
a = document.getElementById('file_inputs')
divx=document.createElement('div')
divx.class='file_inputs'
x=document.createElement('input');
x.type='file';
x.name='docfile';
divx.appendChild(x);
a.appendChild(divx) ;
}
</script>
and in views i did this
if request.method == 'POST':
name_instance = get_name_instance(request)
if(name_instance == -1):
return HttpResponse("Error - Check Server logs")
for f in request.FILES.getlist('docfile'):
# do your logic for each file f
# as f.name to get filename ...
all my fileinputs have the same id as docfile ...
so in my views i called getlist('docfile')
you can do the same with normal data like
request.POST.getlist('idname')

Related

Django Validate Form As Per Database Entry ID

Hello Wonderful people,
I have made a form in Django which has some serial numbers stored in Django-admin database.
I am now creating another app and similar form, However I want is that the new Form should accept the serial number which is valid and checked as per the serial number got entered in the first form which is in app 1.
I am pasting a bit of my code for you to understand it more clearly with some screenshots.
<form method="POST" action="/reservation/home/">
{% csrf_token %}
<div class="form-group">
<label for="exampleFormControlInput1">Radio Serial Number</label>
<input type="text" class="form-control" id="exampleFormControlInput1" name= "sno"
placeholder="S/N123ABC123" required >
</div>
<button type="submit" class="btn btn-primary"> Submit </button>
</form>
views.py of new app.
def reserve(request):
if request.method == "POST":
sno = request.POST.get('sno')
date_req = request.POST.get('date_req')
reserve = Reserve( sno=sno, date_req=date_req )
reserve.save()
return render(request, 'home.html')
models.py of new app.
from django.db import models
# Create your models here.
class Reserve(models.Model):
sno = models.CharField(max_length=100)
date_req = models.DateField()
def __str__(self):
return self.sno
I want it to accept the serial number which got input by another form and validate it.
If the new serial number is not same as the database entry in previous form , It should display some error message that it is not found or not valid.
If it is valid it should accept that serial number and the entry should be done in new form.
I have provided the name and id as "sno"
I am not sure how to get any documentation or any video regarding this.
Any help would be highly appreciated.
In case you need more of information, please drop a comment or check my github repository : https://github.com/samatharkar/altiostar/tree/reserve-tool/inventory/reservation_app

Is there a way to extract data from django templates except the POST method

In one of the pages of my website i m trying to create two buttons save and delete. Save as the name suggests saves the data filled into form in my database. Delete deletes this data. I want to access these two buttons separately in my views.py file but the only way i know to detect user input is checking if request.method == 'POST'. But in the case of both the save and delete button POST request is going to be made. How can i differentiate between the click of delete and save button so that i can write different code for each?
Use the name tag in the button to differentiate between POST operations.
For example:
<button name="delete">Delete</button>
And use in condition in view:
if "delete" in request.POST:
Use two separated form, and submit them by ajax seems the easiest way.
view.py
Create 2 views. One for add/update data, and second one for delete data.
def submit_view(...):
if request.POST:
# add data (if form.is_valid, and more)
def delete_view(...):
if request.POST:
# delete data (if form.is_valid, and more)
template
Now add two separated forms in template, and submit them by using ajax.
<form action="/submit" id="submit_form">
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="button" value="submit" id="submit_button">
</form>
<form action="/delete" id="delete_form">
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="button" value="delete" id="delete_button">
</form>
<script>
$('#submit_button').on('click',function(){$('#submit_form').submit();});
$('#delete_button').on('click',function(){$('#delete_form').submit();});
</script>

How can I get a Django view.py to request a selected posts information such as primary key?

I have a Django project with an HTML file that lists all of the CSV files that have been uploaded to my Postgresql database and when you click on the CSV of interest a new page is rendered with the CSV model's basic information (name/time submitted).
This is the First Page:
{% for csv in Data_List %}
<button class="btn btn-primary" style = "font-size:1.2em;" >{{csv.name}}</button>
<br><br>
{% endfor %}
This is the second page:
<p>{{request.user.username}}'s Note
<h6>{{worklog.name}}
<br>
{{worklog.date}}
<br>
{{worklog.notes|safe}}
<br>
{{worklog.mycsv|safe}}
</h6>
</p>
However, my goal is that when you click the button a python VIEW will be passed (or just retrieve) the chosen posts primary key (or other information). I want to do this so the view can ask the database for the actual CSV and do some work.
How can I get a view.py to request a selected posts information such as primary key?
Thanks and Happy Coding
#The url
url(r'^anote/(?P<pk>\d+)$', views.A_Note, name = 'anote'),
#The view
def A_Note(request, pk):
#the rest of code here
return render(request, "some.html", {"thing":thing, "pk":pk, "etc":etc})
I learned that sharp brackets <> in a url passes the value through to the view where it can then be accessed as an argument when defining the view. From there it can easily be used in the code.
Thanks!

Transferring front end data from HTML checkboxes to backend django in forms.py/views.py/urls.py

I have a bunch of checkboxes on my HTML page and want to store whether a checkbox was ticked or not in backend django. My current HTML code is:
<input type="checkbox" name="activism" value="Yes">Activism & advocacy
I don't know how to modify my forms.py/urls.py/views.py to store whether a particular checkbox was ticked or not. Thank you very much.
There you are, it's not the best way to. Since you are new to django, this will work. Alongside you're learning, take the django documentation as guide
<form action='url' method='post'> {% csrf_token %}
<input type="checkbox" name="activism" value="Yes">Activism & advocacy
<input type='submit' value="submit" />
</form>
python view
def viewName(request):
if request.method == 'POST':
# You have access to data inside request.POST
activism = request.POST.get('activism')
if activism:
pass # Activism is checked

How can I access the form submit button value in Django?

I have a Django project that, on one page, has multiple forms (in different tags) that can be submitted to have different effects. In all cases I want the user to be redirected back to the same page, so I use in my view the pattern of submitting the form and then redirecting to the original page. In at least one case, the only difference between two of the forms is the value of the submit button.
In my view I have the code (which is the first time my view function accesses the request.POST):
if request.POST['submit']=='Add':
#code to deal with the "Add" form
and in the template, the first form has a submit button like
<input type="submit" value="Add">
I thought this would work, but when I submit that form, I get an error at the line in view from above:
Key 'submit' not found in <QueryDict: {u'clientyear': [u'2012'], u'csrfmiddlewaretoken': [u'be1f2f051f09f6ab0375fdf76cf6a4d7'], u'ben': [u'123405']}>
Obviously, this does not have a 'submit' key or any key with the value corresponding to the submit button I clicked. So, since this does not work, how can access the value of the submit button or tell which of the forms has been submitted?
Submit is an HTML Form structure... You must use name attribute of form objects as follows... In your template:
<form>
...
<input type="submit" name="list" value="List Objects" />
</form>
<form>
...
<input type="submit" name="do-something-else" value="Do Something Else" />
</form>
In your view:
if 'list' in request.POST:
# do some listing...
elif 'do-something-else' in request.POST:
# do something else
One thing to keep in mind to prevent confusion. The name of the submit button will not show if there is only a single button in the form.
#template.html
<form action="..." method="post">
<input type="submit" name = "first_button" value="Add">
</form>
#view.py
...
'first_button' in request.POST #False
#template.html
<form action="..." method="post">
<input type="submit" name = "first_button" value="Add">
<input type="submit" name = "second_button" value="Remove">
</form>
#view.py
...
'first_button' in request.POST #True if you clicked on that button
I'm little bit late but here is the solution
Problem you are facing
Your are trying to get Button name but getting the initial value of button that is not correct way.
HTML Code
<input type="submit" value="Add">
Python Code/View.py
if request.POST['submit']=='Add':
#code to deal with the "Add" form
Solution
First find button name in request.POST dictionary if exist then get their value.
HTML Code
Add name of your button and their value.
<input type="submit" value="Add" name="add_object">
Views.py
You can find the button name in request.POST dictionary
if request.POST['submit'] == 'add_object':
# Both ways to deal with it
if 'add_object' in request.POST:
Extra Stuff
We have two forms on a page.
First form have 2 buttons with same name subjects but different values fav_HTML and fav_CSS.
Second form also have 2 buttons with same name tutorials but different values
Tutorials_HTML and Tutorials_CSS.
<form action="" method="post">
Form 1
<button name="subject" type="submit" value="interview_HTML">HTML</button>
<button name="subject" type="submit" value="interview_CSS">CSS</button>
</form>
<form action="" method="post">
Form 2
<button name="tutorials" type="submit" value="Tutorials_HTML">HTML</button>
<button name="tutorials" type="submit" value="Tutorials_CSS">CSS</button>
</form>
views.py
We can handle different forms, check which button is clicked then getting their values and do something.
if 'subject' in request.POST: # this section handle subject form (1st Form)
#now we can check which button is clicked
# Form 1 is submitted , button value is subject now getting their value
if 'interview_HTML' == request.POST.get('subject'):
pass
# do something with interview_HTML button is clicked
elif 'interview_CSS' == request.POST.get('subject'):
pass
# do something with interview_CSS button is clicked
elif 'tutorials' in request.POST: #this section handle tutorials form (2nd form)
#now we can check which button is clicked
# Form 1 is submitted , button name is tutorials now getting their value
if 'Tutorials_HTML' == request.POST.get('tutorials'):
pass
# do something with fav_HTML button is clicked
elif 'Tutorials_CSS' == request.POST.get('tutorials'):
pass
# do something with fav_CSS button is clicked

Categories

Resources