在django中上传文件时出错

时间:2016-07-02 09:37:19

标签: django django-models django-forms

我正在尝试在django模型中附加文件,但是当我点击提交按钮时,所选文件会立即消失,表单提交失败。这里出了什么问题?

forms.py

from django import forms
from .models import IssueNotice

class IssueNoticeForm(forms.ModelForm):
    class Meta:
        model = IssueNotice
        fields = ('title', 'content','issuer','attachment',)

models.py

from django.db import models
from django.utils import timezone
from django import forms


class IssueNotice(models.Model):
    title = models.CharField(max_length=300)
    content = models.TextField()
    attachment = models.FileField(upload_to='attachments')
    issuer = models.CharField(max_length=100)
    issuer_id = models.ForeignKey('auth.User')
    issued_date = models.DateTimeField(default = timezone.now)


    def publish(self):    
        self.issued_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title

views.py

from django.shortcuts import render
from django.utils import timezone
from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required
from .models import IssueNotice
from .forms import IssueNoticeForm

def issue_notice(request):
    if request.method == "POST":
        form = IssueNoticeForm(request.POST, request.FILES)
        if form.is_valid():
             handle_uploaded_file(request.FILES['attachment'])
             notice = form.save(commit = False)
             notice.issuer_id = request.user
             notice.issued_date = timezone.now()
             notice.save()
             return redirect('home_page')
    else:
        form = IssueNoticeForm()
    return render(request, 'webadmin/issue_notice.html',{'form':form})

issue_notice.html

{% extends 'webadmin/base.html' %}

{% block content %}


<div class="col-md-8">

<form method="POST" class="post-form">{% csrf_token %}
    {{ form.as_p }}
    <button type="submit" class="save btn btn-default">Issue</button>
</form>   

{% endblock %}

0 个答案:

没有答案