Django - 无法使用模型形式更新模型给出str错误

时间:2017-12-06 20:48:14

标签: django django-models django-forms django-views

我试图让用户更新其团队中的一些设置,但它似乎无法正常工作我想更新名称以及他们是否接受用户。

Views.py

@login_required
def teamsettings_general(request, team_pk):
    logged_in_user = get_object_or_404(User, pk=request.user.pk)
    requested_team = get_object_or_404(Team, pk=team_pk)
    if request.method == 'POST':
        for member in requested_team.teammembership_set.all().order_by('-leader'):
            if member.user.pk == request.user.pk and member.leader:
                form = TeamSettings_GeneralForm(request.POST, instance=team_pk)
                if form.is_valid():
                    form.save()
                    messages.success(request, "The team has been updated!")
                    return redirect('teamsettings_general', team_pk=team_pk)
    for member in requested_team.teammembership_set.all().order_by('-leader'):
        if member.user.pk == request.user.pk and member.leader:
            feedback = FeedbackSupportForm()
            form = TeamSettings_GeneralForm(instance=team_pk)
            context = {
                'requested_team': requested_team,
                'feedback': feedback,
                'form' : form,
                'logged_in_user': logged_in_user,
            }
            return render(request, 'team/settings.html', context)
            break
        else: return redirect('team', team_pk)

和我的form.py

class TeamSettings_GeneralForm(forms.ModelForm):
    class Meta:
        model = Team
        fields = ('name', 'accepts_applications',)

现在我只想让它更新name和accepts_applications

'str' object has no attribute '_meta'

    form = TeamSettings_GeneralForm(request.POST, instance=team_pk)
    if form.is_valid():
        form.save()
        messages.success(request, "The team has been updated!")
        return redirect('teamsettings_general', team_pk=team_pk)
logged_in_user = get_object_or_404(User, pk=request.user.pk)
requested_team = get_object_or_404(Team, pk=team_pk)
form = TeamSettings_GeneralForm(instance=team_pk) ...
for member in requested_team.teammembership_set.all().order_by('-leader'):
    if member.user.pk == request.user.pk and member.leader:
        feedback = FeedbackSupportForm()
        context = {
            'requested_team': requested_team,
            'feedback': feedback,

感谢adbanvce

1 个答案:

答案 0 :(得分:1)

你得到了Team实例,但后来忽略了它并将PK传递给了表单。它应该是:

form = TeamSettings_GeneralForm(instance=requested_team)