简体   繁体   中英

Conditionally Show Form Elements in Django

I'm working on a small Django project and for a form, i want to capture the details of the person signing in. There is a radio option which has the values ' Student ' or ' Industry '. If Student is chosen, I want two input boxes to be shown, one for ' graduating year ' and other for ' university name '. If ' Industry ' is chosen I want 2 text boxes, one for ' Company name ' other for ' Job title '.

Right now, I'm able to get this working using jQuery to hide the un-needed text boxes and attaching a changelistener to the radiobuttons. However is there a django way of doing the same? Right now, my model has:

name - common for both cases student_or_industry - ChoiceField job_title company_name univeristy graduating_year

And my form is created using the simple ModelForm, which leads to loads of NULLs in the table. Should I be creating a different model for Student and Industry and linking these with a foreign key? If yes, how does this tie in with the forms? Do I create multiple forms?

Thanks in Advance

Breaking this into 2 seperate models (Student, Industry) would not be a problem, it would actually help you if you need in the future to add more fields to each individual model. Since a Person can only belong to 1 university or 1 Industry then your query is also combined with no much additional overhead. Your initial approach is not wrong as well, but you need to think if in the future you will need to add additional information to the related models, if for instance you need to add courses, or sectors then you start overloading your initial model.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM