Django ModelForm更新不起作用

时间:2018-06-30 23:03:03

标签: django transactions django-forms

嗨,我对ModelForms有疑问。当我尝试使用事务更新对象形式的两个类时,什么也没发生。

我的表单类:

class TeamForm(forms.ModelForm):
    employers = forms.ModelMultipleChoiceField(queryset=Employer.objects.all(), widget=forms.CheckboxSelectMultiple)

    class Meta:
        model = Team
        fields = '__all__'

我的模型课:

class Team(models.Model):
    name = models.CharField(default='Team', max_length=100, unique=True)

    def __str__(self):
        return self.name


class Employer(models.Model):
    user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True)
    team = models.ForeignKey(Team, on_delete=models.SET_NULL, null=True)
    team_leader = models.BooleanField(default=False)
    project_menager = models.BooleanField(default=False)
    # project_id = models.ForeignKey(Project, on_delete=models.SET_NULL, null=True)

    hourly_rate = models.IntegerField(default=0)
    working_time = models.FloatField(default=0.0)

    def __str__(self):
        return self.user.first_name + ' ' + self.user.last_name

最后是我的观点:

def TeamUpdateView(request, pk):
    if request.method == 'POST':
        team_form = TeamForm(request.POST)
        if team_form.is_valid():
            with transaction.atomic():
                team = Team.objects.filter(pk=pk).update(name=str(team_form['name'].value()))
                for e in team_form['employers'].value():
                    Employer.objects.filter(pk=e).update(team=team)
            print(team_form.errors)
            return redirect('resources:ResourcesListView')
    else:
        team = get_object_or_404(Team, pk=pk)
        team_form = TeamForm(initial={'name': team.name})  # milestone_form = MilestoneForm()
        context = {'team_form': team_form, 'form_pk': pk}  # , 'milestone
        return render(request, 'resources/resources_edit_modal.html', context)

当我打印表格错误时,我会看到类似这样的内容:

<ul class="errorlist"><li>name<ul class="errorlist"><li>Team with this Name already exists.</li></ul></li></ul>

0 个答案:

没有答案