如何通过登录用户从模板数据保存模型中的查询集?

时间:2019-07-05 16:23:42

标签: django django-models django-templates django-views

在型号中:

class Match(models.Model):
    user = models.ManyToManyField(User, blank=True)
    match_name = models.CharField(max_length=20, help_text='Enter the name of 2 team using vs (eg. ban vs ind)')
    first_team = models.ForeignKey('FirstTeam', on_delete=models.SET_NULL, null=True)
    second_team = models.ForeignKey('SecondTeam', on_delete=models.SET_NULL, null=True)
    tournament_name = models.ForeignKey('TournamentName', on_delete=models.SET_NULL, null=True)
    match_created = models.DateTimeField(auto_now_add=True)
    match_stated = models.DateTimeField(default=timezone.now())

在视图中:

def league(request, pk):
    match = Match.objects.all()

    context = {
        'match': match,
    }
    return render(request, 'main/league.html', context=context)

在模板中:

{% for match in match %}
  <div class="row text-center py-2">
    <div class="col-3">
      <img src="{{ match.first_team.flag.url }}" alt="image" class="team-image">
      <h6>{{ match.first_team.name }}</h6>
    </div>
    <div class="col-6" style="font-size: 14px;">
      <p>{{ match.tournament_name }}</p>
      <div>Starts On: <div style="color: red;">{{ match.match_stated|date:"d F, Y. h:i A" }}</div></div>
    </div>
    <div class="col-3">
      <img src="{{ match.second_team.flag.url }}" alt="image" class="team-image">
      <h6>{{ match.second_team.name }}</h6>
    </div>
  </div>
  <button type="button" class="btn btn-danger btn-sm">join</button>
{% endfor %}

在我的管理站点中,我为模型添加了许多数据,但没有user字段,并且在templates中显示了该查询集。这工作正常。

现在,我需要保存user中登录templates的查询集。在template中,当users选择我的内置查询集时,查询集将与选择它的models保存在user中。每个user都可以选择与templates不同的数据,并且数据将添加到models中存储在我的user的新行中。

使用formmodels可以将查询集保存在user中。这样,我需要通过models将查询集保存到我的user中。但是在这里我不能使用form。我需要从templates querset中保存它。 user选择我的数据(通过单击加入按钮)时,它将保存在我的models中。

我该怎么做?

0 个答案:

没有答案
相关问题