Django实现音乐网站 ⑾
在这个问题中,我们将会实现在Django音乐网站中用户可以创建和编辑音乐专辑的功能。
首先,我们需要在music/templates/music/album_form.html
文件中创建一个表单模板:
<!-- templates/music/album_form.html -->
{% extends "music/base.html" %}
{% block content %}
<h1>{% block title %}New Album{% endblock %}</h1>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Save</button>
</form>
{% endblock %}
然后,在music/views.py
中添加创建和编辑视图:
# views.py
from django.shortcuts import render, get_object_or_404, redirect
from django.urls import reverse
from .models import Album
from .forms import AlbumForm
def create_album(request):
if request.method == "POST":
form = AlbumForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect(reverse("music:index"))
else:
form = AlbumForm()
return render(request, "music/album_form.html", {"form": form})
def edit_album(request, pk):
album = get_object_or_404(Album, pk=pk)
if request.method == "POST":
form = AlbumForm(request.POST, request.FILES, instance=album)
if form.is_valid():
form.save()
return redirect(reverse("music:index"))
else:
form = AlbumForm(instance=album)
return render(request, "music/album_form.html", {"form": form, "edit": True})
最后,在music/urls.py
中添加URL模式:
# urls.py
from django.urls import path
from .views import create_album, edit_album
urlpatterns = [
path("album/add/", create_album, name="create_album"),
path("album/<int:pk>/edit/", edit_album, name="edit_album"),
]
这样,用户就可以通过访问/album/add/
来创建新专辑,或者通过访问/album/<int:pk>/edit/
来编辑现有的专辑,其中<int:pk>
是专辑的主键。
评论已关闭