4

enter image description hereI am using django-bootstrap-modal-forms 1.3.1 following https://pypi.org/project/django-bootstrap-modal-forms/ but if I run it's project of books it calls the post request to create book twice but saves the from once.

As I am using it, it makes twice post request but both the request are saved one with empty file i.e one post saves all the fields of modal like title description, date but not the upload (file) and the next post saves all of it with upload simultaneously

This is my model :

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)

If I remove author then it works fine but as my requirement I need author.

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

View

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 %}

Other is same as the example implementation.

3 Answers 3

4

Try this:

 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
    This actually worked for me, what was the reason of this issue ?
    – Sark
    Sep 5, 2020 at 14:14
0

Adding to alex's answer: For Django 4 request.is_ajax(): does not work! request.headers.get('x-requested-with') == 'XMLHttpRequest': works for me.

-1

You need to modify your 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'))
5
  • How do I do that ? Can you please elaborate? Jan 4, 2019 at 15:42
  • replace your FileCreateView with mine.
    – shafik
    Jan 4, 2019 at 15:44
  • There is no error but the same file is again uploaded twice one with all the description except the upload i.e any file and the next uploads all the fields with file Jan 4, 2019 at 16:04
  • Let us continue this discussion in chat.
    – shafik
    Jan 4, 2019 at 16:06
  • Please explain your anwser. I am coming from a slightly different angle and can't understand what you think the problem is in the OP solution and why your rewrite addresses the issue. As a result, this answer is unusable.
    – Sebastien
    May 7, 2019 at 15:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.