我正在上传两个文件,然后将它们与 xxhash 算法进行比较,如果它们相同或不同,则返回相同的值,但是当提交包含文件的表单时,它不会将其重定向到视图中发挥作用的函数,而是给我错误 404:
找不到页面 (404) 请求方法:GET 请求 URL:http://127.0.0.1:8000/post?file1=f.txt&file2=t.txt 使用 URLconf 定义在 hashhosh.urls 中,Django 尝试了这些 URL 模式,在 此订单:
admin/ [name='home'] 登录/ [name='login'] 比较文件/ [name='compare-files'] 当前路径 post 与其中任何一个都不匹配
为什么会这样? urls.py:
from django.contrib import admin
from django.urls import path
from django.contrib.auth.views import LoginView
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home_view, name='home'),
path('login/', LoginView.as_view(template_name='login.html'), name='login'),
path('compare-files/', views.compare_files_view, name='compare-files'), # Update the URL pattern
]
views.py:
from django.contrib.auth.views import LoginView
from django.shortcuts import render
import xxhash
from django.http import HttpResponse
def home_view(request):
return render(request, 'home.html')
def login_view(request):
return render(request, 'login.html')
def compare_files_view(request): # Update the view name
if request.method == 'POST' and 'file1' in request.FILES and 'file2' in request.FILES:
file1 = request.FILES['file1']
file2 = request.FILES['file2']
result = "Same" if compare_files(file1, file2) else "Different"
return render(request, 'home.html', {'result': result})
else:
return render(request, 'home.html')
def compare_files(file1, file2):
hash1 = xxhash.xxh64(file1.read()).hexdigest()
hash2 = xxhash.xxh64(file2.read()).hexdigest()
return hash1 == hash2
home.html:
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home</title>
</head>
<body>
{% block content %}
{% if user.is_authenticated %}
Yo wassup {{ user.username }}!
<form method="post" action="{% url 'compare-files' %}" enctype="multipart/form-data">
<br>file 1: <br>
<input type = 'file' name="file1"/>
<br>file 2: <br>
<input type = 'file' name="file2"/>
<br><button type="submit">Compare Files</button>
</form>
{% if result %}
<p>Comparison Result: {{ result }}</p>
{% endif %}
{% else %}
<p>please Login</p>
<a href="{% url 'login' %}">Login</a>
{% endif %}
{% endblock %}
</body>
</html>
设置.py:
"""
Django settings for hashhosh project.
Generated by 'django-admin startproject' using Django 5.0.1.
For more information on this file, see
https://docs.djangoproject.com/en/5.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.0/ref/settings/
"""
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/5.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-5q$^nk1tp-fe)w9x25xqg3sy0fg98bhx7rm8gu!lk%b2*z_tfw'
# 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',
]
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 = 'hashhosh.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [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 = 'hashhosh.wsgi.application'
# Database
# https://docs.djangoproject.com/en/5.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
AUTHENTICATION_BACKENDS = [
'hashhosh.backends.xxhash_backend.XXHashAuthBackend',
'django.contrib.auth.backends.ModelBackend',
]
# Password validation
# https://docs.djangoproject.com/en/5.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/5.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.0/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
LOGIN_REDIRECT_URL = 'home'
一些修复(至少是我现在能发现的):
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('appname.urls')), # Change appname to the actual name of your app
]
在您的应用程序目录中(这是您的views.py所在的位置),创建一个urls.py并添加:
from django.urls import path
from . import views
app_name = 'appname' # Change appname to the name of your app.
urlpatterns = [
path('home_view/', views.home_view, name='home_view'),
path('login_view/', views.login_view, name='login_view'),
# Add other url patterns here
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'appname', # Your app name. Please change to your app name
]