文件未在 Django 中上传

File not uploading in Django

我正在尝试将 Django 中的文件上传到模型:

class Dealer(models.Model):
    user = models.OneToOneField(User,on_delete=models.PROTECT)
    profile = models.OneToOneField(UserProfile,on_delete=models.PROTECT)
    kyc_verified = models.BooleanField('kyc status',default=False)
    aadhar = models.FileField(upload_to='aadhar_images')
    pan = models.FileField(upload_to='pan_images')
    gts = models.FileField(upload_to='gts')
    registration = models.FileField(upload_to='registration')
    manager = models.CharField(max_length=75)
    manage_mobile = models.IntegerField()

在媒体中,我创建了文件夹 aadhar_imagespan_imagesgtsregistration。但是当我使用 html:

中的表单上传文件时
<form method="post" action="{% url 'dealer:update' %}" enctype="multipart/form-data">
{% csrf_token %}
<br><br>
AAdhar upload :
<input type="file" name="aadhar" id="aadhar" accept="*"><br><br>
Pan upload :
<input type="file" name="pan" id="pan" accept="*"><br><br>
Gts upload :
<input type="file" name="gts" id="gts" accept="*"><br><br>
Registration upload :
<input type="file" name="registration" id="regis" accept="*"><br><br>
</form>

并在 views.py 中:

def update(request):
    if request.method=='POST':
        user = User.objects.filter(username=request.user).values()[0]['id']
        try:
            aadhar = request.FILES['aadhar']
            print(aadhar)
            Dealer.objects.filter(user=user).update(aadhar=aadhar,kyc_verified=False)
        except:
            pass
        try:
            pan = request.FILES['pan']
            Dealer.objects.filter(user=user).update(pan=pan,kyc_verified=False)
        except:
            pass
        try:
            gts = request.FILES['gts']
            Dealer.objects.filter(user=user).update(pan=gts,kyc_verified=False)
        except:
            pass
        try:
            reg = request.FILES['registration']
            Dealer.objects.filter(user=user).update(registration=reg,kyc_verified=False)
        except:
            pass

提交表格后,文件没有上传到各自的目录。此外,数据库中的 url 显示为 media/filename,但即使在媒体目录中也没有上传文件。

.update() 方法不会将任何文件保存到存储中。您需要使用模型 save 方法。也不要以简单的 if 就足够的方式使用 try-except,或者您可以简单地使用 .get()。由于您的模型经销商与用户具有一对一的关系,您可以简单地将经销商设为 user.dealer。试试这个:

if request.method == 'POST':
    user = request.user # Why so much work to get what you already have even if you want id request.user.id would be enough...
    dealer = user.dealer
    if dealer:
        aadhar = request.FILES.get('aadhar')
        pan = request.FILES.get('pan')
        gts = request.FILES.get('gts')
        reg = request.FILES.get('registration')
        dealer.aadhar = aadhar
        dealer.pan = pan
        dealer.gts = gts
        dealer.reg = reg
        dealer.kyc_verified = False
        dealer.save()

请注意,使用 ModelForm.

会更好也更容易