简体   繁体   中英

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

I'm doing an assignment for Uni from Python/Django. One of the things I have to do is to create a form where a user can create a new "tournament" on the website. Frontend doesn't matter at all.

I created a model, added some tournaments from the Admin panel and that works fine. But when I try to create a new tournament from the form, and click the sumbit button, I get redirected to my home page (even though nothing specifies in the HTML or views.py that this should happen), I get no error, no data posted and no info back from the command line.

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>

As you can see in the views.py I tried to check for at least any errors as suggested on some other post years ago, but I get NO response back. In the command line i see it as such:

[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

I have absolutely no experience in WebDev and no experience in Django. Can you please help me identify problem? If there was at least some error response or anything like that.

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

Oh, but you're specifying that, quite explicitly. :-)

You're POSTing to / , not /new-tournament (your TournamentView).

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

Get rid of the action to post to the current URL instead.

<form method="POST">

Additionally, you can simplify your TournamentView to a CreateView :

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

(yes, that should be all)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM