gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 13:02:05 24 4
gpt4 key购买 nike

enter image description here我正在使用 django-bootstrap-modal-forms 1.3.1关注 https://pypi.org/project/django-bootstrap-modal-forms/但是如果我运行它的书籍项目,它会调用 post 请求来创建书籍两次,但保存一次。

当我使用它时,它发出了两次 post 请求,但两个请求都保存了一个空文件,即一个 post 保存了所有模态字段,如 title description , date但不是 upload (file) 和下一篇文章用 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)

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

其他与示例实现相同。

最佳答案

尝试这个:

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

关于Django模型表单同时保存两次发布请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54041660/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com