如何在 Django 中解决 /route/blah/ 处的模型匹配
How to solve Model matching at /route/blah/ in django
您好,我目前正在制作一个使用 django allauth 和 Google Auth
的 Django 应用程序
Issue is that when I login using django allauth and try to access the route /profile/view/
It throws this huge error at me, below is just the minified version
有关更多帮助,这是以下文件的代码...
models.py
from django.db import models
from django.core.validators import FileExtensionValidator
from django.utils import timezone
from django.contrib.auth.models import User
class Profile(models.Model):
COUNTRY_CHOICES = (
('No region selected ...', 'No region selected ...'),
('The Caribbean', 'The Caribbean'),
('Central America', 'Central America'),
('North America', 'North America'),
('South America', 'South America'),
('Oceania', 'Oceania'),
('Africa', 'Africa'),
('Europe', 'Europe'),
('Asia', 'Asia'),
)
first_name = models.CharField(max_length=30, blank=True, default="John")
last_name = models.CharField(max_length=30, blank=True, default="Doe")
username = models.CharField(max_length=100, blank=False, null=False, default="FireCDN-User")
description = models.TextField(max_length=240, blank=True, default="No informations provided ...")
region = models.CharField(max_length=50, blank=False, default="No country selected ...", choices=COUNTRY_CHOICES)
avatar = models.ImageField(upload_to='profile/avatars/', default="shared/avatar/default-avatar.png")
created_at = models.DateTimeField(default=timezone.now)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
verbose_name_plural = "Profiles"
class FileUploads(models.Model):
FILE_TYPE_CHOICES = (
('No file type selected ...', 'No file type selected ...'),
('Stylesheets', 'Stylesheets'),
('JavaScript', 'JavaScript'),
('Documents', 'Documents'),
('Images/Pictures', 'Images/Pictures'),
('Scripts', 'Scripts'),
)
user = models.ForeignKey(Profile, on_delete=models.CASCADE, verbose_name="User Profile")
file = models.FileField(upload_to='storage/files/', blank=False, null=False, validators=[
FileExtensionValidator([
# Image Files
"tiff",
"svg",
"pdf",
"raw",
"webp",
"gif",
"heif",
"heic",
"psd",
"ind",
"indt",
"indd",
"png",
"jpg",
"jpeg",
"jfif",
"bmp",
"dib",
"pdf",
"arw",
"cr2",
"nrw",
"k25",
"tif",
"jfi",
"jpe",
"jif",
"ai",
"eps",
"svgz"
"jp2",
"j2k",
"jpf",
"jpx",
"jpm",
"mj2"
# Stylesheet Files
"css",
"less",
"sass",
"scss",
# Scripts / JavaScript Files
"py",
"js",
"ts",
# Misc: (Microsoft Word)
"docx",
"txt",
])
], verbose_name="File Path")
file_name = models.CharField(max_length=50, default="File name needs to be provided!")
file_type = models.CharField(max_length=25, choices=FILE_TYPE_CHOICES, default="no file type selected ...")
created_at = models.DateTimeField(default=timezone.now)
class Meta:
verbose_name_plural = "File Uploads"
views.py
from django.shortcuts import render
from .forms import FileUploadsForm
from django.http import HttpResponseRedirect
from user_profiles.models import Profile
from django.contrib.auth.decorators import login_required
@login_required
def profile_view(request):
user = request.user
profile = Profile.objects.get(username=user)
form = FileUploadsForm(request.POST or None, request.FILES or None, instance=profile)
if request.method == "POST":
if form.is_valid():
form.save()
return HttpResponseRedirect("/profile/files/list/")
context = {
"form": form,
"profile": profile,
}
return render(request, "profiles/profile.html", context)
# Function to render 404 error
def page_not_found(request, exception):
error_message_code = "404"
error_message = "Not Found"
context = {
"error_code": error_message_code,
"error_message": error_message,
}
return render(request, "shared/errors/404.html", context)
# Function to render 500 error
def server_error(request):
error_message_code = "500"
error_message = "Internal Server Error"
context = {
"error_code": error_message_code,
"error_message": error_message,
}
return render(request, "shared/errors/500.html", context)
def file_uploads_list(request):
file_uploads = Profile.objects.get(username=request.user)
context = {
}
return render(request, "profiles/file-uploads/list.html", context)
urls.py
from django.urls import path
from .views import profile_view, file_uploads_list
urlpatterns = [
path('view/', profile_view, name='profile-view'),
path('files/list/', file_uploads_list, name='file_uploads-view'),
]
The error is below:
Traceback (most recent call last):
File "C:\Users\lokot\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\lokot\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\lokot\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "C:\Users\lokot\Desktop\Django Applications\django-project-2\src\user_profiles\views.py", line 11, in profile_view
profile = Profile.objects.get(username=user)
File "C:\Users\lokot\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\lokot\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py", line 429, in get
raise self.model.DoesNotExist(
Exception Type: DoesNotExist at /profile/view/
Exception Value: Profile matching query does not exist.
老实说,我真的需要帮助,因为我 运行 没有办法解决它...
If you need more info just ask
改变这个:
user = request.user
profile = Profile.objects.get(username=user)
至
user = request.user.username
profile = Profile.objects.get(username=user)
在你的views.py...
user = request.user
profile = Profile.objects.get(username=user)
是什么引发了错误。如果您的用户未通过身份验证,这可能总是会发生,因此您应该使用...
if request.user.is_authenticated:
user = ...
此外,request.user returns 和 AUTH_USER_MODEL。您的第二行查询配置文件的用户名是否等于 AUTH_USER_MODEL。相反,它应该查询您的用户模型的用户名。
if request.user.is_authenticated():
user = request.user.username
profile = Profile.objects.get(username=user)
您好,我目前正在制作一个使用 django allauth 和 Google Auth
的 Django 应用程序Issue is that when I login using django allauth and try to access the route /profile/view/
It throws this huge error at me, below is just the minified version
有关更多帮助,这是以下文件的代码...
models.py
from django.db import models
from django.core.validators import FileExtensionValidator
from django.utils import timezone
from django.contrib.auth.models import User
class Profile(models.Model):
COUNTRY_CHOICES = (
('No region selected ...', 'No region selected ...'),
('The Caribbean', 'The Caribbean'),
('Central America', 'Central America'),
('North America', 'North America'),
('South America', 'South America'),
('Oceania', 'Oceania'),
('Africa', 'Africa'),
('Europe', 'Europe'),
('Asia', 'Asia'),
)
first_name = models.CharField(max_length=30, blank=True, default="John")
last_name = models.CharField(max_length=30, blank=True, default="Doe")
username = models.CharField(max_length=100, blank=False, null=False, default="FireCDN-User")
description = models.TextField(max_length=240, blank=True, default="No informations provided ...")
region = models.CharField(max_length=50, blank=False, default="No country selected ...", choices=COUNTRY_CHOICES)
avatar = models.ImageField(upload_to='profile/avatars/', default="shared/avatar/default-avatar.png")
created_at = models.DateTimeField(default=timezone.now)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
verbose_name_plural = "Profiles"
class FileUploads(models.Model):
FILE_TYPE_CHOICES = (
('No file type selected ...', 'No file type selected ...'),
('Stylesheets', 'Stylesheets'),
('JavaScript', 'JavaScript'),
('Documents', 'Documents'),
('Images/Pictures', 'Images/Pictures'),
('Scripts', 'Scripts'),
)
user = models.ForeignKey(Profile, on_delete=models.CASCADE, verbose_name="User Profile")
file = models.FileField(upload_to='storage/files/', blank=False, null=False, validators=[
FileExtensionValidator([
# Image Files
"tiff",
"svg",
"pdf",
"raw",
"webp",
"gif",
"heif",
"heic",
"psd",
"ind",
"indt",
"indd",
"png",
"jpg",
"jpeg",
"jfif",
"bmp",
"dib",
"pdf",
"arw",
"cr2",
"nrw",
"k25",
"tif",
"jfi",
"jpe",
"jif",
"ai",
"eps",
"svgz"
"jp2",
"j2k",
"jpf",
"jpx",
"jpm",
"mj2"
# Stylesheet Files
"css",
"less",
"sass",
"scss",
# Scripts / JavaScript Files
"py",
"js",
"ts",
# Misc: (Microsoft Word)
"docx",
"txt",
])
], verbose_name="File Path")
file_name = models.CharField(max_length=50, default="File name needs to be provided!")
file_type = models.CharField(max_length=25, choices=FILE_TYPE_CHOICES, default="no file type selected ...")
created_at = models.DateTimeField(default=timezone.now)
class Meta:
verbose_name_plural = "File Uploads"
views.py
from django.shortcuts import render
from .forms import FileUploadsForm
from django.http import HttpResponseRedirect
from user_profiles.models import Profile
from django.contrib.auth.decorators import login_required
@login_required
def profile_view(request):
user = request.user
profile = Profile.objects.get(username=user)
form = FileUploadsForm(request.POST or None, request.FILES or None, instance=profile)
if request.method == "POST":
if form.is_valid():
form.save()
return HttpResponseRedirect("/profile/files/list/")
context = {
"form": form,
"profile": profile,
}
return render(request, "profiles/profile.html", context)
# Function to render 404 error
def page_not_found(request, exception):
error_message_code = "404"
error_message = "Not Found"
context = {
"error_code": error_message_code,
"error_message": error_message,
}
return render(request, "shared/errors/404.html", context)
# Function to render 500 error
def server_error(request):
error_message_code = "500"
error_message = "Internal Server Error"
context = {
"error_code": error_message_code,
"error_message": error_message,
}
return render(request, "shared/errors/500.html", context)
def file_uploads_list(request):
file_uploads = Profile.objects.get(username=request.user)
context = {
}
return render(request, "profiles/file-uploads/list.html", context)
urls.py
from django.urls import path
from .views import profile_view, file_uploads_list
urlpatterns = [
path('view/', profile_view, name='profile-view'),
path('files/list/', file_uploads_list, name='file_uploads-view'),
]
The error is below:
Traceback (most recent call last):
File "C:\Users\lokot\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\lokot\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\lokot\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "C:\Users\lokot\Desktop\Django Applications\django-project-2\src\user_profiles\views.py", line 11, in profile_view
profile = Profile.objects.get(username=user)
File "C:\Users\lokot\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\lokot\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py", line 429, in get
raise self.model.DoesNotExist(
Exception Type: DoesNotExist at /profile/view/
Exception Value: Profile matching query does not exist.
老实说,我真的需要帮助,因为我 运行 没有办法解决它...
If you need more info just ask
改变这个:
user = request.user
profile = Profile.objects.get(username=user)
至
user = request.user.username
profile = Profile.objects.get(username=user)
在你的views.py...
user = request.user
profile = Profile.objects.get(username=user)
是什么引发了错误。如果您的用户未通过身份验证,这可能总是会发生,因此您应该使用...
if request.user.is_authenticated:
user = ...
此外,request.user returns 和 AUTH_USER_MODEL。您的第二行查询配置文件的用户名是否等于 AUTH_USER_MODEL。相反,它应该查询您的用户模型的用户名。
if request.user.is_authenticated():
user = request.user.username
profile = Profile.objects.get(username=user)