我需要对我的代码进行一些修改,因为我有一个基于函数的视图,需要将其更改为基于类的视图
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)
表单.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"),
为模型类创建一个ModelForm
。将form_class
添加到您的CBV中
参考: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