Django模型表单保存同时发布请求两次

时间:2019-01-04 15:17:56

标签: django django-models django-forms

enter image description here我在django-bootstrap-modal-forms 1.3.1之后使用https://pypi.org/project/django-bootstrap-modal-forms/,但是如果我运行它是书籍项目,它将调用发布请求以两次创建书籍,但是一次保存一次。

当我使用它时,它会发出两次发布请求,但是两个请求都被保存为一个空文件,即,一个发布保存了title descriptiondate之类的所有模态字段但没有upload(文件),下一篇文章将同时用upload保存所有内容

这是我的模特:

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)

如果我删除作者,则可以正常工作,但根据我的需要,我需要作者。

class FileForm(PopRequestMixin, CreateUpdateAjaxMixin, forms.ModelForm):
    class Meta:
        model = File
        fields = ('title', 'description', 'upload')

查看

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()
        # 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

{% block extrascripts %}
<script type="text/javascript">
$(function () {
  $(".upload-file").modalForm({formURL: "{% url 'file-upload' %}"});
 });
</script>
{% endblock extrascripts %}

其他与示例实现相同。

2 个答案:

答案 0 :(得分:2)

尝试一下:

 if form.is_valid():
     if not self.request.is_ajax():
         file = form.save(commit=False)
         file.upload = form.cleaned_data['upload']
         file.author = User.objects.get(pk=self.request.user.pk)
         file.save()

答案 1 :(得分:-1)

您需要修改CreateView

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 form_valid(self, form):
       file = form.save(commit=False)
       file.author = self.request.user.pk
       file.save()
       return HttpResponseRedirect(reverse('home'))