gpt4 book ai didi

Django 表单 is_valid 总是假的

转载 作者:行者123 更新时间:2023-12-04 23:28:27 25 4
gpt4 key购买 nike

在我的 Django 应用程序中,即使我添加了与管理应用程序相同的数据,表单也永远不会返回 true。我的 model.py 看起来像:

from django.db import models
from django.db.models import ImageField, signals
from django.dispatch import dispatcher
from django.forms import ModelForm

# Create your models here.
class Image(models.Model):
emailAddress = models.EmailField(max_length=75)
image = ImageField(upload_to='photos')
caption = models.CharField(max_length=100)

class UploadForm(ModelForm):
class Meta:
model = Image

我的 views.py 看起来像:
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from competition.models import Image, UploadForm

# Create your views here.

def index(request):
images = Image.objects.all().order_by('emailAddress')
return render_to_response('images/index.html', {'images': images})

def uploadImage(request):
if request.method == 'POST': # If the form has been submitted...
form = UploadForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
emailAddress = form.cleaned_data['emailAddress']
image = form.cleaned_data['image']
caption = form.cleaned_data['caption']
i = Image(emailAddress=emailAddress, image = image, caption = caption)
i.save()
return HttpResponseRedirect('../image/')
else:
return render_to_response('images/upload.html', {'form': form})
else:
form = UploadForm() # An unbound form
return render_to_response('images/upload.html', {'form': form})

我的模板看起来像:
<html>
<body>
<form enctype="multipart/form-data" action="/image/uploadImage" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
</body>
</html>

如果我使用管理应用程序但需要通用表单,我可以使其正常工作,但这不起作用,因为它不断要求电子邮件地址或图像(错误出现在图像字段上方)。那么为什么我的表格可能无效?

最佳答案

您需要使用 request.FILES 和 request.POST 实例化您的表单。

顺便说一句,您可以保存模型表单,而不是在 View 中手动创建图像。

关于Django 表单 is_valid 总是假的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8702520/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com