I currently want to send some data to my database by doing the following: Sending a document to the database and each document has a foreign key from the user table i.e. each document is a reference to an author(from another table) but it will be bad for the user to get all the users in the system and choosing one of them, I want the author assignment to be performed in the views. So as a summary I want to get fields from the form in views. I found a corresponding question and tip at this link, but the only issue here being that a file was not inlcuded in his model but on mine yes. Snipets of my files below;
models.py
class UploadedDocuments(models.Model):
user = models.ForeignKey(
TheUsers,
on_delete=models.CASCADE,
)
document = models.FileField(
verbose_name='Document',
upload_to=f'documents/%Y/',
null=True,
)
plagiarism_status = models.CharField(max_length=100, null=True)
serialised_content = models.CharField(null=True, max_length=255)
date_uploaded = models.DateTimeField(
verbose_name='Uploaded On',
auto_now_add=True
)
def __str__(self):
return self.document.name
class Meta:
verbose_name = "Document"
verbose_name_plural = 'Documents'
Views.py
def upload(request):
form = UploadedDocumentsForm(request.POST, request.FILES)
if request.POST:
if form.is_valid():
form_stack = form.save(commit = False)
form.user = request.user
form_stack.serialised_content = "bala"
form_stack.plagiarism_status = 'Hello'
form_stack.save()
return redirect("results")
function which is constantly telling me invalid.
forms.py
class UploadedDocumentsForm(forms.ModelForm):
class Meta:
model = UploadedDocuments
fields = ['document', 'user', 'plagiarism_status', 'serialised_content']
widgets = {
'document': forms.FileInput(
attrs = {
'class': 'drop-zone__input',
'id': 'file',
'accept': '.doc, .docx, .txt',
'required': True,
}
),
'user': forms.Select(
attrs = {
}
),
'plagiarism_status': forms.TextInput(
attrs = {
'hidden': True,
}
),
'serialised_content': forms.TextInput(
attrs = {
'hidden': True,
}
)
}
my template file
<form action="{% url 'upload' %}" method="POST" enctype='multipart/form-data'>
{% csrf_token %}
<div class="drop-zone w-50">
<span class="drop-zone__prompt text-center h3">
Drops file here
</span>
{{ form.document }}
{{ form.user }}
{{ form.serialised_content }}
{{ form.plagiarism_status }}
</div>
<div class="d-flex justify-content-center">
<button type="submit" class="btn btn-white btn-outline-success
p-4 px-5 w-lg-25 w-md-50 w-sm-50 text-capitalize5 my-5">
<i class="fa fa-2x fa-sync px-3"></i>
Upload
</button>
</div>
</form>
Any suggestion on how this could be done will be helpful.
add blank and none to your user of UploadedDocuments model: