简体   繁体   English

Django:为什么我的表单发送POST数据却返回request.method GET?

[英]Django: Why is my form sending POST data but returning request.method GET?

I expect the print(request.method) statement in my views.py to return POST below. 我希望我的views.py中的print(request.method)语句返回下面的POST。 I have seen other examples of code where request.method is POST. 我已经看到了request.method是POST的其他代码示例。 However my code simply outputs GET: 但是我的代码只是输出GET:

test1 TEST1

GET 得到

I can see that the form is sending POST data when I submit the info https://imgur.com/a/BSLLAgB 当我提交信息https://imgur.com/a/BSLLAgB时,我可以看到表单正在发送POST数据

After a bit of digging I found that HTTP is not designed to redirect POST data: 经过一番挖掘,我发现HTTP并非旨在重定向POST数据:

https://softwareengineering.stackexchange.com/questions/99894/why-doesnt-http-have-post-redirect https://softwareengineering.stackexchange.com/questions/99894/why-doesnt-http-have-post-redirect

But leads me to ask why is my code redirecting this POST data ? 但是导致我问为什么我的代码重定向这个POST数据 I would expect my views to return "POST" not "GET" because I'm not using a HttpResponseRedirect for example. 我希望我的视图返回“ POST”而不是“ GET”,因为例如,我没有使用HttpResponseRedirect。 Would like to understand why this happening and what I can do to stop Django redirecting that POST data to get GET. 想了解为什么会发生这种情况,以及我如何才能阻止Django重定向该POST数据以获取GET。 What am I missing? 我想念什么?

urls.py 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 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 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>

Index view (views.py) 索引视图(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): add_coin视图(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})

The form appears to be handled by the add_coin view, so you should change the form action to post to it. 该表单似乎由add_coin视图处理,因此您应该更改表单操作以将其发布到该视图。

<form action="{% url 'add_coin' %}" method="post" name="add_coin">

Then I would expect to see 那我期望看到

test1

GET

when you do the initial GET request to the add_coin view, and 当您对add_coin视图执行初始GET请求时,以及

test1

POST

when you submit the form with the POST request. 当您使用POST请求提交表单时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我的 Django request.method 是“GET”而不是“POST”? - Why does my Django request.method is 'GET' not 'POST'? Django 文件上传表单:如果 request.method==“POST” 失败 - Django File Upload form: if request.method==“POST” fails request.method == &#39;POST&#39; 在 Django 中不起作用 - request.method == 'POST' is not working in Django Django "如果 request.method == 'POST':" 返回 False - Django "if request.method == 'POST':" returns False Django Test request.method ==&#39;POST&#39;不起作用 - Django Test request.method == 'POST' not working Django request.method =&#39;GET&#39;无法正常工作 - Django request.method = 'GET' not working django 中 request.method 的问题,它无法识别 POST 而是将 GET 显示为请求方法 - Problem with request.method in django which is not recognising POST instead it is showing GET as request method 为什么request.files中的request.method ==&#39;POST&#39;和&#39;photo&#39; - Why is if request.method == 'POST' and 'photo' in request.files DJango 不执行 request.method == "post" 与 ajax 数据提交 - DJango doesn't execute request.method == "post" with ajax data submission python flask:如果request.method == &#39;POST&#39;,则附加到表单 - python flask: append to form if request.method == 'POST'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM