Django使用表单上传文件

时间:2013-11-12 18:04:09

标签: django

伙计们帮助解决一个小问题。在我的项目中,我上传了图片。当我从管理面板上传图像时,一切都很完美。现在我需要从表单上传图像。除了图像外,表格中的每个字段都能很好地上传。我的源代码:

forms.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()

views.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)

file.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>

models.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)

1 个答案:

答案 0 :(得分:2)

您需要在enctype="multipart/form-data"

上指定form
<form action="" method="post" class="form-horizontal" role="form" enctype="multipart/form-data">
相关问题