Django UpdateView无法正常工作

时间:2018-07-29 20:42:19

标签: python django django-models django-forms django-views

我的问题是,当我使用UpdateView时,它不会更新记录。除此之外,它也没有任何错误。

调试代码时,在HTTP POST请求之后未调用form_valid()函数。但是我的表单类(AdvertisementDetailForm)正常工作。我找不到我在做什么错。

这样的控制台输出:

  

获取   / advertisement / publish / adv1_3ad5f56a-d99d-4ed4-b878-1327b9fa1bf8 / 1 /   HTTP / 1.1
  开机自检   / advertisement / publish / adv1_3ad5f56a-d99d-4ed4-b878-1327b9fa1bf8 / 1 /   HTTP / 1.1

第一个应用的views.py:

class PublishAdvertisement(LoginRequiredMixin, generic.UpdateView):
    login_url = '/'
    redirect_field_name = '/'
    model = AdvSummary
    form_class = AdvertisementDetailForm
    template_name = 'advertisement/publish_advertisement.html'
    success_url = reverse_lazy('brand:brand_home')

    def form_valid(self, form):
        pk = self.kwargs.get('pk')
        obj = get_object_or_404(AdvSummary, pk=pk)
        obj.advertisement_image = form.cleaned_data['advertisement_image']
        obj.adv_max_follower = self.request.POST['adv_max_follower']
        obj.adv_min_follower = self.request.POST['adv_min_follower']
        obj.adv_desc = self.request.POST['adv_desc']
        selected_categories = Category.objects.filter(pk__in=self.request.POST.getlist('categories'))
        obj.categories.add(*[cat for cat in selected_categories])
        obj.publish_date = timezone.now()
        obj.save()
        return super().form_valid(form)

urls.py:

urlpatterns = [
    path('publish/<slug:slug_name>/<int:pk>/',
         views.PublishAdvertisement.as_view(), name='publish'),
    path('delete/<slug:slug_name>/<int:pk>/',
         views.DeleteAdvertisement.as_view(), name='delete'),
]

第二个应用的views.py:

class BrandHomePage(LoginRequiredMixin, generic.View):
    login_url = '/'
    redirect_field_name = '/'

    def post(self, request, *args, **kwargs):
        view = CreateAdvertisement.as_view()
        return view(request, *args, **kwargs)

    def get(self, request, *args, **kwargs):
        view = PublishedAdvertisementList.as_view()
        return view(request, *args, **kwargs)

urls.py:

urlpatterns = [
    path('', views.BrandHomePage.as_view(), name='brand_home'),
]

2 个答案:

答案 0 :(得分:0)

def form_valid(self, form):
    pk = self.kwargs.get('pk')
    obj = get_object_or_404(AdvSummary, pk=pk)

在这里检查是否有物体。

答案 1 :(得分:0)

  

解决方案:

当我添加form_invalid()函数时,我已经弄清了问题的原因:

def form_invalid(self, form):
    print("form is invalid")
    return HttpResponse("form is invalid.. this is just an HttpResponse object")

我发现form.py中存在错误

谢谢