Aithusa
Aithusa

Reputation: 169

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.

Upvotes: 0

Views: 2745

Answers (3)

Abhi
Abhi

Reputation: 77

If you have installed django_country and it added in installed app than no need to make it from just use like this

{% load countries %}
 <select name="country">
  {% countries %}
   <option value="{{ code }}">{{ name }}</option>
  {% endcountries %}
 </select>

Upvotes: 0

Guillaume Lebreton
Guillaume Lebreton

Reputation: 2782

In fact it's simpler: https://pypi.org/project/django-countries/#custom-forms

from django_countries.fields import CountryField


class MyForm(forms.Form):
    country = CountryField(blank=True).formfield()

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599628

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)

Upvotes: 4

Related Questions