我需要填写字段名称和图像以上传到 Django DB,但我无法使用 HTML 的表单标签来更新它
views.py
"""Artist views."""
# Django
from django.shortcuts import render, redirect
from django.views import View
from django.http import HttpResponse
# Models
from music.models import Artist
# Forms
from artist.forms import ArtistForm
class AddArtistView(View):
"""Adding new artist."""
def upload_image(request):
if request.method == 'POST':
form = ImageUploadForm(request.POST, request.FILES)
if form.is_valid():
m = Artist.objects.get(pk=image_id)
m.model_pic = form.cleaned_data['image']
m.save()
return HttpResponse('Image upload success')
return HttpResponseForbidden('Allowed only via POST')
template = "artist/create_artist.html"
def get(self, request):
"""Render add artist form."""
form = ArtistForm()
context = {"form": form}
return render(request, self.template, context)
def post(self, request):
"""Receive and validate add artist form."""
form = ArtistForm(request.POST)
if not form.is_valid():
context = {"form": form}
print(form.errors)
return render(request, self.template, context)
new_artist = Artist.objects.create_artist(
name=form.cleaned_data["name"],
)
return HttpResponse("<h1>Artist Added!</h1>")
models.py
"""Music Models"""
from django.db import models
class Artist(models.Model):
"""Artist Model."""
name = models.CharField(max_length=200)
image = models.ImageField(null=True, upload_to='artists/images/')
def __str__(self):
"""Get str representation."""
return self.name
def __repr__(self):
"""Get str representation."""
return self.__str__()
forms.py
"""Artist forms."""
# Django
from django import forms
#from django.contrib.auth.models import Artist
from music.models import Artist
class ArtistForm(forms.Form):
我多次遇到的结果是 405 和 404 错误,或者被重定向到艺术家姓名字段保留的同一页面,但我上传的图像消失了,并显示以下消息:
一只甜甜圈
海绵宝宝撒
相关分类