我是Django的新手,我正在尝试创建一个简单的网页,如果这看起来非常简单或简单,那就很抱歉。目前我有这些模型:
class Fighter(models.Model):
name = models.CharField(max_length=50)
rating = models.DecimalField(default=1600, max_digits=8, decimal_places=2)
url = models.URLField(default='')
class Fight(models.Model):
member1 = models.ForeignKey(Fighter, related_name='fighter_1')
member2 = models.ForeignKey(Fighter, related_name='fighter_2')
我希望每次刷新页面时显示一个随机的战斗,并且它是关联的成员,然后有一个单选按钮(或类似的东西),允许用户选择他们认为会赢的人。
我认为我需要使用表单来执行此操作,但在阅读了大量Django文档后,我不知道如何执行此操作。有人可以解释一下让我这么做的最好方法!
我一直在使用基于类的视图,这是正确的做法吗?如果我没有提供足够的代码,请告诉我。
答案 0 :(得分:0)
为了跟踪被引用的战斗实例,我使用了URL来提及战斗ID。每次用户访问(主页)页面时,都会创建一个新的战斗实例。然后视图将重定向到该战斗形式的URL。
from django.conf.urls import patterns, include, url
from fights.views import FightView, random_fight
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', random_fight, name='home'),
url(r'^fight/(?P<fight_id>\d+)/$', FightView.as_view(), name='fight_view'),
url(r'^admin/', include(admin.site.urls)),
)
表单将使用动态创建的单选框进行初始化,其中包含作为关键字参数传递的战士名称。
from django import forms
from .models import Fighter
class FighterSelectForm(forms.Form):
def __init__(self, *args, **kwargs):
choices = kwargs.pop("choices", [])
super(FighterSelectForm, self).__init__(*args, **kwargs)
self.fields["fighter_choices"] = forms.ChoiceField(
widget=forms.RadioSelect,
choices=choices)
random_fight()
创建一个包含两个随机Fight
成员的新Fighter
个实例,并重定向到相应的fight_view
。 FightView
类重写get_form()
函数以从Fight对象传递战斗机名称,而Fight对象又从URL派生。
from django.shortcuts import render
from .models import Fight, Fighter
from .forms import FighterSelectForm
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.views.generic.edit import FormView
def random_fight(request):
fighters = Fighter.objects.order_by("?")[:2]
fight = Fight.objects.create(member1=fighters[0], member2=fighters[1])
return HttpResponseRedirect(reverse('fight_view', kwargs={"fight_id": str(fight.id)}))
class FightView(FormView):
template_name = 'fight.html'
success_url = '/thanks/' # Not defined here
def get_form(self, form_class):
fight = Fight.objects.get(id=self.kwargs.get("fight_id"))
choices = [(fight.member1.id, fight.member1.name),
(fight.member2.id, fight.member2.name)]
kwargs = super(FightView, self).get_form_kwargs()
kwargs.update({"choices": choices})
form = FighterSelectForm(**kwargs)
return form
def form_valid(self, form):
selected = Fighter.objects.get(id=form.cleaned_data['fighter_choices'])
selected.rating += 100 # Use any logic to change rating here
selected.save()
print("Fighter selected: {}".format(selected.name))
return super(FightView, self).form_valid(form)
<form action="" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>