0

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.

Community
  • 1
  • 1
Hassan Baig
  • 15,055
  • 27
  • 102
  • 205
  • 1
    You should show the view. Did you try passing the `initial` argument to the form instantiation, as shown in the docs under ["dynamic initial values"](https://docs.djangoproject.com/en/1.9/ref/forms/api/#dynamic-initial-values)? And note that the last answer you link to shows you **exactly and precisely** what to do. – Daniel Roseman Feb 27 '16 at 18:56
  • Added the view (it's a CBV). I didn't set `initial`. I'm now seeing what I'm doing wrong. Should I over-ride the `def get_initial(self):` method with the FormView CBV to achieve this? – Hassan Baig Feb 27 '16 at 19:21
  • [Initial](https://docs.djangoproject.com/es/1.9/ref/forms/fields/#initial) is a keyword argument to a form field – Sayse Feb 27 '16 at 19:26
  • Yes, that is exactly what `get_initial` is for in a FormView. – Daniel Roseman Feb 27 '16 at 19:31

1 Answers1

2

I needed to over-ride def get_initial(self): of my FormView to achieve this. I.e. instead of passing a context variable to the template, pass the variable as initial through get_initial() to the related form.

Here's how I did it:

def get_initial(self):
    """
    Returns the initial data to use for forms on this view.
    """
    if self.request.user.is_authenticated():
        #What's the latest chatpicmessage which houses a pic you own
        try:
            msg = PicMessage.objects.filter(which_pic__owner=self.request.user).latest('sending_time')
            self.initial = {'mobile_number': msg.what_number} #initial needs to be passed a dictionary
            return self.initial
        except:
            return self.initial
    else:#i.e user is not authenticated
        return self.initial
    return self.initial

More documentation regarding this can be found here: https://docs.djangoproject.com/es/1.9/ref/forms/fields/#initial

Hassan Baig
  • 15,055
  • 27
  • 102
  • 205