目录结构:
- project 目录
+ images/
views.py +
manage.py- project 目录下: python
manage.py shell 导入
views.py 里的两个视图函数,其中函数 image_like 为 None,
<img src="
https://i.loli.net/2019/02/14/5c64faacd9a72.jpg">
-
views.py 里两个函数的相关代码
@
login_requireddef image_create(request):
if request.method == "POST":
form = ImageCreateForm(data=
request.POST)
if form.is_valid():
cd = form.cleaned_data
new_item = form.save(commit=False)
# assign current user to the item
new_item.user = request.user
new_item.save()
messages.success(request, "Image added successfully.")
# redirect to new created item detail view
return redirect(new_item.get_absolute_url())
else:
# build form with data provided by the bookmarked via GET:
form = ImageCreateForm(data=request.GET)
return render(request, 'images/image/create.html', {'section': 'images', 'form': form})
@
ajax_required@
login_required@
require_POSTdef image_like(request):
# import pdb
# pdb.set_trace()
image_id = request.POST.get('id')
action = request.POST.get('action')
if image_id and action:
try:
image = Image.objects.get(id=image_id)
if action == 'like':
image.users_like.add(request.user)
else:
image.users_like.remove(request.user)
return JsonResponse({"status": "ok"})
except:
pass
return JsonResponse({"status": "ko"})