我需要将基于函数的视图“ FBV”修改为基于类的视图“ CBV”

时间:2018-08-01 18:27:51

标签: python django

我需要对代码进行一些修改,因为我有一个基于函数的视图,需要将其更改为基于类的视图

FBV:

def Adress_Use_Prev(request):
      # print(request.POST)
      address_type=request.POST.get('address_type',"shipping")
      address_id=request.POST.get("Address-id")
      request.session[address_type+"_address_id"]=address_id

      next_ = request.GET.get("next")
      next_post = request.POST.get("next")
      redirected_path = next_ or next_post or None
      if is_safe_url(redirected_path, request.get_host()):
          return redirect(redirected_path)

      return redirect("/")

将这种功能转换为CBV的最佳解决方案是什么

我尝试了以下代码,但失败了

class UsePrevAddress(NextUrlMixin,FormView):

      # def get_success_url(self):
      #     return self.get_next_url()

     def form_valid(self, form):
          print("test5")
          address_type = self.request.POST.get('address_type', "shipping")
          address_id = self.request.POST.get("Address-id")
          self.request.session[address_type + "_address_id"] = address_id
          return self.get_next_url()

     def form_invalid(self, form):
         super().form_invalid(form)

form.html:

{% if address_qs  %}
<form method="POST" action="{% url "cart:checkout-Address-reuse" %}"> {% csrf_token %}
{% for Address in address_qs %}
    <label for="address-{{ Address.id }}">
        <input id="address-{{ Address.id }}" type="radio" name="Address-id" value="{{ Address.id }}"/>
        {{ Address.Address_line_1 }},
        {% if Address.Address_line_2 %} Address.Address_line_2,
        {% endif %}
        {{ Address.State }},{{ Address.Postal_Code }},{{ Address.city }}
    </label><br/>
{% endfor %}



        {% if next_url %}
            <input type="hidden" name="next" value="{{ next_url }}">
        {% endif %}
         {% if address_type %}
             <input type="hidden" name="address_type" value="{{ address_type }}">
        {% endif %}
        <button type="submit" class="btn btn-success">Use Address</button>
</form>
{% endif %}

urls.py:

url('^checkout/Address/reuse$',UsePrevAddress.as_view(),name="checkout-Address-reuse"),

1 个答案:

答案 0 :(得分:0)

为模型类创建一个ModelForm。将form_class添加到您的CBV中。
参考:ModelForm Django

示例

from django import forms
from django.views.generic.edit import CreateView

class YourModelForm(forms.ModelForm):
    model = YourModel
    fields = ('field_1', 'field_2', )

# use `CreateView`. `FormView` is for non-model forms
# and I have used a `ModelForm` here.
class YourModelFormView(NextUrlMixin, CreateView):
    form_class = YourModelForm

    # rest of your code