1đź‘Ť
âś…
Method 1: Separate Forms
class GenericContentForm(forms.ModelForm):
class Meta:
exclude = ('subject', 'subject_name', 'file_creation_time', 'file_uploaded_by')
TYPE_CHOICES = (
('homework', 'Homework'),
('class', 'Class Paper'),
('random', 'Random Paper'),
)
type = forms.ChoiceField(choices=TYPE_CHOICES)
class HomeworkForm(GenericContentForm):
class Meta(GenericContentForm.Meta):
model = Homework
class ClassPaperForm(GenericContentForm):
class Meta(GenericContentForm.Meta):
model = ClassPaper
class RandomPaperForm(GenericContentForm):
class Meta(GenericContentForm.Meta):
model = RandomPaper
Then in your view you just pick one to start with, and when you have the POST data, you can instantiate a different one instead:
def my_view(request):
if request.method == 'POST':
type = request.POST.get('type')
if type == 'homework':
form = HomeworkForm(request.POST)
elif type == 'class':
form = ClassPaperForm(request.POST)
elif type == 'random':
form = RandomPaperForm(request.POST)
else:
form = HomeworkForm()
...
Method 2: Use Proxy Models
Since these three models all share the same data, having three separate tables is redundant. Instead of FileDescription
being abstract, make it just a normal standard model, and add a field to it for type, with choices of “Homework”, “Class Paper” and “Random Paper”. Then create proxy models for each:
class HomeworkManager(models.Manager):
def get_query_set(self, *args, **kwargs):
qs = super(HomeworkManager, self).get_query_set(*args, **kwargs)
return qs.filter(type='homework')
class Homework(FileDescription):
class Meta:
proxy = True
objects = HomeworkManager()
def save(self, *args, **kwargs):
self.type = 'homework'
super(Homework, self).save(*args, **kwargs)
Then, you just need one form for FileDescription
and when the user’s choice for the “type” will be saved. You can then access anything set as type “homework” with the standard Homework.objects.all()
.
👤Chris Pratt
Source:stackexchange.com