首页 > 解决方案 > Nonetype 对象没有属性 is_ajax

问题描述

我在我的项目中使用Django-bootstrap-modal-forms。但我想要很少的定制,并添加了UploadAuthor​​字段作为外键。如果我从图书馆开始,它就可以正常工作。但在这里我得到了Nonetype object has no attribute is_ajaxNonetype即使我已登录,我也不知道为什么会这样。

模型 :

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)

这里在 post 方法中查看如果我使用而form = self.get_form()不是Django 模型表单同时保存 post request 两次问题。form = self.form_class(self.request.POST, self.request.FILES)

主页.html

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

追溯 :

File "/home/bishwa/PycharmProjects/sharefile/env/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner
response = get_response(request)
File "/home/bishwa/PycharmProjects/sharefile/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/bishwa/PycharmProjects/sharefile/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python3.6/contextlib.py", line 52, in inner
return func(*args, **kwds)
File "/home/bishwa/PycharmProjects/sharefile/env/lib/python3.6/site-packages/django/views/generic/base.py", line 69, in view
return self.dispatch(request, *args, **kwargs)
File "/home/bishwa/PycharmProjects/sharefile/env/lib/python3.6/site-packages/django/views/generic/base.py", line 89, in dispatch
return handler(request, *args, **kwargs)
File "/home/bishwa/PycharmProjects/sharefile/sharefile/file/views.py", line 103, in post
file = form.save(commit=False)
File "/home/bishwa/PycharmProjects/sharefile/env/lib/python3.6/site-packages/bootstrap_modal_forms/mixins.py", line 40, in save
if not self.request.is_ajax():
AttributeError: 'NoneType' object has no attribute 'is_ajax'

[06/Jan/2019 00:06:30]“POST /upload/file/HTTP/1.1”500 110437

根据我正在使用的库,它说我认为我跟踪了错误,即我需要在函数中调用和方法On submit the form is POSTed via AJAX request to formURL 时发出 ajax 请求。你知道我该怎么做吗?file = form.save(commit=False)file.save()post

答:所以最后我解决了它:

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

def save(self, commit=False):

    if not self.request.is_ajax():
        instance = super(CreateUpdateAjaxMixin, self).save(commit=commit)
        instance.author = User.objects.get(pk=self.request.user.pk)
        instance.save()
    else:
        instance = super(CreateUpdateAjaxMixin, self).save(commit=False)

    return instance

save方法被覆盖CreateUpdateAjaxMixin,我在视图中删除了该post方法。

标签: ajaxdjangodjango-formsdjango-rest-frameworkdjango-views

解决方案


推荐阅读