【问题标题】:django - How to upload file to the folder in filefielddjango - 如何将文件上传到文件字段中的文件夹
【发布时间】:2020-02-05 14:03:00
【问题描述】:

我正在保存一个带有文件字段的表单,并从用户配置文件中将upload_to 说给user_path。我不知道如何为表单编写视图

models.py


def nice_user_folder_upload(instance, filename):
    extension = filename.split(".")[-1]
    return (
        f"{instance.UserProfile.Assigned_Group}/{filename}"
    )

class Metadataform(models.Model):


    id = models.AutoField(primary_key=True)
    Authors_Name = models.CharField(max_length=500, blank=True, null=True)
    Document = models.FileField(upload_to=nice_user_folder_upload)

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)

    Assigned_Group= models.CharField(max_length=500, choices=Group_choices, default='Please Select')

    def __str__(self):
        return self.user.username

views.py

def Metadata_submission(request):


        Authors_Name = request.POST["Authors_Name"]
          if request.method == 'POST':
                form = Fileuploadform(request.POST, request.FILES)
                if form.is_valid():
                        form.save()
                   return render(request, "home.html")

        else:
                form = Fileuploadform()
# forms.py                              

class Fileuploadform(forms.ModelForm):
    class Meta:
        model = Metadataform
        fields = ['Authors_Name','Affliations','Dataset_Creation_Date','Publication_Ref','Embargo_Time','DataGeneration_Type','Methods','Instruments','Software','Models','Device','Configuration','Precursor','Data_Type','Variables','Error_Estimation','Document']


class UserProfileForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ('Assigned_Group',)

我在 /Metadata_submission/ 处收到 AttributeError 'Metadataform' 对象没有属性 'UserProfile'

【问题讨论】:

  • 我能得到一些指导吗?
  • 您可以发布您在视图中使用的 HTML 表单吗?
  • 已将 html 文件添加到我的问题中
  • 表单的结束标签在哪里?表格上还有其他字段吗?
  • 是的,我的表单中还有几个字段,但为什么要查看结束标记?如果可以请解释一下,我可以相应地更新更改

标签: django filefield


【解决方案1】:

我认为这里的问题是您这里有很多字段可能与您的Metadataform 模型无关(也许您还没有完整地发布它)。我认为您应该考虑阅读doc。从外观上看,您正试图在表单的某处添加 UserProfile,这会导致错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-23
    • 2014-03-08
    • 2012-03-14
    • 2012-05-10
    • 1970-01-01
    • 2020-10-16
    • 2011-10-08
    • 1970-01-01
    相关资源
    最近更新 更多