我是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
models.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)
答案 0 :(得分: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)