#python #django #python-3.8
#python #django #python-3.8
Вопрос:
Здравствуйте, в настоящее время я создаю приложение Django, которое использует django allauth и Google Auth
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:UserslokotAppDataLocalProgramsPythonPython38-32libsite-packagesdjangocorehandlersexception.py", line 47, in inner
response = get_response(request)
File "C:UserslokotAppDataLocalProgramsPythonPython38-32libsite-packagesdjangocorehandlersbase.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:UserslokotAppDataLocalProgramsPythonPython38-32libsite-packagesdjangocontribauthdecorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "C:UserslokotDesktopDjango Applicationsdjango-project-2srcuser_profilesviews.py", line 11, in profile_view
profile = Profile.objects.get(username=user)
File "C:UserslokotAppDataLocalProgramsPythonPython38-32libsite-packagesdjangodbmodelsmanager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:UserslokotAppDataLocalProgramsPythonPython38-32libsite-packagesdjangodbmodelsquery.py", line 429, in get
raise self.model.DoesNotExist(
Exception Type: DoesNotExist at /profile/view/
Exception Value: Profile matching query does not exist.
Честно говоря, мне действительно нужна помощь, потому что у меня закончились идеи по ее исправлению…
Если вам нужна дополнительная информация, просто спросите
Ответ №1:
В вашем views.py…
user = request.user
profile = Profile.objects.get(username=user)
Это то, что выдает ошибку. Это, вероятно, всегда будет происходить, если ваш пользователь не аутентифицирован, поэтому вам следует использовать…
if request.user.is_authenticated:
user = ...
Кроме того, request.user возвращает AUTH_USER_MODEL . Ваша вторая строка запрашивает, равно ли имя пользователя профиля AUTH_USER_MODEL. Вместо этого он должен запросить имя пользователя ваших пользовательских моделей.
if request.user.is_authenticated():
user = request.user.username
profile = Profile.objects.get(username=user)
Ответ №2:
Измените это:
user = request.user
profile = Profile.objects.get(username=user)
Для
user = request.user.username
profile = Profile.objects.get(username=user)