我需要填写字段名称和图像以上传到 Django DB,但我无法使用 HTML 的表单标签来更新它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):我多次遇到的结果是 405 和 404 错误,或者被重定向到艺术家姓名字段保留的同一页面,但我上传的图像消失了,并显示以下消息:
- 2 回答
- 0 关注
- 93 浏览
添加回答
举报
0/150
提交
取消