代码之家  ›  专栏  ›  技术社区  ›  LeLouch

django def post方法在cbv中不起作用

  •  0
  • LeLouch  · 技术社区  · 6 年前

    我的观点

    class ProfileUpdateView(LoginRequiredMixin, View):
        template_name = "accounts/update.html"
    
        def get_object(self):
            user = get_object_or_404(User, username=self.kwargs.get("username"))
            return user
    
        def get(self, request, *args, **kwargs):
            user = get_object_or_404(User, username=self.kwargs.get("username"))
            user_form = UserForm(instance=user)
            if user.is_client:
                print("client get is working")
                profile = Client.objects.get(id=user.clients.id)
                profile_form = ClientForm(instance=profile)
            if user.is_artisan:
                profile = Artisan.objects.get(id=user.artisans.id)
                profile_form = ArtisanForm(instance=profile)
            return render(
                request,
                self.template_name,
                {"user_form": user_form, "profile_form": profile_form},
            )
    
        def post(self, request, *args, **kwargs):
            print("post is working")
            if user.is_client:
                print("client post is working")
                profile_form = ClientForm(
                    request.POST, request.FILES, instance=profile
                )
                user_form = UserForm(request.POST, request.FILES, instance=user)
    
            if user.is_artisan:
                profile_form = ArtisanForm(
                    request.POST, request.FILES, instance=profile
                )
                user_form = UserForm(request.POST, request.FILES, instance=user)
    
            if profile_form.is_valid() and user_form.is_valid():
                print("form validation is working")
                created_profile = profile_form.save(commit=False)
                user_form.save()
                created_profile.save()
                reverse("accounts:profile", kwargs={"username": self.user.username})
            return render(
                request,
                self.template_name,
                {"user_form": user_form, "profile_form": profile_form},
            )
    

    模板

    <form action="." method="POST" enctype="multipart/form-data">
                      {% csrf_token %}
                  {{ user_form.as_p }}
                    <p> client form</p>
                  ------------------------------------------------
                    {{ profile_form.as_p }}
              <button class="btn btn-primary btn-round" type="submit">update</button>
        </form>
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   AKX    6 年前

    您的窗体操作设置为 "." ,即“此目录”。

    相反,只需把它放到当前的URL上。

    <form method="POST" enctype="multipart/form-data">