编辑对象时保留旧文件,而不是在Django表单上上传新文件

时间:2011-06-23 23:05:19

标签: django

我有一个Player类,它将一个ForeignKey用于Photo对象,以便附加一个照片。我的问题是,当我编辑一个有照片的玩家并且我没有上传新照片时,旧的照片会从玩家对象中脱离出来。我的逻辑一定有问题。

class Player( models.Model ):
    ...
    mugshot = models.ForeignKey( 'content.Photo', null=True, blank=True )
    ...

我的PlayerForm类看起来像这样:

class PlayerForm( forms.ModelForm ):
    ...
    mugshot = forms.FileField( widget=forms.FileInput(), required=False )
    ...

    def save(self, commit=True, request=None, user=None):
        player = super( PlayerForm, self ).save( commit=False )

        if commit:
            player.save()

        return player

在我的编辑视图中,我更新了播放器,然后检查是否存在文件上传,以查看是否更换了照片。

def edit_player( request, team_season_id, player_id ):
    team_season = get_object_or_404( TeamSeasonConference, pk=team_season_id )
    player = get_object_or_404( Player, pk=player_id )

    if request.method == 'POST' and 'cancel' not in request.POST:
        player_form = PlayerForm( request.POST, instance=player )

        if player_form.is_valid():
            updated_player = player_form.save(True)

            if request.FILES: # if sent a file
                file_data = request.FILES['mugshot']
                picture = Photo.objects.create( # create a photo object with that file
                name = player_form.cleaned_data['first_name'] + ' ' + player_form.cleaned_data['last_name'], # and give it the name of the player you're adding
                cutline = '',
                file = file_data,
                source = '',
            )
        else:
            picture = player.mugshot; # keep the old one

        updated_player.mugshot = picture
        updated_player.save()

1 个答案:

答案 0 :(得分:1)

稍微改一下就可以解决问题:

def edit_player( request, team_season_id, player_id ):
team_season = get_object_or_404( TeamSeasonConference, pk=team_season_id )
player = get_object_or_404( Player, pk=player_id )

if request.method == 'POST' and 'cancel' not in request.POST:
    player_form = PlayerForm( request.POST, instance=player )

    if player_form.is_valid():
        updated_player = player_form.save(True)

        if request.FILES: # if sent a file
            file_data = request.FILES['mugshot']
            picture = Photo.objects.create( # create a photo object with that file
                name = player_form.cleaned_data['first_name'] + ' ' + player_form.cleaned_data['last_name'], # and give it the name of the player you're adding
                cutline = '',
                file = file_data,
                source = '',
            )

            # You only need to save again if there is a picture
            updated_player.mugshot = picture
            updated_player.save()

此外,您的表单需要排除现有的mugshot:

class PlayerForm( forms.ModelForm ):

    class Meta:
        model = Player
        exclude = ('mugshot',)

    def save(self, ...):
        #as it was before