I am making an app, and I need to set the default value of a textarea
in a form as a field inside a model.
This is what my form looks like:
class SaveNotes(forms.Form):
notes = forms.CharField(widget=forms.Textarea(attrs={
'class' : 'textarea has-fixed-size',
'style' : 'height: 50%; margin-bottom: 1%',
'placeholder' : 'might start limiting my spending...',
}))
and here is the view for the webpage:
def spaceDashboard(request, id):
template = "spaces/dashboard.html"
accessDeniedTemplate = "errors/403.html"
space = get_object_or_404(Space, pk=id)
recordsFormClass = RecordForm
bardRequestsFormClass = BardRequests
saveNotesFormClass = SaveNotes
deleteUrl = "delete/%s" % space.id
recordsUrl = "%s/records" % space.id
if request.method == "POST":
recordsForm = recordsFormClass(request.POST)
bardRequests = bardRequestsFormClass(request.POST)
saveNotesForm = saveNotesFormClass(request.POST)
if saveNotesForm.is_valid():
notes = saveNotesForm.cleaned_data["notes"]
space["notes"] = notes
space.save()
if recordsForm.is_valid():
data = recordsForm.cleaned_data
new = Record(amount=data["amount"], memo=data["memo"])
new.save()
space.records.add(new)
space.balance = space.calculateBalance()
print(space.balance)
messages.info(request, "Record has been added successfully.")
if bardRequests.is_valid():
data = bardRequests.cleaned_data
response = bard_requests.askQuestion(data["request"])
return HttpResponse(response)
if request.user.is_authenticated:
if request.user.username == space.owner.username or space.owner == None:
return render(request, template, context={
"space" : space,
"goalPercentage" : (space.calculateBalance()/(space.goal/100)),
"recordsForm" : recordsFormClass,
"bardRequestsForm" : bardRequestsFormClass,
"saveNotesForm" : saveNotesFormClass,
"recordsCount" : len(space.records.all()),
"deleteUrl" : deleteUrl,
"recordsUrl" : recordsUrl,
})
else:
return render(request, accessDeniedTemplate)
else:
return redirect("/login")
Is there a way to pass an argument to the form and make that the default value of the textarea
? Does anyone know how to do what I am trying to do?
There is two way's pass initial
(default value) in form input
class SaveNotes(forms.Form):
def __init__(self, *args, **kwargs):
super(SaveNotes, self).__init__(*args, **kwargs)
self.fields['notes'].initial = 'Default input'
notes = forms.CharField(widget=forms.Textarea(attrs={
'class' : 'textarea has-fixed-size',
'style' : 'height: 50%; margin-bottom: 1%',
'placeholder' : 'might start limiting my spending...',
}))
def DemoView(request):
form = SaveNotes(initial={'notes':'default value'})
context = {'form':form}
return render(request,'index.html',context)
<div class="container p-5">
<div class="row mx-auto">
<div class="col-6">
{{form.notes.label_tag}} <br>
{{form.notes}}
</div>
</div>
</div>
NOTE - if you pass both side, Django template render value of the views first