I have Django template which has one CharField
. Users can enter a mobile phone number here and submit it.
The view connected to this template sometimes passes to the said template, a context variable containing a pre-defined phone number {{ number }}
.
How do I auto-populate the CharField
in the Django template with {{ number }}
?
The template code is like so:
<form action="{% url 'user_phonenumber' slug=unique num=decision %}" method="POST">
{% csrf_token %}
<b style="font-size:90%;color:green;">Enter your mobile number:</b><br><br>
{{ form.mobile_number }}<br><br>
<input type="submit" name="number" value="OK"><br>
</form>
If required, forms.py contains the following:
class UserPhoneNumberForm(forms.Form):
mobile_number = forms.CharField(max_length=50)
class Meta:
fields = ("mobile_number")
In views.py, I simply have:
class UserPhoneNumberView(FormView):
form_class = UserPhoneNumberForm
template_name = "get_user_phonenumber.html"
def get_context_data(self, **kwargs):
context = super(UserPhoneNumberView, self).get_context_data(**kwargs)
if self.request.user.is_authenticated():
#some code to determine what number should be
context["number"] = number
return context
I've looked at a few other SO answers. The last one I've linked comes close to solving the problem, but the solution isn't for dynamic values (which is what I need), plus that's for modelforms. The rest don't quite address my particular needs.