How to get value of <option> in django view?

Viewed 24

I have form with option to choose which country are you coming from. In my model I've got country_living field with choices:

LIVING_COUNTRIES = [
    ('AFGANISTAN', 'Afganistan'),
    ('ALBANIA', 'Albania'),
    ('ALGERIA', 'Algeria'),
    ('ANGORRA', 'Andorra'),
    ('ANGOLA', 'Angola')]

class Employee(models.Model):
    user                =               models.OneToOneField(User, on_delete = models.CASCADE, primary_key = True)
    first_name          =               models.CharField(max_length=100, blank=True)
    last_name           =               models.CharField(max_length=100, blank=True)
    username            =               models.CharField(max_length=30, blank=True)
    email               =               models.EmailField(max_length=140, blank=True)
    date_of_birth       =               models.DateField(blank=True, default='1929-11-11')
    education           =               models.CharField(max_length=50, blank=True)
    country_living      =               models.CharField(max_length=50, choices=LIVING_COUNTRIES, default='AFGANISTAN', blank=True)
    created_at          =               models.DateTimeField(auto_now_add=True, blank=True)
    password            =               models.CharField(max_length=30, null=True)

In my class-based view I get those fields like:

    def get(self, request):

        employees = models.Employee.objects.all()
        living_countries_list = LIVING_COUNTRIES
        context = {
            'employees': employees,
            'living_countries_list': living_countries_list
        }
        return render(request, 'authentication/employee_register.html', context)

and my html:

<select name="country" id="id_category">
    {% for each in living_countries_list %}
       <option value="{{ each.0 }}" class="living_countries">{{ each.1 }}</option>
    {% endfor %}
 </select>

In my post method I get option and check if it exists

country = request.POST.get('coutry')
if not country:
     print('no country')
     context['has_error'] = True
     print(country)

Problem is even if country is selected when I click submit button I can't get value of it

Thanks for help:)

1 Answers

I think the error in request.POST.get('coutry) that should be request.POST.get('country).

Why it does not give a value, because request.POST.get return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError. So in ur case u wrong type in variabel name, so it give None value to country.

And some insight how to use request.POST.get (What does request.POST.get method return in Django?)

and i recomment to add print(request.POST) in view to see actual data post in terminal for debugging.

# you can add here
print(request.POST)

country = request.POST.get('coutry')
if not country:
     print('no country')
     context['has_error'] = True
     print(country)

Related