【问题标题】:Django model form saving simultaneously post request twiceDjango模型表单同时保存两次发布请求
【发布时间】:2019-05-31 04:27:54
【问题描述】:

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

当我使用它时,它发出两次发布请求,但两个请求都保存了一个空文件,即一个帖子保存了所有模态字段,如titledescriptiondate,但不是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 %}

其他与示例实现相同。

【问题讨论】:

    标签: django django-models django-forms


    【解决方案1】:

    试试这个:

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

    【讨论】:

    • 这实际上对我有用,这个问题的原因是什么?
    【解决方案2】:

    你需要修改你的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'))
    

    【讨论】:

    • 我该怎么做?能详细点吗?
    • 把你的FileCreateView换成我的。
    • 没有错误,但同一个文件再次上传了两次,其中包含除upload之外的所有描述,即任何文件,下一次上传文件中的所有字段
    • 请解释一下您的回答。我的角度略有不同,无法理解您认为 OP 解决方案中的问题是什么,以及为什么您的重写解决了该问题。结果,这个答案是不可用的。
    猜你喜欢
    • 2014-09-12
    • 2019-10-06
    • 1970-01-01
    • 2023-01-23
    • 2016-10-03
    • 2020-04-15
    • 2018-02-21
    • 2011-06-29
    • 1970-01-01
    相关资源
    最近更新 更多