Django:当 Date/TimeField 为 auto_now=True 时更新表单而不更新日期/时间

问题描述 投票:0回答:1

我已经构建了一个记录保存应用程序。我希望用户能够编辑事件,但在设置为 auto_now=True 时无需更新日期/时间字段。

模型.py

class Game(models.Model):
    # ForeignKeys
    user = models.ForeignKey(User,
                             max_length=10,
                             on_delete=models.CASCADE,
                             null=True)
    deck = models.ForeignKey(Deck, on_delete=models.CASCADE, null=True)
    wincon = models.ForeignKey(Wincon, on_delete=models.CASCADE, null=True, blank=True)
    tournament = models.BooleanField(default=False)

    num_players = models.IntegerField(choices=NUM_PLAYERS_CHOICE, default=4)
    start_pos = models.CharField(max_length=20, choices=START_POS_CHOICE, default=1)
    mull = models.CharField(max_length=20, choices=MULL_CHOICE, default='1st 7')
    outcome = models.CharField(max_length=10, choices=OUTCOME_CHOICE, default='Win')
    medium = models.CharField(max_length=10, choices=MEDIUM_CHOICE, default='Paper')
    date = models.DateField(auto_now=True)
    time = models.TimeField(auto_now=True)

表格.py

class GameForm(forms.ModelForm):
    def __init__(self, user, *args, **kwargs):
        super(GameForm, self).__init__(*args, **kwargs)

        # Set deck list shown to only decks from user
        user_decks = Deck.objects.filter(user=user)
        user_decks_list = []
        for deck in user_decks:
            if deck.is_cedh:
                deck.deck += ':  cEDH'
            user_decks_list.append((deck.id, deck.deck))
        self.fields['deck'].choices = user_decks_list

        # Set wincon list shown to only wincon from user
        user_wincon = Wincon.objects.filter(user=user)
        user_wincon_list = []
        for wincon in user_wincon:
            user_wincon_list.append((wincon.id, wincon.wincon))
        self.fields['wincon'].choices = user_wincon_list

    class Meta:
        model = Game
        exclude = {'date', 'time', 'user'}
        labels = {
            'deck': 'What deck',
            'num_players': '# of Players',
            'start_pos': 'Starting position',
            'mull': 'Starting hand',
            'outcome': 'Outcome',
            'wincon': 'Your Wincon',
            'medium': 'Paper or Online',
            'tournament': 'Tournament',
        }

class UpdateGameForm(forms.ModelForm):
    class Meta:
        model = Game
        exclude = {'date', 'time', 'user'}
        fields = {
            'deck': 'What deck',
            'num_players': '# of Players',
            'mull': 'Starting hand',
            'outcome': 'Outcome',
            'wincon': 'Wincon',
            'medium': 'Paper or Online',
            'tournament': 'Tournament',
        }

views.py

@login_required(login_url='my-login')
def game_tracker(request):
    user = User.objects.get(username=request.user)
    user_decks = Deck.objects.filter(user=request.user)
    user_wincon = Wincon.objects.filter(user=request.user)

    if request.method == "POST":
        form = GameForm(request.user, request.POST)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.user = user
            obj.save()
            return HttpResponseRedirect('/view-games')
    else:
        form = GameForm(request.user)

    context = {'form': form, 'user_decks': user_decks, 'user_wincon': user_wincon, 'user': user, }
    return render(request, 'gametracker_app/gametracker.html', context=context)


@login_required(login_url='my-login')
def update_game(request, game_id):
    game = Game.objects.get(pk=game_id)
    form = UpdateGameForm(request.POST or None, instance=game)
    if form.is_valid():
        form.save()
        return redirect('/view-games')

    context = {'game': game, 'form': form}
    return render(request, 'gametracker_app/update-game.html', context=context)

在 forms.py 中,我试图将日期和时间字段“设置”为之前的值。这就是我将“deck”选项设置为“user_deck_list”所做的操作,但我不知道如何获取日期/时间的值来设置该值,因为我在模型中使用 auto_now=True 。

class UpdateGameForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(UpdateGameForm, self).__init__(*args, **kwargs)
        self.fields['date'] = 'date'
        self.fields['time'] = 'time'
django django-models django-views django-forms
1个回答
0
投票

您可以使用

auto_now=True
,而不是使用
auto_now_add=True
。当对象被创建时,它会保留一个时间戳。

© www.soinside.com 2019 - 2024. All rights reserved.