首页 > 解决方案 > Django Form 不更新模型中的数据

问题描述

这是我的第一个 Django 项目,我被卡住了。如果不是解决方案,而只是提示我做错了什么,将不胜感激。

我有一个模型,其中一个属性默认设置为 Null,我想使用表单来使用从另一个模型获取的 ID 更新该属性。这些是2个模型:

模型.py

class Squad(models.Model):
    squad_name = models.CharField(max_length=20)
  
    def __str__(self):
        return self.squad_name

class AvailablePlayer(models.Model):
    player_name = models.CharField(max_length=25)
    squad = models.ForeignKey(Squad, on_delete=models.CASCADE, blank=True, null=True)

    def __str__(self):
        return self.player_name

这是表格:

表格.py

class AddSquadToPlayerForm(forms.Form):
    # squad the player will be added to
    squad_to_player = forms.ModelMultipleChoiceField(queryset=None)
    
    def __init__(self, *args, **kwargs):
        super(AddSquadToPlayerForm, self).__init__()
        self.fields['squad_to_player'].queryset = AvailablePlayer.objects.all()

这是视图文件,我认为其中缺少/错误:

视图.py

def add_player_to_squad(request, squad_id):
    # player = AvailablePlayer.objects.get(id=squad_id)
    squad = Squad.objects.get(id=squad_id)
    if request.method == "POST":
        form = AddPlayerToSquadForm(request.POST)
        if form.is_valid():
            form.squad = form.cleaned_data['id']
            form.save()
            return redirect('fanta_soccer_app:squad', squad_id=squad_id)
    else:
        form = AddPlayerToSquadForm(queryset=AvailablePlayer.objects.all())
    context = {"squad": squad, "form": form}
    return render(request, 'fanta_soccer_app/add_player.html', context)

最后,这是 html 文件

add_player.html

<body>
<p>Add a new player to the Squad:</p>
<p><a href="{% url 'fanta_soccer_app:squad' squad.id %}">{{ squad }}</a></p>
<form action="{% url 'fanta_soccer_app:add_player' squad.id %}" method="POST">
    {% csrf_token %}
    <table>
        {{ form.as_table }}
    </table>
    <button name="submit" type="submit" >Add player</button>
</form>
</body>

The rendered html shows correctly a form with a drop down menu correctly populated with the objects in the database from the "AvailablePlayer" model, however when selecting one and clicking on "Add", nothing happens, and selected player is not added to the DB .

提前感谢您的宝贵时间。

EDIT: the code in views.py has been modified according to a comment

ADDITIONAL INFO: to confirm the db is working, if I manually add the squad_id to one of the AvailablePlayer(s) in the DB, it will be correctly listed in the squad details view.

标签: pythondjangosqlitedjango-forms

解决方案


Based off the docs I think where you are going wrong is that you are trying to update an existing value, which requires you to pass an instance keyword argument to form.save().

So I think you need to do something like this:

if form.is_valid():
    a = Squad.objects.get(id=squad_id)
    form = AddSquadToPlayerForm(request.POST, instance=a)
    form.squad = form.cleaned_data['id']
    form.save()

推荐阅读