探索Django:从项目创建到图片上传的全方位指南
from django.shortcuts import render
from django.http import HttpResponse
from .models import Post
from .forms import PostForm
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_POST
from django.http import JsonResponse
import os
# 创建一个新的帖子
@login_required
@require_POST
def create_post(request):
form = PostForm(request.POST, request.FILES)
if form.is_valid():
post = form.save(commit=False)
post.user = request.user
post.save()
return JsonResponse({'id': post.id})
return JsonResponse({'error': 'Invalid data'}, status=400)
# 图片上传视图
@login_required
@require_POST
def upload_image(request):
image = request.FILES['image']
image_name = os.path.join('posts', image.name)
with open(image_name, 'wb+') as destination:
for chunk in image.chunks():
destination.write(chunk)
return JsonResponse({'image_url': image_name})
# 展示创建帖子的表单
@login_required
def create_post_form(request):
if request.method == 'POST':
# 处理POST请求
return create_post(request)
else:
# 显示空表单
return render(request, 'posts/create_post.html', {'form': PostForm()})
# 展示上传图片的表单
@login_required
def upload_image_form(request):
if request.method == 'POST' and 'image' in request.FILES:
# 处理POST请求和图片上传
return upload_image(request)
else:
# 显示空表单或错误信息
return render(request, 'posts/upload_image.html')
在这个示例中,我们创建了两个视图函数create_post
和upload_image
来处理帖子创建和图片上传的逻辑。这两个视图函数都使用了Django的装饰器login_required
和require_POST
来确保只有登录用户可以访问,并且只处理HTTP POST请求。另外,我们使用了JsonResponse
来返回JSON格式的响应,这是一种常见的AJAX请求处理方式。
评论已关闭