【问题标题】:django - Upload file to models on existing formdjango - 将文件上传到现有表单上的模型
【发布时间】:2021-09-19 14:43:10
【问题描述】:

我正在尝试在现有表单中上传文件,想法是发送带有交易收据的购买请求。

我需要将 input type="file" 上传到 models

上的 receipt

我尝试使用表单,但无法让它工作(它给了我一个错误,来自 modelsamount),我认为这是因为有一个表格内的表格......我猜

有什么想法吗?

.html

<div>
    <form action="{%url 'buying' %}" method="post" name="f">   
        {% csrf_token %}
        <div class="form-group h1color">
            <label for="">USD Amount</label>
            <input type="number" 
            class="form-control" 
            name="amount"
            placeholder="$" 
            value={{values.amount}}
            onchange="cal()" 
            onkeyup="cal()" 
            >
        </div>
        <div class="form-group h1color">
            <label for="">Price in UF</label>
            <p><input class="form-control" type="text" name="amount_uf" value="UF 00" readonly="readonly" /></p> 

        </div>
        <div class="form-group h1color">
            <Label for="">Attach Receipt</Label>
            <input type="file" class="form-control-file border">
        </div>
            <button type="submit" class="btn whitecolor bgcolorgraay" style="width: 100%;">Send</button>
    </form>
</div> 

模型

class Transactions(models.Model):

    STATUS = [
        ('pending', 'pending'),
        ('aproved', 'aproved'),

    ]
    

    amount = models.FloatField()
    date = models.DateField(default=now)
    owner = models.ForeignKey(to=User, on_delete=models.CASCADE)
    category = models.CharField(default='Payment', max_length=255)
    status = models.CharField(max_length=255,
                              choices=STATUS,
                              default='pending',
                              )
    receipt= models.FileField(upload_to='documents/%Y/%m/%d')
    amount_uf=models.FloatField(default=0)

    account = models.CharField(default="n/a" , max_length=255)

    def __str__(self):
        return str(self.owner) + " | " + self.category + " | " + str(self.date)

【问题讨论】:

  • 请分享完整的回溯

标签: django file upload


【解决方案1】:

在表单中添加 enctype 属性:

<form action="{%url 'buying' %}" method="post" name="f" enctype='multipart/form-data'>

在您看来,请执行以下操作:

def simple_upload(request):
    if request.method == 'POST' and request.FILES['myfile']:
        myfile = request.FILES['myfile']
        fs = FileSystemStorage()
        filename = fs.save(myfile.name, myfile)
        uploaded_file_url = fs.url(filename)
        return render(request, 'core/simple_upload.html', {
            'uploaded_file_url': uploaded_file_url
        })
    return render(request, 'core/simple_upload.html')

【讨论】:

    猜你喜欢
    • 2012-06-24
    • 2021-12-31
    • 1970-01-01
    • 2012-11-22
    • 2016-11-09
    • 2018-03-05
    • 2021-07-30
    • 1970-01-01
    • 2013-06-01
    相关资源
    最近更新 更多