繁体   English   中英

在我提交表单并上传照片后,Django 数据库中没有任何内容可保存

[英]After I submit form with uploading photos, there are nothing to save on Django database

我遇到了一个问题。

当我在注册页面上选择一张照片作为 profile_pic 时,

它可以保存任何没有照片的信息。

但我不知道为什么它不起作用。

在此处输入图像描述

提交后个人资料图片中没有任何内容。

在此处输入图像描述

设置.py

"""
Django settings for learning_templates project.
 
Generated by 'django-admin startproject' using Django 3.1.7.
 
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
 
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
 
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATE_DIR=os.path.join(BASE_DIR,'templates')
STATIC_DIR=os.path.join(BASE_DIR,'static')
MEDIA_DIR=os.path.join(BASE_DIR,'media')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
 
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'pgmh_#pcqd(3sf(a3oj#^vyv4l-#p6g=n-=^!z)0d@!k)!_ear'
 
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
 
ALLOWED_HOSTS = []
 
 
# Application definition
 
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'basic_app',
]
 
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 = 'learning_templates.urls'
 
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATE_DIR,],
        '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 = 'learning_templates.wsgi.application'
 
 
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
 
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}
 
 
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
PASSWORD_HASHERS=[
    'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
    'django.contrib.auth.hashers.Argon2PasswordHasher',
    'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
]
 
 
AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        'OPTIONS':{'min_length':9}
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]
 
 
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
 
LANGUAGE_CODE = 'en-us'
 
TIME_ZONE = 'UTC'
 
USE_I18N = True
 
USE_L10N = True
 
USE_TZ = True
 
 
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
 
STATIC_URL = '/static/'
STATICFILES_DIRS=[STATIC_DIR,]
 
#MEDIA
MEDIA_ROOT=MEDIA_DIR
MEDIA_URL='/media/'
 
LOGIN_URL='basic_app/user_login'

在views.py中:注册

def register(request):
    
    registered= False
    logging.error(request.method)
    if request.method == 'POST':
       user_form= UserForm(data=request.POST)
       profile_form=UserProfileInfoForm(request.POST)
       logging.error(user_form) 
       if user_form.is_valid() and profile_form.is_valid():
           user=user_form.save()
           
           user.set_password(user.password)
           user.save()
 
           profile=profile_form.save(commit=False)
           profile.user=user
 
           if 'profile_pics' in request.FILES:
               profile.profile_pic=request.FILES['profile_pics']
 
           profile.save()
           
           registered=True
       else:
            print(user_form.errors,profile_form.errors)
 
    else:
        user_form=UserForm()
        profile_form=UserProfileInfoForm()
    
    return render(request,'basic_app/registeration.html',
    {'user_form':user_form,
    'profile_form':profile_form,
    'registered':registered})

模型.py

from django.db import models
from django.contrib.auth.models import User
 
# Create your models here.
 
class UserProfileInfo(models.Model):
    user=models.OneToOneField(User,on_delete=models.CASCADE)
    # additional
    portfolio_site=models.URLField(blank=True)
    profile_pic = models.ImageField(upload_to = 'profile_pics', blank = True)
    def __str__(self):
        return self.user.username

forms.py

class UserProfileInfoForm(forms.ModelForm):
    class Meta():
        model=UserProfileInfo
        fields=('portfolio_site','profile_pic')

注册.html

<!DOCTYPE html>
{% extends "basic_app/base.html" %}
{% load static %}
  {% block body_block %}
  {{registered }}
    <div class=jumbotron>
      <h1>Test Register</h1>
      {% if registered %}
      <h1>Thank you for Register</h1> 
      {% else %}
      <h1>Register Here</h1>
      <h3>
          <h1>Fill out the form</h1>
          <form method="post" enctype="multipart/form-data">
              {% csrf_token %}
              {{ user_form.as_p}}
              {{ profile_form.as_p }}
              <input type="submit" name="" value="Register">
          </form>
      </h3>
      {% endif %}
    </div>
  {% endblock %}

在此处输入图像描述

而且我已确保 profile_pics 文件夹中没有任何内容。

我不知道我错在哪里或我错过了什么,但没有照片的任何东西都已保存。

如果有什么遗漏,请告诉我。

感谢您的时间。

首先检查上传的图片是否在您的 media/profile_pics 文件夹中。
由于您正在查看使用 django 管理面板上传的数据,因此它不会显示实际图像,它将显示图像名称。

尝试通过在上下文部分中传递用户内容来在模板中显示图像,同时发送渲染模板。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM