我想上传任何文件。但是,当我提交上载时,同一帖子被上载了两次,但其中一个没有文件,只有内容,而下一个有文件。
class FileCreateView(PassRequestMixin, SuccessMessageMixin,
CreateView):
template_name = 'file/upload-file.html'
form_class = FileForm
success_message = 'File was uploaded successfully'
success_url = reverse_lazy('home')
def post(self, *args, **kwargs):
"""
Handle POST requests: instantiate a form instance with the passed
POST variables and then check if it's valid.
"""
# form = self.get_form([self.request.FILES])
form = self.form_class(self.request.POST, self.request.FILES)
if self.request.method == 'POST':
if form.is_valid():
file = form.save(commit=False)
file.upload = form.cleaned_data['upload']
file.author = User.objects.get(pk=self.request.user.pk)
file.save()
return self.form_valid(form)
else:
return self.form_invalid(form)
home.html
<div class="container mt-3">
<div class="row">
<div class="col-12 mb-3">
<button class="upload-file btn btn-primary" type="button" name="button">
<span class="fa fa-plus mr-2"></span>Upload Form</button>
</div>
</div>
{% block extrascripts %}
<script type="text/javascript">
$(function () {
$(".upload-file").modalForm({formURL: "{% url 'file-upload' %}"});
});
</script>
{% endblock extrascripts %}
urls.py
path('upload/file/', FileCreateView.as_view(), name="file-upload"),
model.py
class File(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
author = models.ForeignKey(User, on_delete=models.CASCADE)
visible_to_home = models.ManyToManyField(Home, blank=True) # when none visible to all home
visible_to_company = models.ManyToManyField(Company, blank=True) # when none visible to all company
# To determine visibility, check if vtc is none or include company of user and if true, check same for home
created_date = models.DateTimeField(auto_now=True)
published = models.BooleanField(default=True)
upload = models.FileField(blank=True, null=True, upload_to=update_filename)
title = models.CharField(max_length=225, blank=True, null=True)
description = models.TextField(blank=True, null=True)
在上载的文件之一中,没有模型的upload
字段,在下一个文件中,没有任何内容。