Written Written - 5 months ago 17
HTML Question

Why is my Django form template removing all data after a space?

I am using a Django Form to validate a specific sign up page. The Form is set up as so:

class MemberForm(forms.Form):
email = forms.EmailField(label='Email', required=True)
password = forms.RegexField(label='Password', widget=forms.PasswordInput, required=True, regex=r'^(?=.*[A-Za-z])(?=.*\d)[\S]{8,}$')
confirm_password = forms.CharField(label='Confirm Password', widget=forms.PasswordInput, required=True)
full_name = forms.CharField(label='Full Name', required=True)
pref_name = forms.CharField(label='Preferred Name', required=False)
phone = forms.RegexField(label='Phone', regex=r'^\+?1?\d{9,15}$', required=True)
address = forms.CharField(label='Address', required=True)
city = forms.CharField(label='City', required=True)
provinces = forms.ChoiceField(label='Provinces', choices=PROVINCE_CHOICES, required=True)
postal_code = forms.RegexField(label='Postal Code', regex=r'^([A-Z][0-9][A-Z]\s[0-9][A-Z][0-9])$')
dob = forms.DateField(label='Birthday', required=True)
occupation = forms.CharField(label='Occupation', required=True)

Everything is working fine in this regard, the form accepts everything it should and rejects everything it should. If the form is invalid, I render it again. This is all done in the following view:

def create_member(request):
form = forms.MemberForm(request.POST or None)

if request.method == 'POST':
if form.is_valid():

provinces = Provinces.objects.all()
return render(request, 'party/adminCreateAccount2.html', {'form': form, 'provinces': provinces, 'today': str(now_date())})

So, if the form is not valid, I simply stay on the page and reuse the current form. However, when the form reloads, for some reason, all data that has a space will erase everything after the space when it is shown.

For example, if I use 'Test Test' as my full name, then leave everything else blank, when the page reloads, I will only see 'Test'.

My form is displayed using the following custom template:

{% for field in form %}
<div class="form-row grp-row grp-cells-1 {{ field.html_name }}">
<div class="field-box l-2c-fluid l-d-4">
<div class="c-1">
<label {% if field.field.required %} class="required" {% endif %} for={{ field.html_name }}>{{ field.label }}</label>

<div class="c-2">
<input class="vTextField" type="text" name={{ field.html_name }} id={{ field.html_name }} value={{ field.data|default_if_none:"" }}>
{% endfor %}

I tried outputting
{{ field.data|default_if_none:"" }}
right beside the input and it displayed the entire string ('Test test' in our example) so I am completely stumped because I know the correct data is getting passed through. Any idea why its being changed for the input value?


Django is not doing this, your browser is. You need to put the value variable in quotes:

value="{{ field.data|default_if_none:"" }}"

But really, your shouldn't output fields like this: use Django to do it properly, with just {{ field }}.