How to get value from form field in django framework?
Using a form in a view pretty much explains it.
The standard pattern for processing a form in a view looks like this:
def contact(request):
if request.method == 'POST': # If the form has been submitted...
form = ContactForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
# Process the data in form.cleaned_data
# ...
print form.cleaned_data['my_form_field_name']
return HttpResponseRedirect('/thanks/') # Redirect after POST
else:
form = ContactForm() # An unbound form
return render_to_response('contact.html', {
'form': form,
})
How to get value from form and redirect to /value in Django 1.10
form.cleaned_data
comes from form.is_valid()
, so you sould change your views.py
like this:
def index(request):
[...]
if request.method == 'POST':
form = ApartmentForm(request.POST or None)
if form.is_valid():
[...]
id = form.cleaned_data.get('id', None)
return redirect(id)
How do I get the values from input text fields from my custom form through the request: Django 3.0?
Your mistakes:
item_description(item_name=data.item_name, item_number=data.item_number, item_quantity=data.item_quantity)
data
is aQueryDict
, so you must access the data in it usingdata['item_name']
ordata.get('item_name')
as you would for a regulardict
.item_description(...)
doesn't actually do anything. It does not save anything to the database. To save to the database, you must useitem_description.objects.create(...)
.
Other problems with your code:
- you render the form fields on your own
- you extract the POST data on your own
- you attempt to save to the database on your own
- you are missing input validation (what if some required values are missing? e.g. what if
item_name
is not submitted?) - you did not provide a suitable error message as feedback to the user if he/she enters inappropriate values (e.g. a string of length 201).
Django's ModelForm
is able to handle all of these issues, so please use ModelForm
instead.
If models.py
is this:
from django.db import models
class ItemDescription(models.Model):
item_name = models.CharField(max_length=200)
item_number = models.CharField(max_length=200)
item_quantity = models.CharField(max_length=200)
def __str__(self):
return self.item_name
Then, create a ModelForm
in forms.py
:
from django import forms
from .models import ItemDescription
class ItemDescriptioneForm(forms.ModelForm):
class Meta:
model = ItemDescription
fields = ['item_name', 'item_number', 'item_quantity']
In your views.py
, use the ModelForm
you just created:
from django.shortcuts import render, redirect
from .forms import ItemDescriptionForm
def addItem(request):
if request.method == 'POST':
form = ItemDescriptionForm(request.POST)
if form.is_valid():
form.save()
return redirect('Items-list')
else:
form = ItemDescriptionForm()
return render(request, 'ims/addItemForm.html', {
'form': form,
})
Show the form in your template:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Item</title>
</head>
<body>
<form action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" />
</form>
</body>
</html>
Cannot set a field value of a Django form in views
You can set the .user
attribute of the .instance
wrapped in the form:
@login_required(login_url='todo:login')
def task_add(request):
if request.method == 'POST':
task_form = AddTask(request.POST)
if task_form.is_valid():
task_form.instance.user = request.user
task_form.save()
return redirect('todo:index')
return render(request,'todo/task_add.html')
How do I display the value of a Django form field in a template?
The solution proposed by Jens is correct.
However, it turns out that if you initialize your ModelForm with an instance (example below) django will not populate the data:
def your_view(request):
if request.method == 'POST':
form = UserDetailsForm(request.POST)
if form.is_valid():
# some code here
else:
form = UserDetailsForm(instance=request.user)
So, I made my own ModelForm base class that populates the initial data:
from django import forms
class BaseModelForm(forms.ModelForm):
"""
Subclass of `forms.ModelForm` that makes sure the initial values
are present in the form data, so you don't have to send all old values
for the form to actually validate.
"""
def merge_from_initial(self):
filt = lambda v: v not in self.data.keys()
for field in filter(filt, getattr(self.Meta, 'fields', ())):
self.data[field] = self.initial.get(field, None)
Then, the simple view example looks like this:
def your_view(request): if request.method == 'POST':
form = UserDetailsForm(request.POST)
if form.is_valid():
# some code here
else:
form = UserDetailsForm(instance=request.user)
form.merge_from_initial()
How can I get custom form field value from within Django Admin's response_change?
If you add a name
to your <textarea>
you will be able to retrieve the contents on the server side. Without a name
, the data is not being sent to the server (Django).
So something like this:
<textarea
placeholder="If you find necessary, provide information on the reasons that led to the rejection of the suggestion"
id="decline-reasons" name="decline-reasons" class="vLargeTextField" rows="5"></textarea>
Should allow you to retrieve the text on the Django side with request.POST["decline-reasons"]
.
Django: Set a dropdown form field to a value from the current detail view's Model
Found the answer after posting. For anyone else looking for the answer.
When creating a new form instance (in my case within the get_context_data of my detail view class) use the initial parameter:
context['change_stage_form'] = ChangeStageForm(initial={
'assessment_stage': self.object.assessment_stage
})
Django Forms Docs: https://docs.djangoproject.com/en/dev/ref/forms/api/#initial-form-values
Thank you to: https://stackoverflow.com/a/813474/16395136
How set example of value in input box of django form
The way to do this is to use Django Forms' widget
properties. Here, you can change the HTML that will be rendered client-side.
class YourForm(ModelForm):
class Meta:
model = YourModel
fields = ('your', 'fields')
widgets = {
'form_field': forms.TextInput(attrs={'placeholder': "Search Content..."}
}
The above code will render an input
tag for the field form_field
, and add an HTML attribute of placeholder
with the value of Search Content...
Related Topics
Python - Using the Multiply Operator to Create Copies of Objects in Lists
Pymongo Keeps Refusing the Connection at 27017
Printing a List Separated with Commas, Without a Trailing Comma
Python Argparse Conditionally Required Arguments
How to Sort a Pandas Dataframe by Index
How to Write Strategy Pattern in Python Differently Than Example in Wikipedia
Matplotlib: Draw Grid Lines Behind Other Graph Elements
Numpy to Tfrecords: Is There a More Simple Way to Handle Batch Inputs from Tfrecords
@Csrf_Exempt Does Not Work on Generic View Based Class
How to Remove Leading Whitespace in Python
"Private" (Implementation) Class in Python
How to Merge Multiple Lists into One List in Python
How to Merge Images into a Canvas Using Pil/Pillow
Python Command Line Input in a Process
How to Create a Decorator That Can Be Used Either with or Without Parameters