Save HTML Form Data To Database - Django - python

I want to update database values by HTML Forms
HTML form :
<form action="/school_manager/students/{{student.id}}/update/" method="post" accept-charset="utf-8">
{% csrf_token %}
<label for="update_name">Edit Name :</label><br/>
<input type="text" name="update_name" id="update_name" placeholder="Enter A Name" />
<input type="submit" value="Update"/>
</form>
views.py :
def update_student_detail(request, student_id):
list = get_object_or_404 ( student, pk=student_id)
if request.method == 'POST' :
student.First_Name = request.POST.get('update_name','')
list.save()
return HttpResponseRedirect('/school_manager/students/' + student_id)
When I run the program and type a word in text box, after submit it does not work. I can't see any change to my database.

I found my fault
in views.py calling student for change database values is wrong
When we created a list of database tuple, values can edit by using that list
def update_student_detail(request, student_id):
list = get_object_or_404 ( student, pk=student_id)
if request.method == 'POST' :
list.First_Name = request.POST.get('update_name','')
list.save()
return HttpResponseRedirect('/school_manager/students/' + student_id)

Related

Django MultiValueDictKeyError Passing input type file

I am getting this error when I am trying to pass the value of the folder to another html.
I have stored the form in a database in DB Browser Sqlite. I am trying to pass the input type = file to another HTML. So that when I view the existing type = file, the file will automatically be shown.
Below is an attachment from submitclaim.html
<form action="/newclaim/" method="post" enctype="multipart/form-data">
<label for="receipt">Receipt: </label> <br>
<input id="receipt" type="file" name="receipt_field">
</form>
This is my verfiyexistingclaims.html
<form method="POST" action="/verifyexistingclaims/{{claims.id}}" enctype="multipart/form-data">
<label for="receipt">Receipt: </label>
<input id="receipt" type="file" name="receipt" value={{claims.receipt}}>
</form>
This is my views.py
def financeverifyclaims(request, id):
context = initialize_context(request)
user = context["user"]
# get original object
claims = SaveClaimForm.objects.get(id=id)
if request.method == "POST":
# update original object
claims.receipt = request.FILES["receipt"]
# save it with original `ID`
claims.save()
return render(
request, "Login/verifyexistingclaims.html", {"claims": claims, "user": user}
)
Models.py
from django.db import models
from django.core.validators import FileExtensionValidator
# Create your models here.
class SaveClaimForm(models.Model):
receipt = models.FileField(upload_to='receipts/%Y/%m/%D', validators=[FileExtensionValidator(allowed_extensions=['jpg','png'])])
You should provide a default value in case it does not exist, i.e.:
claims.receipt = request.FILES.get('receipt', False)

Element of my django forms.py is not defined?

I've got a problem with django with handling forms : I created a form with 2 fields, and I associated it to my view, but it tells me that my fields are undefined. Could you explain me please ?
I created a form in my index.html :
<form action="/addUser" method="post">
{% csrf_token %}
<label> Name of the Employee : <input type="text" name="employeeName", id="employeeName"/> </label>
<label> Email of the Employee : <input type="email" name="employeeEmail", id="employeeEmail" /> </label>
<button class="btn btn-primary" type="submit">Add User</button>
</form>
Then I created in views.py
def addUser(request):
if request.method == 'POST':
form = CreationUserForm(request.POST)
newEmployee = Employee()
newEmployee.name = form[employeeName]
newEmployee.email = form[employeeEmail]
newEmployee.save()
return HttpResponseRedirect(reverse('app:home'))
And then I created in forms.py
class CreationUserForm(forms.Form):
employeeName = forms.CharField(label='employeeName', max_length=254)
employeeEmail = forms.CharField(label='employeeEmail', max_length=254)
So I don't understand why I get this error : name 'employeeName' is not defined
For my point of view it is...
I tried with form.employeeName too, but it considered as a non existant attribute.
Thank you for helping :)
In your addUser method, both the employeeName and employeeEmail are variables, which are not defined. You want to be accessing the keys via the strings.
def addUser(request):
if request.method == 'POST':
form = CreationUserForm(request.POST)
newEmployee = Employee()
newEmployee.name = form['employeeName']
newEmployee.email = form['employeeEmail']
newEmployee.save()
return HttpResponseRedirect(reverse('app:home'))
also a Django suggestion - before accessing the attributes of the form, it is often useful to check that the input is valid by calling if form.is_valid() as defined here: https://docs.djangoproject.com/en/2.2/ref/forms/api/

How to get select field text from html form in django?

