简体   繁体   English

如何在 django 中上传文件?

[英]How I can upload file in django?

I'm trying to upload file in a specific folder and store its path in DB through forms(CBV), but it doesn't work,, this is my code (forms, models. views, template).我正在尝试将文件上传到特定文件夹并通过表单(CBV)将其路径存储在数据库中,但它不起作用,这是我的代码(表单、模型、视图、模板)。 I'm selecting the file through forms then I submit the form, but it doesn't submit.我通过 forms 选择文件然后我提交表单,但它没有提交。

#views.py
class PostCreateView(LoginRequiredMixin, CreateView):
    model = Post
    # fields = ['title', 'content']
    success_url = reverse_lazy('blog/new_post.html')
    template_name = 'blog/new_post.html'
    form_class = PostCreateForm

    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect(self.success_url)
        else:
            return render(request, self.template_name, {'form': form})

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

#model.py
class Post(models.Model):
    title = models.CharField(max_length=1000)
    content = models.TextField()
    xml_file = models.FileField(null=True, upload_to='xml_files')
    rate = models.FloatField(null=True, blank=True, default=None)
    post_date = models.DateTimeField(default=timezone.now)
    post_update = models.DateTimeField(auto_now=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        # return '/detail/{}'.format(self.pk)
        return reverse('detail', args=[self.pk])
    class Meta:
        ordering = ('-post_date', )

#forms.py
class PostCreateForm(forms.ModelForm):
      title = forms.CharField( max_length=1000)
    content = forms.CharField(widget=forms.Textarea(
        attrs={'rows': 15, 'placeholder':  'write here'}
    ), max_length=50000)
    xml_file = forms.FileField(label='upload file')
    class Meta:
        model = Post
        fields = ['title', 'content', 'xml_file', ]
#new_post.html
{% block content %}
{% load crispy_forms_tags %}
<div class="border p-4 mb-5">
    <legend class="border-bottom pb-1 mb-3">new post</legend>
    <form method="POST">
        {% csrf_token %}
        {{form|crispy}}
        <input class="btn btn-secondary mt-4" type="submit" value="post">
    </form>
</div>
{% endblock content %}

When you are uploading media like what you've got, it is necessary to add the following part to your <form> :当您上传您所拥有的媒体时,有必要将以下部分添加到您的<form>

enctype=multipart/form-data

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM