def group_display(request, group_id):
groups = Groups.objects.get(id=group_id)
username = UserInfo.objects.get(owner = request.user)
form = membership_form()
template = 'groups.html'
if request.method == 'POST':
form = membership_form(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.name = username
post.group = groups
post.save()
context = {
'form':form,
}
return render(request, template, context)
问题在于,每次重新加载页面时,都会向成员资格模型添加新行。好像页面加载为request.POST。有什么办法可以只在按钮点击时插入数据吗?
答案 0 :(得分:2)
成功发出POST请求后,最好返回重定向。这可以防止在刷新页面时再次处理发布请求。如果需要,您可以重定向到当前网址。
from django.shortcuts import redirect
def group_display(request, group_id):
...
if request.method == 'POST':
form = membership_form(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.name = username
post.group = groups
post.save()
return redirect('/success-url/')
...
答案 1 :(得分:1)
您可以做两件事:
成功发布后重定向。
检查以确保该用户没有注册。
这是一个照顾两者的视图:
from django.shortcuts import get_object_or_404, redirect
def group_display(request, group_id):
groups = get_object_or_404(Groups, id=group_id)
username = get_object_or_404(UserInfo, owner=request.user)
if username.membership_set.exists():
# This user is already enrolled
return redirect('/')
form = membership_form(request.POST or {})
template = 'groups.html'
context = {'form': form}
if form.is_valid():
post = form.save(commit=False)
post.name = username
post.group = groups
post.save()
return redirect('/')
return render(request, template, context)
您必须根据自己的型号调整username.membership_set.exists
。