Reputation: 1205
Right now my code looks like this:
#models.py
class Document(models.Model):
docfile = models.FileField(upload_to='documents/%Y/%m/%d')
class Course(models.Model):
course_document = models.ForeignKey(Document,null=True,blank=True)
subject = models.CharField(max_length = 255)
#forms.py
class DocumentForm(forms.Form):
docfile = forms.FileField(
label='Select a file',
help_text='max. 42 megabytes'
)
course = forms.ChoiceField(choices=Course.objects.all(),
widget=forms.RadioSelect)
#views.py
def list(request):
# Handle file upload
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile = request.FILES['docfile'])
newdoc.save()
# Redirect to the document list after POST
return HttpResponseRedirect(reverse('notes_app.views.list'))
else:
form = DocumentForm() # A empty, unbound form
# Load documents for the list page
documents = Document.objects.all()
# Render list page with the documents and the form
return render_to_response(
'notes_app/list.html',
{'documents': documents, 'form': form},
context_instance=RequestContext(request)
)
#notes_app/list.html -- The majority of it anyway
<form action="{% url "list" %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>
<p>
{{ form.docfile.errors }}
{{ form.docfile }}
</p>
I used a simple python script to populate the "Courses" into the database, and want I want is so each time a User uploads a file they choose a "Course" and that course is associated with the file they uploaded, so my question is how do I display those courses as a choice? Sorry if this question seems stupid I am new to programming and even newer to python/django. Thanks for the feedback.
Upvotes: 0
Views: 59
Reputation: 20780
choices
should be a CharField
, with a choices argument. The value of the choices argument is a tuple
with 2 items in it. The first is a value for you to access if you need it. The second value is what the User sees. So"
class MyForm(forms.Form):
courses = forms.CharField(max_length=255, choices=(
('1', 'First Course'),
('2', 'Second Course')
)
)
Here is the Django Docs for this:
https://docs.djangoproject.com/en/dev/ref/models/fields/#choices
Upvotes: 0
Reputation: 366
I still haven't really understood your question but this might help you. In your models.py
course_name = ('English', 'Maths',)
from model_utils import Choices
class Course(models.Model):
course_document = models.ForeignKey(Document,null=True,blank=True)
name = models.CharField(max_length=255, choices=Choices(*course_name))
subject = models.CharField(max_length = 255)
This will create a drop down menu for choosing courses.
Upvotes: 1