【问题标题】:upload .txt file into textarea in django?将.txt文件上传到django中的textarea?
【发布时间】:2019-01-11 10:27:36
【问题描述】:

我是 Django 新手。我使用 django 表单小部件为网站制作了 textareas。

我想添加一个文件上传,以便能够上传一个将插入文本区域的 .txt 文件。我该怎么办?

我查看了https://docs.djangoproject.com/en/2.1/topics/http/file-uploads/的文档

如何将此代码合并到我已经编写的代码中?

forms.py

class HomeForm(forms.ModelForm):
    textInput = forms.CharField(required=True, widget=forms.Textarea(
        attrs={
            'class': 'form-control',
            'placeholder': 'Input text...',
            'id': 'input1'
        }
    ))

    class Meta:
        model = Post #import Post model from home models.py
        fields = {'textInput',} #comma required to ensure tuple capability

模型.py

class Post(models.Model):
    post = models.CharField(max_length=1000)
    user = models.ForeignKey(User, on_delete=models.PROTECT) #default .CASCADE
    date = models.DateTimeField(auto_now=True) #data saved into db

views.py

class HomeView(TemplateView):
    template_name='home/home.html'

    def get(self, request):
        form = HomeForm

        posts = Post.objects.all()
        args = {'form': form, 'posts': posts}

        return render(request, self.template_name, args)


    def post(self, request):
        form = HomeForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False) #saves data (thanks to the model form)
            #comit is false as object still needs to be modified
            post.user = request.user
            post.save()
            text = form.cleaned_data['textInput'] #anticipates SQL injection
            #return redirect('home:home')

        args = {'form': form, 'text': text}
        return render(request, self.template_name, args)

【问题讨论】:

    标签: python django python-3.x django-forms django-views


    【解决方案1】:

    首先你应该附加forms.FileField来使用Django框架上传机制。

    在处理请求时,任何 Django 表单都有其lifecycle。当用户上传 .txt 文件时,您可以像这样在save 方法中捕获它:

    class HomeForm(forms.ModelForm):
        ...
        text_file = forms.FileField()
        ...
    
        def save(self, commit=True):
            ...
            # check if text_file contains content
            text_file_data = self.cleaned_data.get("text_file")
            ...
            if text_file_content:
                # self.instance is instance of "Post" model
                self.instance.post = text_file_content
            ...
            return super().save(commit)  
    

    【讨论】:

    • 感谢帕维尔。 text_file_content 来自哪里?
    • 我不确定,但self.cleaned_data.get("text_file") 可能会返回 InMemory 存储,您应该从中解析内容
    猜你喜欢
    • 2012-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-17
    • 2022-01-18
    • 1970-01-01
    相关资源
    最近更新 更多