Django数据库正在更新每个页面加载

时间:2016-05-15 11:02:48

标签: django post

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。有什么办法可以只在按钮点击时插入数据吗?

2 个答案:

答案 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)

您可以做两件事:

  1. 成功发布后重定向。

  2. 检查以确保该用户没有注册。

  3. 这是一个照顾两者的视图:

    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