如何让用户只使用POST方法生成一个“bet”对象的实例,并通过PUT方法修改它(例如)
forms.py
class BetForm(forms.ModelForm):
team1_score = forms.IntegerField(min_value=0, max_value=15)
team2_score = forms.IntegerField(min_value=0, max_value=15)
match = forms.ModelChoiceField(queryset=Match.objects.only('id'))
class Meta:
model = Bet
fields = ('team1_score', 'team2_score', 'match')
models.py
class Bet(models.Model):
match = models.ForeignKey(Match, on_delete=models.CASCADE, related_name='+')
team1_score = models.PositiveIntegerField(default=0)
team2_score = models.PositiveIntegerField(default=0)
def __str__(self):
return (str(self.match))
views.py
def post(self, request):
form = BetForm(request.POST)
if form.is_valid():
form.save()
team1_score = form.cleaned_data.get('team1_score')
team2_score = form.cleaned_data.get('team2_score')
match = form.cleaned_data.get('match')
form = BetForm()
return redirect ('home')
args = {'form': form, 'team1_score': team1_score, 'team2_score': team2_score, 'match': match}
return render(request, self.template_name, args)
答案 0 :(得分:2)
使用户只能生成一个对象的实例“下注”......
为此,您需要在Bet
模型中添加用户字段。在这里,您将保存对发出请求的用户的引用。
class Bet(models.Model):
user = models.ForeignKey(AUTH_USER_MODEL, related_name='bets', blank=True)
match = models.ForeignKey(Match, related_name='bets')
team1_score = models.PositiveIntegerField(default=0)
team2_score = models.PositiveIntegerField(default=0)
class Meta:
unique_together = ('user', 'match')
def __str__(self):
return (str(self.match))
注意unique_together
选项,确保用户只能为给定的匹配创建一个Bet实例。
通过PUT方法(例如)修改它
Django不像POST那样自动解析PUT请求的正文。浏览器通常会在表单提交时发出POST请求。如果您仍想使用PUT解决它,请查看此帖子(双关语)。
Parsing Unsupported Requests (PUT, DELETE, etc.) in Django
我的建议是修改您的帖子视图,使其接受可选参数bet_id
。这可以在urlpatterns中定义。然后视图看起来像这个。如果提供了bet_id,您可以检索赌注并将其传递给表格。这样它就能理解用户正在修改它。
def post(self, request, bet_id=None):
if bet_id:
bet = Bet.objects.get(pk=bet_id)
form = BetForm(request.POST, instance=bet)
else:
form = BetForm(request.POST)
if form.is_valid():
bet = form.save(commit=False)
bet.user = request.user
bet.save()
# Do what you want here
请注意,我们不会立即保存表单(commit=False
),因此我们稍后可以将其分配给用户。此用户是request
对象的登录用户。