编辑对象时保留旧文件,而不以Django形式上传新文件

问题描述

|| 我有一个Player类,该类使用ForeignKey到Photo对象以附加面部照片。我的问题是,当我编辑具有面部照片的播放器并且不上传新的面部照片时,旧的面部照片会与Player对象分离。我的逻辑肯定有问题。
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()
    

解决方法

        稍作修改即可解决问题:
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()
另外,您的表单需要排除现有的面部照片:
class PlayerForm( forms.ModelForm ):

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

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