我希望views.py中的print(request.method)语句在下面返回POST。我已经看到了request.method是POST的其他代码示例。但是我的代码只输出GET:
TEST1
GET
我可以看到,当我提交信息https://imgur.com/a/BSLLAgB
时,表单正在发送POST数据经过一番挖掘后,我发现HTTP并不是为了重定向POST数据而设计的:
https://softwareengineering.stackexchange.com/questions/99894/why-doesnt-http-have-post-redirect
但是请我为什么我的代码会重定向此POST数据?我希望我的观点返回“POST”而不是“GET”,因为我没有使用HttpResponseRedirect。想了解为什么会发生这种情况以及我可以做些什么来阻止Django重定向POST数据以获得GET。我错过了什么?
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name = 'index'),
path('add_coin/', views.add_coin, name = 'add_coin'),
path('register/', views.register, name = 'register'),
path('login/', views.user_login, name='login'),
path('logout/', views.user_logout, name='logout')
]
forms.py
class PortfolioForm(forms.ModelForm):
coin = forms.ModelChoiceField(queryset = Coin.objects.all())
amount = forms.IntegerField()
trade_price = forms.DecimalField(decimal_places = 2)
field_order = ['coin', 'amount', 'trade_price']
class Meta:
model = Portfolio
fields = {'coin', 'amount', 'trade_price', 'user'}
exclude = ['user']
add_coin.html
<form action="{% url index %)" method="post" name="add_coin">
<table>
{{ form }}
</table>
{% csrf_token %}
<input type="submit" name="add_coin" formmethod="post" value="Add Coin">
</form>
索引视图(views.py)
def index(request):
portfolio_list = []
for coin in Portfolio.objects.filter(user = request.user): #(user = request.user.username):
portfolio_dict = {}
coin_str = str(coin.coin)
portfolio_dict['coin'] = coin_str
portfolio_dict['amount'] = coin.amount
portfolio_dict['symbol'] = GetCoin(coin_str).symbol
portfolio_dict['price'] = GetCoin(coin_str).price
portfolio_dict['value'] = GetCoin(coin_str).price * coin.amount
portfolio_dict['last_updated'] = GetCoin(coin_str).last_updated
portfolio_dict['daily_change'] = GetCoin(coin_str).percent_change_24h
portfolio_dict['gains'] = coin.trade_price - GetCoin(coin_str).price
portfolio_list.append(portfolio_dict)
#print(portfolio_list)
def get_top_coins(limit): # display coins if no user is logged in
data = requests.get("https://api.coinmarketcap.com/v1/ticker/?limit={}".format(limit)).json()
y = 0
coin_list = {
"image": [],
"name": [],
"price": [],
"symbol": [],
"market_cap": []
}
for x in data:
coin_list["name"].append(data[y]['name'])
coin_list["price"].append(data[y]['price_usd'])
coin_list["symbol"].append(data[y]['symbol'])
coin_list["market_cap"].append(data[y]['market_cap_usd'])
y += 1
return coin_list
coin_list = get_top_coins(20)
for x in coin_list["name"]:
image = "{}.png".format(x)
coin_list["image"].append(image)
context_dict = {'portfolio_list': portfolio_list, 'coin_list': zip(coin_list["image"], coin_list["name"], coin_list["price"], coin_list["market_cap"])}
return render(request, 'myportfolio/index.html', context = context_dict)
add_coin view(Views.py):
def add_coin(request):
print("test 1")
print(request.method)
form = PortfolioForm()
if request.method == "POST":
form = PortfolioForm(request.POST)
if form.is_valid():
print("test 2")
obj = form.save(commit = False)
obj.user = request.user
obj.save()
else:
print(form.errors)
return render(request, 'myportfolio/add_coin.html', {'form': form})
答案 0 :(得分:1)
表单似乎由add_coin
视图处理,因此您应该更改表单操作以发布到该表单。
<form action="{% url 'add_coin' %}" method="post" name="add_coin">
然后我希望看到
test1
GET
当您对add_coin
视图执行初始GET请求时,
test1
POST
当您使用POST请求提交表单时。