0

我对 python 和 Django 比较陌生。

表单正在显示自己,但是当我选择一个文件并点击保存时,表单会自行刷新,并且 FormField 中的选定文件会消失,并且表单说该文件是必需的。

代码是:

模型.py

class ScribbleMedia(models.Model):
     media = models.FileField(upload_to='photos')
     def __unicode__(self):
      return self.media
     
class Scribble(models.Model):
     body = models.TextField()
     user = models.ForeignKey(User)
     media = models.ForeignKey(ScribbleMedia)
     def __unicode__(self):
      return u'%s, %s' % (self.user.username, self.media)

class Tag(models.Model):
  name = models.CharField(max_length=64, unique= True)
  scribbles = models.ManyToManyField(Scribble)
  def __unicode__(self):
    return self.name
    

视图.py

def scribbler_save_page(request):
    if request.method == 'POST':
        form = ScribbleSaveForm(request.POST)
        if form.is_valid():
            #Create or get media.
            media, dummy = ScribbleMedia.objects.get_or_create(
                media=form.cleaned_data['media']
            )
            #Create or get media.
            scribble, created=Scribble.objects.get_or_create(
                user=request.user,
                media=media
            )
            #update scribble body
            scribble.body=form.cleaned_data['body']
            # If the scibble is being updated, clear old tag list.
            if not created:
                scribble.tag_set.clear()
            # Create new tag list.
            tag_names = form.cleaned_data['tags'].split()
            for tag_name in tag_names:
                tag, dummy = Tag.objects.get_or_create(name=tag_name)
                scribble.tag_set.add(tag)
            # Save scribble to database.
            scribble.save()
            return HttpResponseRedirect ( '/user/%s/' % request.user.username
            )
    else:
        form = ScribbleSaveForm()
    variables = RequestContext (request, { 
        'form': form
    })
    return render_to_response ('scribble_save.html', variables)
    

表格.py

class ScribbleSaveForm(forms.Form):
    media=forms.FileField(
      label=u'add file',
      widget=forms.FileInput()
    )
    text=forms.CharField(
      label=u'description',
      widget=forms.Textarea()
    )
    tags=forms.CharField(
      label=u'Tags',
      required=False,
      widget=forms.TextInput(attrs={'size':64})
    )

网址.py

(r'^save/$', scribbler_save_page),

scribble_save.html

{% extends "base.html" %}
    {% block title %}Save Scribble {% endblock %}
    {% block head %}Save Scribble { % endblock % }
    {% block content %}
    <form method="post" action=".">
        {{ form.as_p }}
        <input type="submit" value="save" />
        {% csrf_token %}
    </form>
    {% endblock %}
4

1 回答 1

3

您需要专门为文件上传做两件事:

(1) 您的 HTML 表单元素必须包含enctype值为的属性multipart/form-data

<form enctype="multipart/form-data" method="post" action=".">

(2) 在您看来,您会在中找到上传的文件,request.FILES而不是request.POST. 要将上传的文件绑定到表单,请request.FILES作为第二个参数传入表单构造函数。

form = ScribbleSaveForm(request.POST, request.FILES)

来源:Django docs - The Forms API - 将上传的文件绑定到表单

于 2012-08-19T00:19:44.357 回答