【问题标题】:Django 3.0 Not Found: /favicon.ico and failing to store uploaded image into disk找不到 Django 3.0:/favicon.ico 并且无法将上传的图像存储到磁盘中
【发布时间】:2020-07-29 08:03:31
【问题描述】:

我是 Django 开发和开发应用程序的新手,用户可以在其中上传他们的详细信息和个人资料图片。上传的图片存盘失败,显示错误。请帮帮我。 [已编辑]

Not Found: /favicon.ico
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 53590)
Traceback (most recent call last):
  File "c:\users\venkatesh\appdata\local\programs\python\python38-32\lib\socketserver.py", line 650, in process_request_thread
    self.finish_request(request, client_address)
  File "c:\users\venkatesh\appdata\local\programs\python\python38-32\lib\socketserver.py", line 360, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "c:\users\venkatesh\appdata\local\programs\python\python38-32\lib\socketserver.py", line 720, in __init__
    self.handle()
  File "C:\Users\venkatesh\Envs\django\lib\site-packages\django\core\servers\basehttp.py", line 174, in handle
    self.handle_one_request()
  File "C:\Users\venkatesh\Envs\django\lib\site-packages\django\core\servers\basehttp.py", line 182, in handle_one_request
    self.raw_requestline = self.rfile.readline(65537)
  File "c:\users\venkatesh\appdata\local\programs\python\python38-32\lib\socket.py", line 669, in readinto
    return self._sock.recv_into(b)
ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine



这是我的 urls.py 文件

from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from django.views.generic.base import RedirectView
from django.contrib.staticfiles.storage import staticfiles_storage

from . import views

urlpatterns = [
    path('',views.home,name='home'),
    path('signup/',views.register,name='signup'),
    path('signup/register',views.register,name='signup'),
    path('signin/',views.signin,name='signin'),
    path('signin/signin',views.signin,name='signin'),
    path('logout/',views.logout,name='logout'),

]

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root = settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)

这是我的 settings.py

"""
Django settings for AI project.

Generated by 'django-admin startproject' using Django 3.0.7.

For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '4+12aq#j(k%zq%(b%)o2&ln=2ex7-dykjo-(=hk1m3dxj2#&dtz_'

# 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',
    'Bharatha',
]

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 = 'AI.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 = 'AI.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'postgres',
        'USER':'postgres',
        'PASSWORD':'2208',
        'HOST':'localhost'

    }
}


# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators

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',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.0/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.0/howto/static-files/

STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'), ) 
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

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

这是我的意见.py

from django.shortcuts import render,redirect
from django.contrib.auth.models import User,auth
from django.contrib import messages
from .forms import Profile_Form
from .models import ResgisterFrom


# Create your views here.
def home(request):
    return render(request,'base.html')


def signin(request):
    if request.method=='POST':
        username = request.POST['username']
        password= request.POST['password']

        user =auth.authenticate(username=username,password=password)
        if user is not None:
            auth.login(request,user)
            return redirect("/")
        else:
            messages.info(request,'Invalid Credentials!')
            return redirect('signin')
    else:

        return render(request,'signin.html')

def logout(request):
    auth.logout(request)
    return redirect('/')

def register(request):
    # if this is a POST request we need to process the form data
    template = 'register.html'
   
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        #form = Profile_Form(request.POST)
        form = Profile_Form(request.POST, request.FILES)
        # check whether it's valid:
        if form.is_valid():
            if User.objects.filter(username=form.cleaned_data['username']).exists():
                return render(request, template, {
                    'form': form,
                    'error_message': 'Username already exists.'
                })
            elif User.objects.filter(email=form.cleaned_data['email']).exists():
                return render(request, template, {
                    'form': form,
                    'error_message': 'Email already exists.'
                })
            elif form.cleaned_data['password'] != form.cleaned_data['password_repeat']:
                return render(request, template, {
                    'form': form,
                    'error_message': 'Passwords do not match.'
                })
            else:
                # Create the user:
                user = User.objects.create_user(
                    form.cleaned_data['username'],
                    form.cleaned_data['email'],
                    form.cleaned_data['password']
                )
                user.first_name = form.cleaned_data['first_name']
                user.last_name = form.cleaned_data['last_name']
                user.phone_number = form.cleaned_data['phone_number']
                user.photo = request.FILES['photo']
                user.save()
                

                return redirect('signin')
               

   # No post data available, let's just show the page.
    else:
        form = Profile_Form()

    return render(request, template, {'form': form})

class EmpImageDisplay(DetailView):
    model = ResgisterFrom
    template_name = 'base.html'
    context_object_name = 'user'

这是我的models.py

from django.db import models
from django.contrib.auth.models import User

# Create your models here.

class ResgisterFrom(models.Model):
    username = models.CharField(max_length=200)
    email = models.EmailField(max_length=200)
    password = models.CharField(max_length=200)
    password_repeat = models.CharField(max_length=200)
    first_name = models.CharField(max_length=200)
    last_name = models.CharField(max_length=200)
    phone_number = models.CharField(max_length=200)
    photo = models.ImageField(upload_to='images/')

    def __str__(self):
        return self.username

提前致谢

【问题讨论】:

  • 您在 settings.py 中有错字 - 它应该是 MEDIA_URL(全部大写)而不是 MEDIA_URl。我不知道这是否能解决问题 - 请包含完整的回溯,以便我们查看错误发生的位置。
  • 您已从您的设置中泄露了您的SECRET_KEY - 请确保在部署您的站点之前更改它。
  • @Alasdair。错误已解决。感谢您承认秘密密钥。现在又一个问题上传的图片没有存入磁盘,请帮帮我
  • 如果您有新问题,请开始一个新问题。您已将此答案标记为已接受,因此人们不会意识到您仍然需要答案。
  • 感谢@Alasdir 提醒有关密钥的信息。这个应用程序不会投入生产,因为我仍然是一个学习者。好的,我将开始另一个问题。

标签: python django django-models django-views


【解决方案1】:

在你的 settings.py 你应该添加/

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

【讨论】:

    猜你喜欢
    • 2022-12-03
    • 2012-07-29
    • 2011-08-25
    • 2013-12-26
    • 2018-12-22
    • 2013-12-18
    • 1970-01-01
    • 2018-09-14
    • 1970-01-01
    相关资源
    最近更新 更多