html 从django前端上传和检索文件到postgresql后端

neekobn8  于 2022-12-09  发布在  Go
关注(0)|答案(1)|浏览(119)

这是我在postgres的表:

我如何将其引入前端,以便用户可以上传他们的文档,而不必访问数据库。目前,我只能将文档上传到文件系统,而不是数据库:
views.py:

def upload(request):
if request.user.is_authenticated:
    username = request.user.username
if request.method == 'POST' and request.FILES['myfile']:
    myfile = request.FILES['myfile']
    fs = FileSystemStorage()
    filename = fs.save(myfile.name, myfile)
    uploaded_file_url = fs.url(filename)
    return render(request, 'app/upload.html', {
       "uploaded_file_url": uploaded_file_url,
       "username": username,
    })
return render(request, 'app/upload.html', {
    "username": username,
})

upload.html:

{% if form.errors %}
    <p>You did not select a file to upload!</p>
{% endif %}

<form method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    <input type="file" name="myfile">
    <button type="submit">Upload</button>
</form>

{% if uploaded_file_url %}
    <p>File uploaded at: <a href="{{ uploaded_file_url }}">{{ uploaded_file_url }}</a></p>
{% endif %}

models.py:

class Document(models.Model):
Document_name = models.CharField(max_length=255, default='Document_name')
Date = models.DateField()
Client_id = models.ForeignKey(ClientDetail, on_delete=models.CASCADE)

def __str__(self):
    return self.Document_name

结构描述:

还有我将如何检索上传的文档。

b1uwtaje

b1uwtaje1#

以下是一个示例:
settings.py

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

urls.py

from django.conf.urls.static import static
urlpatterns = [
    ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

models.py

from django.core.validators import FileExtensionValidator
class Document(models.Model):
    name = models.CharField(max_length=255, default='Document_name')
    date = models.DateField()
    client = models.ForeignKey(ClientDetail, on_delete=models.CASCADE)
    myfile = models.FileField(validators=[
        FileExtensionValidator(allowed_extensions=['pdf', 'doc', 'ppt', 'xlsx'])
    ])

    def __str__(self):
        return self.name

forms.py

from django import forms
from .models import Document
class DocumentForm(forms.ModelForm):
    class Meta:
        model = Document
        fields = '__all__'

upload.html:

<form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="ok">
</form>
{% if uploaded_file_url %}
    <p>File uploaded at: <a href="{{ uploaded_file_url }}">{{ uploaded_file_url }}</a></p>
{% endif %}

views.py

def upload(request):
    if request.user.is_authenticated: 
        # Is it better to use @login_required ?
        username = request.user.username
    else:
        username = ''
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            doc = form.save()
            return render(request, 'app/upload.html', {
               "form": DocumentForm(),
               "uploaded_file_url": doc.myfile.url,
               "username": username,
            })
    else:
        form = DocumentForm()
    return render(request, 'app/upload.html', {"form": form})

相关问题