Anuj TBE
Anuj TBE

Reputation: 9800

generate select field in django form using model

I'm writing a Django application and building the form manually.

<form method="post">
{% csrf_token %}

<input name="name" class="form-control">

<textarea name="description">

<select name="teaching_language">
    <option value="">Value 1</option>
</select>
</form>

my models.py contains

class TeachingLanguage(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    title = models.CharField(max_length=250)
    modified = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)

    class META:
        verbose_name_plural = 'teaching_languages'
        db_table = 'languages'

    def __str__(self):
        return self.title

class Course(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=250)
    teaching_language = models.ForeignKey(TeachingLanguage, on_delete=models.CASCADE)
    description = models.TextField(blank=True)

I have to fill <option> by the list of TeachingLanguage

The view.py file contains

class NewCourse(CreateView):
    model = Course
    fields = ['name', 'teaching_language', 'description']

    def get_context_data(self, **kwargs):
        context = super(NewCourse, self).get_context_data(**kwargs)
        teaching_languages = TeachingLanguage.objects.all()
        context['teaching_languages'] = teaching_languages
        return context

    def form_valid(self, form):
        form.instance.created_by = self.request.user
        form.save()

        return super().form_valid(form)

How to render the teaching_languages in select field to generate a dropdown list?

Upvotes: 0

Views: 567

Answers (2)

solarissmoke
solarissmoke

Reputation: 31404

If you must do it manually rather than just letting Django handle it, then you can simply iterate over the teaching languages that you've passed to the context:

<select name="teaching_language">
    {% for lang in teaching_languages %}
    <option value="{{ lang.pk }}">{{ lang }}</option>
    {% endfor %}
</select>

Upvotes: 0

Dan Lupascu
Dan Lupascu

Reputation: 307

Try this in your template:

<form method="post">
{% csrf_token %}

<input name="name" class="form-control">

<textarea name="description">

{{ form.teaching_languages }}
</form>

This will generate only the teaching_languages field from your form. Click here for more details.

Also you should remove the get_context_data method now because the form variable is passed to the template automatically and the form picks-up all the teaching languages automatically as they are set as Foreign Keys in the Course model.

Upvotes: 1

Related Questions