在Django中对于基于函数的视图我们可以 @csrf_exempt 注解来标识一个视图可以被跨域访问。那么对于基于类的视图,我们应该怎么办呢?
简单来说可以有两种访问来解决
方法一:在类的 dispatch 方法上使用 @csrf_exempt
class InsertMyFavView(LoginRequiredMixin, View): """ 加入收藏 """ login_url = '/login/' redirect_field_name = 'next' def post(self, request): user = request.user data = json.loads(request.body.decode()) fav_id = data["fav_id"] fav_type = data["fav_type"] try: user_fav = UserFavorite.objects.get(user=user, fav_id=fav_id, fav_type=fav_type) if user_fav: return JsonResponse({"status": "success", "msg": "已收藏!"}) except UserFavorite.DoesNotExist: UserFavorite(user=user, fav_id=fav_id, fav_type=fav_type,add_time=datetime.now()).save() return JsonResponse({"status": "success", "msg": "添加收藏成功!"})
方法二:在 urls.py 中配置
from django.conf.urls import urlfrom django.views.decorators.csrf import csrf_exemptimport AddMyFavViewurlpatterns = [ # 加入收藏 path('myfav/add/', csrf_exempt(AddMyFavView.as_view()), name="add_fav"),]