我是django的新手并坚持上传一个简单的文件。我使用TemplateView作为视图和基于模型的表单。我被困在这里。我不知道该怎么做。我正在使用django 2.0。我已经附上了我到目前为止所做的工作。
setting.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'key_hash'
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'Aamir.apps.AamirConfig',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'first.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'first.wsgi.application'
DATABASES = {
'default': {
'NAME': 'dbname',
'ENGINE': 'django.db.backends.mysql',
'USER': 'arshad',
'PASSWORD': 'arshad',
'HOST': 'localhost',
'PORT': '3306',
'OPTIONS': {
'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
'charset': 'utf8mb4',
}
}
}
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
urls.py(项目)
from django.contrib import admin
from django.urls import path,include
import Aamir.views as views
urlpatterns = [
path('', include('Aamir.urls')),
path('admin/', admin.site.urls),
]
urls.py(app)
from django.contrib import admin
from django.urls import path
import Aamir.views as views
urlpatterns = [
path('', views.HomePageView.as_view(), name='home'),
path('index/', views.HomePageView.as_view(), name='home'),
path('summerizer/', views.SummerizerView.as_view(), name='summerizer'),
]
views.py
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.views.generic import TemplateView
from .forms import FileUploadForm
#from django.core.files.storage import FileSystemStorage
class HomePageView(TemplateView):
template_name = 'Aamir/index.html'
class SummerizerView(TemplateView):
template_name = 'Aamir/summrizer.html'
def post(self, request, *args, **kwargs):
context = self.get_context_data()
if context["form"].is_valid():
print('yes done')
context["form"].save(commit=True);
# save your model
# redirect
return super(TemplateView, self).render_to_response(context)
def get_context_data(self, **kwargs):
context = super(SummerizerView, self).get_context_data(**kwargs)
form = FileUploadForm(self.request.FILES)
context["form"] = form
return context
models.py
from django.db import models
class FileUpload(models.Model):
upload_file = models.FileField(upload_to='media/%Y/%m/%d/')
forms.py
from django import forms
from .models import FileUpload
class FileUploadForm(forms.ModelForm):
class Meta:
model = FileUpload
fields = ('upload_file',)
widgets = {
'upload_file': forms.FileInput(attrs={'class': 'form-control', 'accept': 'text/plan', 'id':'fupload',
'name':'fupload', 'placeholder': 'Brows Files'
}, ),
}
error_messages = {
'upload_file': {
'required': "No filed selected!",
},
}
def save(self, commit=True):
instance = super(FileUpload, self).save(commit=False)
if commit:
# save
instance.save(update_fields=['name'])
return instance
apps.py
from django.apps import AppConfig
class AamirConfig(AppConfig):
name = 'Aamir'
summrizer.html
{% extends "Aamir/include/base.html"%}
{% block page_title %}Summerizer{% endblock %}
{% block content %}
<style>
legend {
display: block;
-webkit-padding-start: 2px;
-webkit-padding-end: 2px;
border-width: initial;
width: initial;
font-size: initial;
margin-bottom: 15px;
border-style: none;
border-color: initial;
border-image: initial;
}
fieldset {
display: block;
-webkit-margin-start: 2px;
-webkit-margin-end: 2px;
-webkit-padding-before: 0.35em;
-webkit-padding-start: 0.75em;
-webkit-padding-end: 0.75em;
-webkit-padding-after: 0.625em;
min-width: -webkit-min-content;
border-width: 1px;
border-style: solid;
border-color: lightgrey;
border-image: initial;
}
</style>
{% load staticfiles%}
<div class="section-container" style="padding-top: 20px;">
<div class="container">
<div class="row">
<div class="col-xs-12 col-md-8 col-md-offset-2">
<h1 class="text-center">Summerizer</h1>
</div>
<br>
<br>
</div>
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<fieldset>
<legend style="color:lightgrey;font-weight:bold;">Upload File</legend>
<div class="hidden-sm hidden-xs">
{% if form.non_field_errors %}
<div class="alert alert-danger" role="alert">{{ form.non_field_errors }}</div>
{% endif %}
<form action="" method="post" enctype="multipart/form-data" class="form-horizontal">
{% csrf_token %}
<div class="form-group">
<!--label class="control-label col-sm-2" for="email">Upload File:</label-->
<div class="col-sm-10">
<!--input type="file" accept="text/plain" class="form-control" id="fupload" placeholder="Brows for file" name="fupload"-->
{{ form.upload_file }}
{% for field in form %}
<span style="color:#b92c28">{{ field.errors }}</span>
{% endfor %}
</div>
<div class="col-lg-2 col-md-2 col-sm-12 col-xs-12">
<button type="submit" class="btn btn-primary btn-block" id="btnupload" name="submit">
Upload
</button>
</div>
</div>
</form>
</div>
<div class="hidden-lg hidden-md">
<form action="" method="post" enctype="multipart/form-data">
<div class="form-group">
<label class="control-label col-sm-2" for="email">Upload File:</label>
{{ form }}
</div>
</form>
</div>
</fieldset>
</div>
</div>
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<br>
<fieldset>
<legend style="color:lightgrey;font-weight:bold;">Summery</legend>
<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12" style="padding-left: 0px">
<div class="panel panel-default" style="border: 1px solid lightgrey">
<div class="panel-heading" style="background: lightgrey;border:1px solid lightgrey">
<p class="text-center" style="font-weight: bold;margin:0.5em;">Summery</p>
</div>
<div class="panel-body" style="padding:10px">
<div class="text-area-result" style="max-height:400px;min-height: 400px;overflow-y: scroll;padding: 0;width: 100%">
<p id="result-text">
</p>
</div>
</div>
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12" style="padding-right: 0px">
<br class="hidden-lg hidden-md">
<div class="panel panel-default" style="border: 1px solid lightgrey">
<div class="panel-heading" style="background: lightgrey;border:1px solid lightgrey">
<p class="text-center" style="font-weight: bold;margin:0.5em;">File Content</p>
</div>
<div class="panel-body" style="padding:10px">
<div class="text-area-result" style="max-height:400px;min-height: 400px;overflow-y: scroll;margin: 0;padding: 0;width: 100%">
</div>
</div>
</div>
</div>
</fieldset>
</div>
</div>
</div>
</div>
<div class="section-container">
<div class="container text-center">
<div class="row section-container-spacer">
<div class="col-xs-12 col-md-12">
<h3>Do you like it ?</h3>
<p>
<a href="https://facebook.com/" class="social-round-icon fa-icon" title="">
<i class="fa fa-facebook" aria-hidden="true"></i>
</a>
<a href="https://twitter.com/" class="social-round-icon fa-icon" title="">
<i class="fa fa-twitter" aria-hidden="true"></i>
</a>
<a href="https://www.linkedin.com/" class="social-round-icon fa-icon" title="">
<i class="fa fa-linkedin" aria-hidden="true"></i>
</a>
</p>
</div>
</div>
</div>
</div>
{% endblock %}