因此,我一直在尝试实现一种在我的网站上发布项目帖子的方法。但是,我对表单的验证似乎有问题。即使该表格正确无误,也仍然无法通过验证。
我的项目页面上没有帖子,数据库中也没有添加任何内容。我不确定发生了什么。
我在终端上没有看到任何错误。
我的代码如下:
views.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)
forms.html
{% extends "projects/test.html" %}
{% block javascript %}
<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 }} <br />
{% endfor %}
<input type="submit" value="OK">
{% load static %}
{# JQUERY FILE UPLOAD SCRIPTS #}
<script src="{% static 'projects/js/jquery-file-upload/vendor/jquery.ui.widget.js' %}"></script>
<script src="{% static 'projects/js/jquery-file-upload/jquery.iframe-transport.js' %}"></script>
<script src="{% static 'projects/js/jquery-file-upload/jquery.fileupload.js' %}"></script>
{# PHOTOS PAGE SCRIPTS #}
<script src="{% static 'projects/js/basic-upload.js' %}"></script>
{# 1. BUTTON TO TRIGGER THE ACTION #}
<button type="button" class="btn btn-primary js-upload-photos">
<span class="glyphicon glyphicon-cloud-upload"></span> Upload photos
</button>
{# 2. FILE INPUT TO BE USED BY THE PLUG-IN #}
<input id="fileupload" type="file" name="p_file" multiple
style="display: none;"
data-url="{% url 'create_post:create_projects' %}"
data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token }}"}'>
{# 3. TABLE TO DISPLAY THE UPLOADED PHOTOS #}
<table id="gallery" class="table table-bordered">
<thead>
<tr>
<th>Photo</th>
</tr>
</thead>
<tbody>
{% for p_photo in p_photos %}
<tr>
<td><a href="{{ p_photo.file.url }}">{{ p_photo.file.name }}</a></td>
</tr>
{% endfor %}
</tbody>
</table>
<h1>hahahaha</h1>
</form>
{% endblock %}
这让我困扰了两个星期。它开始使我不愿在python中学习Django:(
答案 0 :(得分:2)
您的表单操作指向create_post:retrieve_projects
,将其更改为指向create_post:create_projects