伙计们帮助解决一个小问题。在我的项目中,我上传了图片。当我从管理面板上传图像时,一切正常。现在我需要从表单上传图片。表单优上传表格中的每个字段,除了图片。我的源代码:
表格.py:
from django import forms
class EditorForm(forms.Form):
title = forms.CharField(label='Title', widget=forms.TextInput(attrs={
'class': 'form-control', 'type': 'text', 'name': 'title',
'id': 'title', 'placeholder': 'title here'}))
description = forms.CharField(label='Description', widget=forms.Textarea(
attrs={'class': 'form-control', 'name': 'description',
'id': 'description', 'placeholder': 'Long description here'}))
short_description = forms.CharField(
label='Short description', max_length=160, widget=forms.TextInput(
attrs={'class': 'form-control', 'name': 'short', 'id': 'short',
'placeholder': 'Short description'}))
coordinates = forms.CharField(
label='Coordinates', required=False, widget=forms.TextInput(attrs={
'class': 'form-control', 'type': 'text', 'name': 'latlng',
'id': 'latlng', 'readonly': 'readonly'}))
# img = forms.ImageField()
视图.py:
class PointEditorView(FormView):
template_name = 'geo_location/editor.html'
form_class = EditorForm
success_url = '/point/'
def form_valid(self, form):
# I DO IT BUT I NEED SOME TESTS!
# This method is called when valid form data has been POSTed.
# It should return an HttpResponse.
if form.is_valid():
Point.objects.create(
title=form.cleaned_data['title'],
description=form.cleaned_data['description'],
coordinate=form.cleaned_data['coordinates'],
short_description=form.cleaned_data['short_description'],
# img=form.cleaned_data['img']
)
return super(PointEditorView, self).form_valid(form)
文件.html
<form action="" method="post" class="form-horizontal" role="form">{% csrf_token %}
<legend>Добавляем точку</legend>
<fieldset>
<div class="form-group">
{{ form.as_p }}
<br/>
<div class="row">
<div class="col-md-12">
<button type="submit" class="btn btn-success">Сохранить</button>
</div>
</div>
模型.py:
class Point(models.Model):
title = models.CharField(max_length=32)
short_description = models.CharField(max_length=120)
description = models.TextField()
coordinate = models.PointField(srid=4326)
objects = models.GeoManager()
img = ThumbnailImageField(upload_to='photos', blank=True)