我目前正在尝试为视频游戏制作计算器。我希望用户能够从视频游戏中选择角色,然后网页计算有关所选角色的统计信息。到目前为止,我所拥有的只是一个页面,该页面显示了到目前为止数据库中每个字符的名称列表。我希望用户能够从列表中选择一个字符,然后程序从数据库中获取有关该字符的数据,并对其进行一些计算。
我对models.py有足够的了解,目前我想在这里工作的几乎所有东西。我不知道下一步要走什么方向。我的猜测是同时编辑视图和HTML文件。这就是我目前的看法。角色被命名为单位,如果您熟悉游戏,角色就可以像职业班一样发挥角色。
from django import forms
from .models import Unit
from .models import Class
# Create your views here.
def index(request):
unit_list = Unit.objects.order_by("unit_name")
context = {'unit_list': unit_list}
return render(request, 'calc/index.html', context)
def unit(request, unit_id):
try:
unit = Unit.objects.get(pk=unit_id)
except Unit.DoesNotExist:
raise Http404("Unit does not exist")
return render(request, 'calc/unit.html', {'unit': unit})
#does calculations based on the selected character
def calcStats(currentUnit, currentClass):
hp = max(currentClass.hp_class_base, currentUnit.hp_base + currentClass.hp_class_mod + ((currentUnit.hp_growth * currentUnit.unit_level)/10.0) + ((currentClass.hp_class_growth * currentClass.class_level)/10.0))
hp = min(hp, currentUnit.hp_cap)
stats = [hp]
#grabs the character and other info from the database
class unitSelect(forms.Form):
currentUnit = forms.ChoiceField(label="unit", choices=[(unit.id, unit.unit_name) for unit in Unit.objects.all()])
currentClass = forms.ChoiceField(label="Class", choices=[(Class.id, Class.class_name) for Class in Class.objects.all()])
{% if unit_list %}
<ul>
{% for unit in unit_list %}
<li>{{ unit.unit_name }}</li>
{% endfor %}
</ul>
{% else %}
<p>No units are available.</p>
{% endif %}
我在正确的轨道上吗?我还应该添加什么,接下来我应该做什么?我尝试查看django教程,实际上我在高中和大学时参加了一些Web开发课程,但是我仍然觉得我每次都学不到任何东西。您有什么好的资源推荐吗?对不起,如果感觉到我问了太多问题。
好吧,首先,您将从.com之后截取的URL称为终结点,让我们在Javascript中称为终结点以获取数据
在字符选择中,更改字符后运行此
axios.get('mywebsite.com/my_endpoint/').then((response)=> { // do something with response});
仅通过使用GET-POST请求从服务器获取数据,您已经创建了视图,现在创建特定于您的应用程序的urls.py文件
# myApp/urls.py
from .views import unit # of course this is wrong, I'm just taking unit as example
from django.urls import path
urlpatterns = [
path('my_endpoint/',unit),
]
这是我们要在其上调用GET的端点“ my_endpoint /”,它将调用单元函数,处理字符切换行为的逻辑,然后根据需要返回HttpResponse或JSONResponse。顺便说一句,请求的技术称为AJAX,这是ASYNC Javascript。我们在不阻塞客户端的情况下调用服务器,并等待服务器的响应。
[如果出于某种原因使用jQuery,则没有必要使用axios,here's我的旧答复用jQuery解释了AJAX。Here's附带说明,您很快就会提出问题,请随时查看。