无法在 Django 中使用 HTML 表单更新数据库

我需要填写字段名称和图像以上传到 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 错误,或者被重定向到艺术家姓名字段保留的同一页面,但我上传的图像消失了,并显示以下消息:

https://img1.mukewang.com/652511380001a67103260257.jpg

呼啦一阵风
浏览 94回答 2
2回答

一只甜甜圈

我是这样解决的,你的方法有问题create_user你需要这样做Artist.objects.create( &nbsp;&nbsp;&nbsp;&nbsp;name=form.cleaned_data["name"], &nbsp;&nbsp;&nbsp;&nbsp;image=form.cleaned_data["image"], )并添加ArtistForm(request.POST,&nbsp;request.FILES)我希望我有所帮助

海绵宝宝撒

您还需要提供request.FILES表格。form = ArtistForm(request.POST, request.FILES)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5