pythondjangodjango-formsdjango-countries

django_countries does not display in the form on template


I used {{ form }} as seen here

template.html

<h4>Change your details</h4><br>

<form id="edit_form" method='post'>

    {% csrf_token %}

    {{ form }}

    <div class='section group'>
        <input id="update_details_button" type='submit' class='btn btn-primary wide' value='Change'/>
    </div>

</form>

views.py

def user_view(request, is_admin):
    user = request.user

    form = myForm()

    if request.method == 'POST' and is_admin:
        form = myForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data

            user.name = data['name']
            user.country = data['country']
            user.save()

            messages.success(request, 'You have successfully updated your details.')

    return render(request, 'mysite/user.html', {
        'user': user,
        'is_admin': is_admin,
        'form': form,
    })

My form is as followed

class myForm(forms.Form):
    name = forms.CharField(
        label="Name",
        widget=forms.TextInput(attrs={'placeholder': 'Name'}))
    country = CountryField(blank_label='(select country)')

    def __init__(self, *args, **kwargs):
        super(myForm, self).__init__(*args, **kwargs)

The name field displayed fine on the page but there's no sign of the CountryField, could someone point out the error? The code compiled fine and gives no error while server is running.


Solution

  • CountryField is a model field, not a form field. You're supposed to add it to your user model, in which case a modelform based on that model will automatically generate a country field. Since it looks like you have actually added a field called country to the User model, that's where you should be using CountryField.

    However, for reference, to do it manually on a non-model form is slightly more complicated:

    from django_countries import widgets, countries
    
    class myForm(forms.Form):
        country = forms.ChoiceField(widget=CountrySelectWidget, choices=countries)