简体   繁体   English

Python Django 表单提交按钮无法按预期工作

[英]Python Django Form submit button not working as desired

I have been trying to learn Django.我一直在努力学习 Django。 I am stuck on this form part.我被困在这个表格部分。 A form has been created that allows the user to create an Album object where they can fill in the Artist, Album Name, Genre and upload an Album Logo.已经创建了一个表单,允许用户创建专辑 object,他们可以在其中填写艺术家、专辑名称、流派并上传专辑徽标。 When I fill in the fields and then click submit, it should then redirect me to the details page for that particular Album that just got created.当我填写字段然后单击提交时,它应该会将我重定向到刚刚创建的特定专辑的详细信息页面。 But nothing appears to happen when clicking the submit button and the object does not get created.但是单击提交按钮时似乎没有任何反应,并且没有创建 object。

Here is the models.py code that contains an Album class with 4 fields;这是包含 4 个字段的专辑 class 的 models.py 代码; artist, album_name, genre and album_logo.艺术家、专辑名称、流派和专辑徽标。

from django.db import models
from django.urls import reverse

# Create your models here.
class Album(models.Model):
    artist = models.CharField(max_length=250)
    album_name = models.CharField(max_length=500)
    genre = models.CharField(max_length=100)
    album_logo = models.ImageField()

    def get_absolute_url(self):
        return reverse('music:detail', kwargs={'pk':self.pk})

    def __str__(self):
        return self.album_name + " - " + self.artist

class Song(models.Model):
    album = models.ForeignKey(Album, on_delete=models.CASCADE)
    file_type = models.CharField(max_length=100)
    song_title = models.CharField(max_length=250)
    is_favourite = models.BooleanField(default=False)

    def __str__(self):
        return self.song_title

Here is the album_form.html code which contains the actual form.这是album_form.html 代码,其中包含实际表单。 I have not used crispy_forms as I am not familiar with Bootstrap though I know CSS.虽然我知道 CSS,但我对 Bootstrap 并不熟悉,因此我没有使用过 crispy_forms。

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

{% block title %}Add a New Album{% endblock %}
{% block body %}
    <form class="formContainer" method="post" enctype="multipart/form-data">
        {% csrf_token %}
        {% for field in form %}
            {% if field.label != 'Album logo' %}
                <label for="field{{ forloop.counter }}">{{ field.label }}</label>
                <input type="text" id="field{{ forloop.counter }}" name="" value="">
            {% else %}
                <label for="field{{ forloop.counter }}">{{ field.label }}</label>
                <input type="file" id="field{{ forloop.counter }}" name="" value="" accept="image/*">
            {% endif %}
            <br>
        {% endfor %}
        <input type="submit" id="submitBtn" name="" value="Add">
    </form>
{% endblock %}

This is views.py code where I have made use of class based views and not function based views.这是 views.py 代码,其中我使用了基于 class 的视图,而不是基于 function 的视图。

from django.views import generic from.models import Album, Song from django.views 导入通用 from.models 导入专辑、歌曲

# Create your views here.
class IndexView(generic.ListView):
    template_name = 'music/index.html'
    queryset = Album.objects.all()
    context_object_name = 'all_albums'


class DetailView(generic.DetailView):
    model = Album
    template_name = 'music/detail.html'


class AlbumCreate(generic.CreateView):
    model = Album
    fields = ['artist', 'album_name', 'genre', 'album_logo']

    def form_valid(self, form):
        return super().form_valid(form)

and finally this is my urls.py code:最后这是我的 urls.py 代码:

from django.urls import path, include
from . import views

app_name='music'

urlpatterns = [
    #/music/
    path('', views.IndexView.as_view(), name='index'),

    #/music/5/
    path('<int:pk>/', views.DetailView.as_view(), name='detail'),

    #/music/album/add/
    path('album/add/', views.AlbumCreate.as_view(), name='album-add')
]

After clicking the submit button in the form, it should take me to the "detail" url for the primary key of the Album that got created.单击表单中的提交按钮后,它应该带我到“详细信息” url 以获取创建的专辑的主键。 Am I missing something here?我在这里错过了什么吗?

In your views.py you need to override the get_success_url function in your CreateView and pass the id as an argument while redirecting.在您的 views.py 中,您需要覆盖 CreateView 中的 get_success_url function 并在重定向时将 id 作为参数传递。

class AlbumCreate(generic.CreateView):
    model = Album
    fields = ['artist', 'album_name', 'genre', 'album_logo']

    def form_valid(self, form):
        return super().form_valid(form)

    def get_success_url(self):
        return reverse('music:detail', args=(self.object.id,))

Seems you forgot to put action to your <form> tag似乎您忘记对<form>标记执行action

Try this尝试这个

<form class="formContainer" action='{% url 'music:album-add'%}' method="post" enctype="multipart/form-data">

Edit: Also add success url using get_success_url function in your AlbumCreate view to redirect user to album detail page, like was mentioned in above answer编辑:还在AlbumCreate视图中使用get_success_url function 添加成功 url 以将用户重定向到专辑详细信息页面,就像上面的答案中提到的那样

from django.urls import reverse_lazy
...
class AlbumCreate(generic.CreateView):
    ...
    def get_success_url(self, **kwargs):
        return reverse_lazy('music:detail', args = (self.object.id,))

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

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