Django表单不渲染?(无模型)



所以我的Django表单没有在html中呈现。

我只能看到Get Rank文本。我不确定是不是因为我没有模型,或者也许是我的html有问题?

如果你需要看到任何其他让我知道不确定什么是错的,我也试过只是做这一切都在home函数,但它不渲染html在所有。

侧面问题-我也只打算抓取用户名,并在他们的名字("JohnDoeNA#1")之外的标签,所以我可能使用get方法正确?

编辑:固定的按钮不工作,现在唯一不呈现的是形式。(Mis-spelling)

更新的代码是正确的。

views.py: 
from urllib import response
from django.shortcuts import render
from django.http import HttpResponse
import requests
from .forms import SearchUser
import json
# Create your views here.

def index(response):
return render(response, "main/base.html")

def home(response):
form = SearchUser()
data = requests.get(
'https://americas.api.riotgames.com/riot/account/v1/accounts/by-riot-id/ReallyBlue/NA1?api_key=RGAPI-ee8fcdce-05c5-4ad4-b909-8efa722b1134')
userid = data.json()['puuid']
return render(response, "main/home.html", {
'form': form,
'userid': userid,
# 'mmr': apidata['rank']
})

forms.py:

from django import forms

class SearchUser(forms.Form):
name = forms.CharField(label="Name", max_length=200)

urls . py:

from django.urls import path
from . import views

urlpatterns = [
path("", views.index, name="index"),
path("home/", views.home, name="home")
]

home:

{% extends 'main/base.html'%}

{% block content %}
<h2>Valorant Ranked Checker</h2>
<form method="post" action="/home/">
{{form}}
<button type="submit", name="search">
Get rank
</button>
</form>
<p><strong>{{userid}} - {{mmr}}</strong></p>
{% endblock %}

base.html:

<!DOCTYPE html>
<head>
<title>Blue's Valorant Ranked Checker</title>
</head>
<body>
<div id="content", name="content">
{% block content %}
{% endblock %}
</div>
</body>
</html>

这里有两个主要问题:

  1. 你正在渲染你的基模板作为你的根目录(base.html),因此Django的模板继承不能正常工作。如果你想让模板继承正常工作,你需要渲染子模板(包含extends的那个)。
  2. 你需要把你的Django表单(SearchUser)传递给视图的render函数

我建议做这些修改:

====================

删除urls.py中对index视图的引用,因为我们不需要它。相反,使用home子模板作为根视图:

urls . py:

from django.urls import path
from . import views
urlpatterns = [
path("", views.home, name="home")
]

====================

views.py中删除不再需要的index函数。你还需要在Django的render快捷方式函数中传递引用到你的表单(SearchForm)。

views.py:

from urllib import response
from django.shortcuts import render
from django.http import HttpResponse
import requests
from .forms import SearchUser
import json
# Create your views here.
def home(response):
data = requests.get(
'https://americas.api.riotgames.com/riot/account/v1/accounts/by-riot-id/ReallyBlue/NA1?api_key=RGAPI-APIKEY')
userid = data.json()['puuid']
return render(response, "main/home.html", {
'form': SearchUser(), # include reference to your form
'userid': userid,
# 'mmr': apidata['rank']
})

def search(response):
form = SearchUser()
return render(response, "main/home.html", {"form": form})

呈现表单的视图函数和表单模板必须匹配。form也必须在你的上下文中。

将表单放入home.html中,并更改home视图,如下所示:

def home(response):
form = SearchUser()
return render(response, "main/home.html", {'form': form})

最新更新