为什么 Django 的 POST 什么都不做——甚至连错误都没有?

Why Django's POST doesn't do anything - not even an error?

我正在为 Python/Django 的 Uni 做作业。我必须做的一件事是创建一个表单,用户可以在其中在网站上创建一个新的“锦标赛”。前端根本不重要。

我创建了一个模型,从管理面板添加了一些锦标赛,效果很好。但是当我尝试从表单创建一个新锦标赛并单击 sumbit 按钮时,我被重定向到我的主页(即使在 HTML 或 views.py 中没有指定应该发生这种情况),我没有收到任何错误,没有数据 posted,也没有从命令行返回信息。

models.py

class Tournament(models.Model):
    title = models.CharField(max_length=30)
    creator = models.OneToOneField(User, on_delete=models.CASCADE)
    players = models.ManyToManyField(User, related_name="players",)
    created_date = models.DateField(auto_now=True)
    start_date = models.DateField(auto_now=True)
    max_players = models.IntegerField(
        null=True, validators=[MinValueValidator(2), MaxValueValidator(64)])
    slug = models.SlugField(unique=True, db_index=True)

    def __str__(self):
        return f"{self.title} \n {self.creator} \n {self.max_players}"

Forms.py

class TournamentForm(forms.ModelForm):
    class Meta:
        model = Tournament
        #exclude = ["slug"]
        fields = "__all__"

views.py

class TournamentView(View):
    def get(self, request):
        form = TournamentForm()
        print(form.errors)
        return render(request, "tournament_app/new_tournament.html", {
            "form": form
        })

    def post(self, request):
        form = TournamentForm(request.POST)

        if form.is_valid():
            print(form.errors)
            form.save()
            return redirect("/thank-you")
        print(form.errors)
        return render(request, "tournament_app/new_tournament.html", {
            "form": form
        })

new_tournament.html

{% extends "base.html" %}

{% block title %} Create New tournament {% endblock title %}

{% extends "base.html" %}

{% block title %}
Create New tournament
{% endblock title %}

{% block content %}
<form action="/" method="POST">
    {% csrf_token %}
    {% for field in form%}
        <div class="form-control">
            {{field.label_tag}}
            {{field}}
        </div>
    {% endfor %}
    <button type="submit">Send</button>
</form>

base.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}{% endblock title %}</title>
</head>
<body>
    
    {% if user.is_authenticated %}
        <p style="text-align:right;">You are logged in as <b>{{user.username}}</b></p>
    {% else %}
        <p style="text-align:right;"><b>Anonymous user</b></p>
    {% endif %}
    <a href="{% url "index-page" %}"><button type = "button"> Main Page </button></a>
    <a href="{% url "login" %}"><button type = "button"> Login </button></a>
    {% block content %}{% endblock content %}
</body>
</html>

正如您在 views.py 中看到的那样,我尝试至少检查其他 post 年前建议的任何错误,但我没有得到任何回复。 在命令行中,我是这样看的:

[22/Jul/2021 13:33:10] "GET /new-tournament HTTP/1.1" 200 1839
[22/Jul/2021 13:33:19] "POST / HTTP/1.1" 200 744

我完全没有 WebDev 经验,也没有 Django 经验。你能帮我找出问题吗?如果至少有一些错误响应或类似的东西。

I get redirected to my home page (even though nothing specifies in the HTML or views.py that this should happen)

哦,但是您明确指出了这一点。 :-)

您发布到 /,而不是 /new-tournament(您的 TournamentView)。

<form action="/" method="POST">

去掉原来的action,改为post,改为现在的URL。

<form method="POST">

此外,您可以将 TournamentView 简化为 CreateView:

class TournamentView(CreateView):
    model = Tournament
    template_name = "tournament_app/new_tournament.html"
    success_url = "/thank-you"

(是的,应该是全部)