'ManagementForm数据丢失或已被篡改'问题

时间:2018-12-27 00:21:57

标签: python django python-3.x django-models django-forms

我被这个错误困住了,我不知道该怎么办...

我遵循了Django文档here

当我填写空的额外表单时,我也想创建一个新的Player对象,但是模型的一个require字段必须基于request.user.team而不由用户直接坐坐

希望有人熟悉ManagementForm

我的文件:


views.py

from django.shortcuts import render, redirect
from skeleton.models import Player
from django.contrib.auth.decorators import login_required
from .forms import PlayerForm
from django.forms import modelformset_factory


# Create your views here.
@login_required(login_url="/accounts/login/")
def team_area(request):
    PlayerFormSet = modelformset_factory(Player, fields=('first_name', 'last_name'), extra=1)
    if request.method == "POST":
        player_formset = PlayerFormSet(
            request.POST,
            request.FILES,
            queryset=Player.objects.all().filter(team=request.user.team),)

        if player_formset.is_valid():
            player_formset.save()
            return redirect('team_area:home')
    else:
        player_formset = PlayerFormSet(queryset=Player.objects.all().filter(team=request.user.team))
    return render(request, 'team_area/team_area.html', {'player_formset': player_formset})

team_area.html

{% extends 'base_layout.html' %}

{% block content %}
  <h1>Area Squadra</h1>
  <form method="post" action="">
    {% csrf_token %}
    {{ formset.management_form }}
    {% for player_form in player_formset %}
        {% for field in player_form %}
            {{ field.label_tag }} {{ field }}
        {% endfor %}
        <br>
    {% endfor %}
    <input type="submit" value="Aggiorna">
  </form>
{% endblock %}

2 个答案:

答案 0 :(得分:2)

一个表单集可能包含的表单要多于一个表单,因此,为了将表单集中的数据保存到视图文件中,您必须遍历所有表单并保存每个表单的数据。就像在views.py文件中一样,您可以编写:

  

如果player_formset.is_valid():

    for form in player_formset:

        form.save()

这将创建与表单集中的新表单一样多的Player新对象(假设您尚未删除任何表单或编辑现有表单)。

一旦用户点击添加播放器按钮

,则还必须更新.html文件中的管理表单数据。

答案 1 :(得分:0)

这是我使用

找到并使用的解决方案
  

.save(commit = False)

   if request.method == "POST":
        player_formset = PlayerFormSet(request.POST, request.FILES, queryset=Player.objects.all().filter(team=request.user.team),)
        for player_form in player_formset:
            if player_form.is_valid():
                player = player_form.save(commit=False)
                player.team = request.user.team
        if player_formset.is_valid():
            player_formset.save()