如何将字段值作为参数传递给下一个视图 Django?

How do I pass field value as argument to next view Django?

我在 Django 文档中找不到在不同函数视图之间传递值的方法。我想在我的 create_player_view 中创建一个对象,捕获该新对象 pk 并将其传递给 scoring_view。通过表单操作字段执行此操作未成功,因为视图之间没有数据传递。执行此操作的更好方法是什么?

我想要一个简单的行为,它获取在 create_player_view 中创建的匹配 ID,并将其传递给 update/use 到 scoring_view

型号

class Players(models.Model):
    matchID = models.AutoField(primary_key=True)
    player1Name = models.CharField(max_length=10)
    player2Name = models.CharField(max_length=10)

    def __str__(self):
        return f'{self.matchID}: {self.player1Name} vs {self.player2Name}'

class Scores(models.Model):
    matchID = models.OneToOneField(Players, on_delete=models.CASCADE, related_name='match')
    p1_set_1_score = models.IntegerField(default=0)
    p1_set_2_score = models.IntegerField(default=0)
    p1_set_3_score = models.IntegerField(default=0)
    p1_set_4_score = models.IntegerField(default=0)


    p2_set_1_score = models.IntegerField(default=0)
    p2_set_2_score = models.IntegerField(default=0)
    p2_set_3_score = models.IntegerField(default=0)
    p2_set_4_score = models.IntegerField(default=0)
  

    def __str__(self):
        return f'{self.matchID}: '

观看次数

def create_player_view(request):
    """
    allows users to name two 
    players competing vs one another
    """
    if request.method == "POST":
        form  = PlayerForm(request.POST)
        
        if form.is_valid():
            form.save(commit=True)
            return redirect('tennis:m_score') #is it possible to pass this view created instance?
        else:
            message = "Form could not be completed"

        return render(request, "create_player.html", {"message":message})

    else:
        form  = PlayerForm()
    return render(request, "create_player.html", 
            {'form': form})
    

def scoring_view(request):
    """
    View allows user to select the participating 2 players
    and record their scores per set.
    """
   
    if request.method == "POST":
        
        form = ScoresForm(request.POST )#, instance=player_instance)

        if form.is_valid():
            form.save(commit=True)
            return redirect('tennis:m_results')
   
    else:
        form = ScoresForm()
        
    return render(request, "now_playing.html", {'form':form})     #todo add filtering

forms.py



class PlayerForm(ModelForm):
    class Meta: 
        model = Players

        exclude = ('matchID',)
        labels = {
            'playerName':('Player 1 Name', 'Player 2 Name'),
        }


class ScoresForm(ModelForm):
    class Meta:
        model = Scores

        fields = "__all__"

###urls.py

from django.urls import path
from tennis import views



app_name="tennis"

urlpatterns = [
    path('players/', views.create_player_view, name="c_pl"),
    path('scoring/<new_player>/', views.scoring_view, name="m_score"),
    path('summary/', views.match_summary_view, name="m_results"),
]

编辑您的观点:

def create_player_view(request):
    """"
    allows users to name two 
    players competing vs one another
    """
    if request.method == "POST":
        form  = PlayerForm(request.POST)
        
        if form.is_valid():
            new_player = = form.save(commit=True)
            return redirect('tennis:m_score', new_player=new_player)  # If you want to pass the pk instead of the object itself write: new_player=new_player.pk
        else:
            message = "Form could not be completed"

        return render(request, "create_player.html", {"message":message})

    else:
        form  = PlayerForm()
    return render(request, "create_player.html", 
            {'form': form})
    


def scoring_view(request, new_player):
    """"
    View allows user to select the participating 2 players
    and record their scores per set.
    """
    if request.method == "POST":
        # You can use the value of new_player as your needs
        data = request.POST
        data['matchID'] = new_player
        form = ScoresForm(data)

        if form.is_valid():
            form.save(commit=True)
            return redirect('tennis:m_results')
   
    else:
        form = ScoresForm()
        
    return render(request, "now_playing.html", {'form':form})     #todo add filtering