I have a form in my website, which is the same for three tables (Homework, Class, Random)
So basically I want to make a ChoiceField on the top of the form, to let user choose where to upload file.
I was thinking, because these tables have common abstract class, may be I can choose it from there somehow. But can not figure out how.
Or may be there is much better solution for this.
just in case this is my code:
#models.py
class FileDescription(models.Model):
class Meta:
abstract = True;
ordering = ['file_creation_time']
subject = models.ForeignKey('Subjects', null=True, blank=True, primary_key=True)
subject_name = models.CharField(max_length=100)
file_uploaded_by = models.CharField(max_length=100)
file_name = models.CharField(max_length=100)
file_description = models.TextField()
file_creation_time = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return u'%s' % (self.file_name)
#template
<ul id="tabs">
<li><a href="#homework">Homework</a></li>
<li><a href="#class-papers">Class Papers</a></li>
<li><a href="#random-papers">Random Papers</a></li>
</ul>
<div id="homework" class="tab-section">
<h2>Homework</h2>
<p>This section contains Homework</p>
{% if homework_files %}
<ul>
{% for file in homework_files %}
<li>{{ file.file_name }}
{% endfor %}
</ul>
{% endif %}
</div>
#forms.py
class Homework_Content_Form(forms.ModelForm):
class Meta:
model=Homework_Content
exclude=('subject',
'subject_name',
'file_creation_time',
'file_uploaded_by',
)
Method 1: Separate Forms
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:
Method 2: Use Proxy Models
Since these three models all share the same data, having three separate tables is redundant. Instead of
FileDescriptionbeing 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:Then, you just need one form for
FileDescriptionand when the user’s choice for the “type” will be saved. You can then access anything set as type “homework” with the standardHomework.objects.all().