gpt4 book ai didi

python - django project_form 无效?

转载 作者:太空宇宙 更新时间:2023-11-04 04:35:30 24 4
gpt4 key购买 nike

我一直在尝试实现一种发布项目帖子的方法,用户可以在其中上传多张图片。多张图片上传有效,但发布帖子本身无效。

我不确定如何处理 project_form。

即使字段具有正确的值也是无效的。

我的代码是:

View .py

class CreateProjectsView(View):
def get(self, request):
p_photos = P_Images.objects.all()
#project_form = ProjectsForm(initial=self.initial)
project_form = ProjectsForm
context = {
'p_photos': p_photos,
'project_form': project_form,
}
return render(self.request, 'projects/forms.html', context)

def post(self, request):
project_form = ProjectsForm(request.POST or None, request.FILES or None)
p_formset = P_ImageForm(request.POST, request.FILES)

# Checks if the project_form is valid before save
if project_form.is_valid():
instance = project_form.save(commit=False)
instance.user = request.user
instance.save()

# Checks if multiple image upload is valid before save
if p_formset.is_valid():
#if project_form.is_valid() and p_formset.is_valid():
#instance = project_form.save(commit=False)
#instance.user = request.user
#instance.save()
images = p_formset.save(commit=False)
images.save()

data = {
'is_valid': True,
'name': images.p_file.name,
'url': images.p_file.url
}

else:
data = {
'is_valid': False,
}

return JsonResponse(data)

表单.html

<form action="{% url 'create_post:retrieve_projects' %}" method="POST" enctype="multipart/form-data">

{% csrf_token %}

{% for hidden in project_form.hidden_fields %}
{{ hidden }}
{% endfor %}

{% for field in project_form %}
{{ field.errors }}
{{ field }} <br />
{% endfor %}

<input type="submit" value="OK">
</form>

最佳答案

如果表单无效,您应该为用户提供更正错误并重新提交表单的方法。也许是这样的:

    if project_form.is_valid():
instance = project_form.save(commit=False)
instance.user = request.user
instance.save()

else:
return render(request, 'project_form.html', {'form': project_form})

关于python - django project_form 无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51831995/

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