我正在尝试通过此示例将多张图片上传到现有视图。
PopUp可以选择图片,但是不能上传图片
一些来自我的代码 models.py
class Item(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, related_name="itemauthor", on_delete=models.SET_NULL)
timestamp = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=255, null=False, unique=True)
slug = models.SlugField(max_length=80, null=True, blank=True)
status = models.CharField(max_length=1, choices=STATUS, default=DRAFT)
content = MarkdownxField()
edited = models.BooleanField(default=False)
objects = ItemQuerySet.as_manager()
class Meta:
verbose_name = _("Item")
verbose_name_plural = _("Items")
ordering = ("-timestamp",)
def __str__(self):
return self.title
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(f"{self.title}-{self.user.username}", to_lower=True, max_length=80)
super().save(*args, **kwargs)
def get_markdown(self):
return markdownify(self.content)
def notify_comment(**kwargs):
actor = kwargs['request'].user
receiver = kwargs['comment'].content_object.user
obj = kwargs['comment'].content_object
notification_handler(
actor, receiver, Notification.COMMENTED, action_object=obj
)
class Photo(models.Model):
item = models.ForeignKey(Item, on_delete=models.CASCADE, related_name="articleimage", default='')
title = models.CharField(max_length=255, blank=True)
file = models.FileField(upload_to='photos/')
uploaded_at = models.DateTimeField(auto_now_add=True)
views.py
class CreateItemView(LoginRequiredMixin, CreateView):
model = Item
message = _("created.")
form_class = CreateItemForm
template_name = 'item_create.html'
def post(self, request):
form = PhotoForm(self.request.POST, self.request.FILES)
if form.is_valid():
photo = form.save()
data = {'is_valid': True, 'name': photo.file.name, 'url': photo.file.url}
else:
data = {'is_valid': False}
return JsonResponse(data)
def form_valid(self, form):
form.instance.user = self.request.user
return super(CreateItemView, self).form_valid(form)
def get_success_url(self):
messages.success(self.request, self.message)
return reverse('item:list')
和.html
{% extends 'base.html' %}
{% load static i18n %}
{% load crispy_forms_tags %}
{% block head %}
{% endblock head %}
{% block content %}
{% block javascript %}
{# JQUERY FILE UPLOAD SCRIPTS #}
<script src="{% static 'js/jquery-file-upload/vendor/jquery.ui.widget.js' %}"></script>
<script src="{% static 'js/jquery-file-upload/jquery.iframe-transport.js' %}"></script>
<script src="{% static 'js/jquery-file-upload/jquery.fileupload.js' %}"></script>
{# PHOTOS PAGE SCRIPTS #}
<script src="{% static 'js/basic-upload.js' %}"></script>
{% endblock %}
{% block photos_content %}
<div style="margin-bottom: 20px;">
<button type="button" class="btn btn-primary js-upload-photos">
<span class="glyphicon glyphicon-cloud-upload"></span> Upload photos
</button>
<input id="fileupload" type="file" name="file" multiple
style="display: none;"
data-url="{% url 'item:write_new' %}"
data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token }}"}'>
</div>
{% for photo in photos %}
{{ photo.file.name }}
{% endfor %}
{% endblock %}
<form action="{% url 'item:write_new' %}" enctype="multipart/form-data" id="article-form" method="post" role="form">
{{ form|crispy }}
{% for form in formset %}
{{ form.media}}
{% endfor %}
<div class="form-group">
<button type="button" class="btn btn-primary publish">{% 'Publish' %}</button>
<a href="{% url 'item:list' %}" class="btn btn-default">{% 'Cancel' %}</a>
<br>
</div>
</form>
{% endblock content %}
{% block modal %}
<script src="{% static 'js/item.js' %}"></script>
{% endblock modal %}
但是,如何为现有的Item模型添加一个上传按钮?
P.S .: save.form由item.js触发,设置状态
照片已上传到照片文件夹,但未保存在数据库中。