我需要填寫字段名稱和圖像以上傳到 Django DB,但我無(wú)法使用 HTML 的表單標(biāo)簽來(lái)更新它views.py"""Artist views."""# Djangofrom django.shortcuts import render, redirectfrom django.views import Viewfrom django.http import HttpResponse# Modelsfrom music.models import Artist# Formsfrom artist.forms import ArtistFormclass 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 modelsclass 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."""# Djangofrom django import forms#from django.contrib.auth.models import Artistfrom music.models import Artistclass ArtistForm(forms.Form):我多次遇到的結(jié)果是 405 和 404 錯(cuò)誤,或者被重定向到藝術(shù)家姓名字段保留的同一頁(yè)面,但我上傳的圖像消失了,并顯示以下消息:
無(wú)法在 Django 中使用 HTML 表單更新數(shù)據(jù)庫(kù)
呼啦一陣風(fēng)
2023-10-10 16:53:06