Angela
Angela

Reputation: 11

Dynamic form choice/option field in django

I have made this web app https://notes12345.herokuapp.com

The code of this app is here: https://github.com/theparadoxer02/Notes

What is want is to make the search form in such a way that when user select the year the choices for branches get generated dynamically , means only that branch options should come that of selected year, when when one is done selecting the branch , then the options for subjects should come that are related to selected year,branch above. So in this way I want to generate form .

What should I learn? where should i modify file in views.py or models.py ? I am stuck with that .

Here is my model file:

year_choices = (
        ( 1  , 'First' ),
        ( 2  , 'Second'),
        ( 3  , 'Third' ),
        ( 4  , 'Fourth')
  )
branch_choices = (
        ( 'IT','IT'  ),
        ( 'EE','EE'  ),
        ( 'CSE','CSE'),
        ( 'EC','EC'  ),
        ( 'ME','ME'  ),
        ( 'CE','CE'  ),
  )


subject_choices = (
        ( 'DS' , 'Data Structure'  ),
        ( 'OS' , 'Operating sytem' ),
        ( 'EC' , 'Ecomomics'       ),
        ( 'Thermo' , 'Thermo'      ),
  )

def generate_picture_name(instance, filename):
    url = "images/{0}_{1}_{2}.jpg".format(
        instance.subjects.branch, instance.subjects.year, instance.unit_no)
    return url


class Subject(models.Model):
  name = models.CharField(max_length=20)
  no_of_units = models.IntegerField()
  year=models.IntegerField(choices=year_choices)
  branch=models.CharField(choices=branch_choices,max_length=15)

  def __str__(self):
      return self.name



class Note(models.Model):
  #unit_choices = ((1,'1'),(2,'2'),(3,'3'),(4,'4'),(5,'5'),(6,'6'),(7,'7'),(8,'8'),(9,'9'),(10,'10'))
  #branch = models.CharField(max_length=55,choices=branch_choices)
  #year = models.IntegerField(choices = year_choices)
  #subject_name = models.CharField(choices=subject_choices,max_length=10)
  subjects = models.ForeignKey(Subject,on_delete=models.CASCADE)
  unit_no = models.IntegerField()
  picture = models.ImageField(upload_to = generate_picture_name)

  def __str__(self):
return str(self.id)

Upvotes: 1

Views: 357

Answers (2)

Parul Dixit
Parul Dixit

Reputation: 364

You can easily do this using intercooler.js specifically by its dependent Select feature as mention in docs.

Upvotes: 1

codeape
codeape

Reputation: 100766

You have two options:

  • Either do everything server-side.

    • In that case split the search form in two django views.
    • First view, display a form with the year only. Submit the form to the second view (using <form action="url_for_second_view">
    • Second view, read the selected year, and respond with a form for the other options.
  • Or use javascript on the client to dynamically set the available options when the year changes.

Upvotes: 0

Related Questions