bakarin
bakarin

Reputation: 652

Materialize css 'select' not working with django

I have this template that collects all names of authors from author_info model. These names are shown as a drop down list. When i pass the selected value to the view, it shows null. The template:

<select>
     <option value="" disabled selected>Choose author</option>
     {% for author in ainfo %}
          <option  value="{{author.name}}" name="author_name">{{author.name}}</option>
     {% endfor %}
</select>

The code snippet from views:

if request.method=="POST":

    author=request.POST.get('author_name')

Upvotes: 1

Views: 1584

Answers (2)

apet
apet

Reputation: 1098

You should initiate materialize select, to make selection possible:

<script>
    document.addEventListener('DOMContentLoaded', function() {
        var elems = document.querySelectorAll('select');
        var instances = M.FormSelect.init(elems);
    });
</script>

Upvotes: 0

Borut
Borut

Reputation: 3364

It's null, because you haven't named your select input. When you're trying to get author_name from request, Django is looking for input named author_name. There is none in your case. Delete name attribute from options and add appropriate name attribute to select.

<select name="author">
    <option value="" disabled selected>Choose author</option>
    {% for author in ainfo %}
    <option  value="{{author.name}}">{{author.name}}</option>
    {% endfor %}
</select>

and

author = request.POST.get('author')

Additionally, you could move input to forms.py and use it like any other form, validate selections etc.

class AuthorForm(forms.Form):

    author_choices = [
        (None, 'Choose author')
    ]

    authors = forms.ChoiceField()

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for author in YourAuthorModel.objects.all():
            author_choices.append((author.author_name, author.author_name))
        self.fields['authors'].widget.choices = author_choices

Upvotes: 4

Related Questions