I have created a form with select field in template ehrinfo.html
<form action="{% url 'ehrs:compcreate' %}" method="GET">
<select>
<option value="Vital Signs">Vital Signs</option>
<option value="Cancer Signs">Cancer Signs</option>
</select><br><br>
<input type="submit" value="Select Template" class="addehr">
</form>
I have defined form class as:
class templateselect(forms.Form):
CHOICES = (
('Vital Signs', 'Vital Signs'),
('Cancer Signs', 'Cancer Signs'),
)
template = forms.ChoiceField(widget=forms.Select, choices=CHOICES)
Now I want to get selected text from this form in view compcreate. So I used:
def compcreate(request):
if request.method == 'GET':
form = templateselect(request.GET)
print("a")
if form.is_valid():
print("b")
template = str(form.cleaned_data["template"])
but it cant get past the if form.is_valid(): part as 'a' is printed but 'b' is not printed on console. What is the problem? How can I get the selected text in compcreate()?
The proper way to render your form would be to pass it in to your template via the context object and change your template. For example:
<form action="{% url 'ehrs:compcreate' %}" method="GET">
{{ form.as_p }}<br><br>
<input type="submit" value="Select Template" class="addehr">
</form>
If you want to stick with your current setup, looking at the html produced by the previous solution suggests that adding a name (equal to the name of your field in the Form class declaration) to your select field should also work:
<form action="{% url 'ehrs:compcreate' %}" method="GET">
<select name="template">
<option value="Vital Signs">Vital Signs</option>
<option value="Cancer Signs">Cancer Signs</option>
</select><br><br>
<input type="submit" value="Select Template" class="addehr">
This approach works with ModelForm and POST request:
def compcreate(request):
if request.method == 'POST':
form = templateselect(request.POST)
if form.is_valid():
ts = form.save(commit=False)
print(ts.template)
Let me know if it works in your case.

Django, form is_valid() is always false

I'm learning Django and have some troubles with forms. I try to create a simple form where I type a name and show it on another page. But is_valid() always returns false. Please, help me to find my error
forms.py
from django import forms
class OrderForm(forms.Form):
user=forms.CharField(max_length=100)
views.py
def order(request):
return render(request, 'myapp/order.html', {})
def contact(request):
username='not logged'
if request.method == 'POST' :
form=OrderForm(request.POST)
if form.is_valid():
username=form.cleaned_data['username']
else:
username='not worked'
else:
form=OrderForm()
return render(request, 'myapp/contacts.html', {'username':username})
order.html
<form name = "form" action = "{% url 'contact' %}" method = "POST" >
{% csrf_token %}
<input type="text" name="username" placeholder="Name">
<button type="submit">Login</button>
</form>
contacts.html
You are : <strong>{{ username }}</strong>
Your form control has the name username in HTML, while your form's field is named user in Django. Thus, nothing is set in the form field.
Normally you'd put the form into the context and then render it either as {{ form }} or the like, or render each field, rather than build your own form controls. The docs show how: https://docs.djangoproject.com/en/1.10/topics/forms/#working-with-form-templates
views.py
from forms import OrderForm
def order(request):
form = OrderForm()
return render(request, 'myapp/order.html', {"form" : form})
order.html
<form name = "form" action = "{% url 'contact' %}" method = "POST" >
{% csrf_token %}
{{form.as_p}}
<button type="submit">Login</button>
</form>
At the time of rendering template {{form.as_p}} looks like
<p><label for="id_username">Username:</label>
<input id="id_username" type="text" name="username" maxlength="100" required /></p>

save values in database using django

i have an custom form , whenever i fetch the form values to save in the database than it display an error ( applicationform() got an unexpected keyword argument 'job_title' ) and the values are not save in the table.
views.py :-
def applicationvalue(request):
if request.method == 'POST':
getjobtitle = request.POST['jobtitle']
getintable = applicationform(job_title=getjobtitle)
getintable.save()
print getjobtitle
return HttpResponse(getintable)
else:
return render_to_response('registration/applicationform.html')
my form is :-
<form method="POST" action="#" class="form-horizontal" id="applicationform" name="appform">
<input type="text" id="u_jobtitle" class="input-xlarge" name="jobtitle" value=" " />
<button class="btn btn-gebo" type="submit" name="usubmit">Save changes</button>
whenever i fetch the values from form to save the values in table field " job_title " than it will display an error :-
applicationform() got an unexpected keyword argument 'job_title'
Change input field name to job_title in your html
<input name="job_title" type="text" id="u_jobtitle" class="input-xlarge" value=" " />
-------------^ changed
and then in view do
def applicationvalue(request):
if request.method == 'POST':
#Dont need this
#getjobtitle = request.POST['jobtitle']
#---------------------------Use request.POST
getintable = applicationform(request.POST)
getintable.save()
print getjobtitle
return HttpResponse(getintable)
else:
return render_to_response('registration/applicationform.html')
It will be better if you use same form to render html instead of hand coding it.
The applicationform constructor should take the request.POST as argument.
But it seems to me that you are not using django forms in the "right" way. I think that your view doesn't follow the django philosophy for using form.
In your case, you should have a model:
from django.db import models
class Application(models.Model):
job_title = models.CharField(max_length=100)
Based on this model, you can declare a ModelForm:
from django import forms
from .models import ApplicationModel
class ApplicationForm(forms.ModelForm):
class Meta:
model = ApplicationModel
fields = ('job_title',)
Then you can use this form in your view
def applicationvalue(request):
if request.method == 'POST':
form = ApplicationForm(request.POST)
if form.is_valid():
#This is called when the form fields are ok and we can create the object
application_object = form.save()
return HttpResponse("Some HTML code") # or HttResponseRedirect("/any_url")
else:
form = ApplicationForm()
#This called when we need to display the form: get or error in form fields
return render_to_response('registration/applicationform.html', {'form': form})
finally you should have a registration/applicationform.html template with something like:
{% extends "base.html" %}
{% block content %}
<form action="" method="post">{% csrf_token %}
<table>
{{form.as_table}}
</table>
<input type="submit" value="Add">
</form>
{% endblock %}
I hope it helps

Categories

Resources