完成上传图片的代码

master
RogerWork 1 year ago
parent adce8d27f7
commit b9942e15b6
  1. 11
      django_demo/settings.py
  2. 8
      django_demo/urls.py
  3. 16
      form_demo/forms.py
  4. 25
      form_demo/migrations/0003_imgfile.py
  5. 14
      form_demo/models.py
  6. 20
      form_demo/views.py
  7. 22
      templates/form_demo/uploadimg.html

@ -15,7 +15,6 @@ from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/
@ -27,7 +26,6 @@ DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
@ -64,6 +62,7 @@ TEMPLATES = [
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'django.template.context_processors.media' # 页面显示图片时需要加这个配置
],
},
},
@ -71,7 +70,6 @@ TEMPLATES = [
WSGI_APPLICATION = 'django_demo.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases
@ -88,7 +86,6 @@ DATABASES = {
DJANGO_SETTINGS_MODULE = []
# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators
@ -107,7 +104,6 @@ AUTH_PASSWORD_VALIDATORS = [
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/
@ -119,7 +115,6 @@ USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/
@ -129,3 +124,7 @@ STATIC_URL = 'static/'
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# Media
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "media")

@ -14,10 +14,14 @@ Including another URLconf
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.urls import path, re_path
from django.views.static import serve
from form_demo import views
from . import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('userinfo/', views.userinfo_form)
path('userinfo/', views.userinfo_form),
path('uploadimg/', views.img_file_form),
re_path(r'media/(?P<path>.*)', serve, {'document_root': settings.MEDIA_ROOT}),
]

@ -10,7 +10,7 @@ def age_validate(age):
def mobile_validate(mobile):
mobile_re = re.compile(r'^1[3-9]]\d{9}$')
mobile_re = re.compile(r'^1[3-9][0-9]{9}$')
if not mobile_re.match(mobile):
raise ValidationError('手机号格式错误')
@ -29,8 +29,14 @@ class UserInfoForm(forms.Form):
error_messages={'required': '年龄不能为空'})
mobile = forms.CharField(label='手机号码', validators=[mobile_validate],
error_messages={'required': '手机号不能为空'})
# status = forms.ChoiceField(label='状态', choices=STATUS, widget=forms.widgets.Select,
# error_messages={'required': '状态不能为空'})
status = forms.ModelChoiceField(label='状态', queryset=UserStatus.objects.all(), empty_label='请选择',
error_messages={'required': '状态不能为空'})
status = forms.ChoiceField(label='状态', choices=STATUS, widget=forms.widgets.Select,
error_messages={'required': '状态不能为空'})
# status = forms.ModelChoiceField(label='状态', queryset=UserStatus.objects.all(), empty_label='请选择',
# error_messages={'required': '状态不能为空'})
createdate = forms.DateField(label='创建日期', required=False, input_formats=["%Y-%m-%d"])
class ImgFileForm(forms.Form):
name = forms.CharField()
heading = forms.FileField()

@ -0,0 +1,25 @@
# Generated by Django 4.2.3 on 2023-07-27 01:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('form_demo', '0002_alter_userstatus_id'),
]
operations = [
migrations.CreateModel(
name='ImgFile',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(default='', max_length=30, verbose_name='名称')),
('heading', models.FileField(upload_to='uploads/', verbose_name='文件')),
],
options={
'verbose_name': '用户头像信息',
'db_table': 'user_img',
},
),
]

@ -15,3 +15,17 @@ class UserBaseInfo(models.Model):
class UserStatus(models.Model):
# id = models.AutoField(verbose_name='状态id', primary_key=True)
status = models.CharField(verbose_name='状态', max_length=10)
class ImgFile(models.Model):
name = models.CharField(verbose_name='名称', default='', max_length=30)
heading = models.FileField(verbose_name='文件', upload_to='uploads/')
def __str__(self):
return str(self.name)
class Meta:
verbose_name = '用户头像信息'
db_table = 'user_img'

@ -17,3 +17,23 @@ def userinfo_form(request):
print(errors)
return render(request, "form_demo/userinfo.html", {'form_obj': f, 'errors': errors})
return render(request, "form_demo/userinfo.html", {'form_obj': f})
def img_file_form(request):
if request.method == 'GET':
f = ImgFileForm()
return render(request, "form_demo/uploadimg.html", {'form_obj': f})
else:
f = ImgFileForm(request.POST, request.FILES)
print(request.POST)
print(request.FILES)
if f.is_valid():
name = f.cleaned_data['name']
heading = f.cleaned_data['heading']
userimg = ImgFile()
userimg.name = name
userimg.heading = heading
userimg.save()
print('上传成功')
print(userimg.heading)
return render(request, 'form_demo/uploadimg.html', {'form_obj': f, 'user_img': userimg})

@ -0,0 +1,22 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload Image</title>
</head>
<body>
<form enctype="multipart/form-data" action="" method="POST">
{% csrf_token %}
{{ form_obj.as_p }}
<br>
<input type="submit" value="上传图片">
{{ user_img }}
{% if user_img is not None %}
<div>
<img src="/media/{{ user_img.heading }}" alt="">
</div>
{% endif %}
</form>
</body>
</html>
Loading…
Cancel
Save