Хорошо, так что я немного застрял здесь. Я решил создать свою собственную модель пользователя, которая, оказывается, очень сильно болит голова. И не говоря уже о том, что это мой первый django проект с нуля ...
Итак, я создаю приложение для знакомств. У меня есть пример проекта, в котором я хочу использовать некоторый код, перенести его и адаптировать к своему проекту. Я действительно не знаю, как go адаптировать некоторые изменения, которые мне нужны для моей пользовательской модели. Вот ошибка, которую я получаю:
NameError at /mingle/
name 'models' is not defined
Request Method: GET
Request URL: http://localhost:8000/mingle/
Django Version: 2.2.3
Exception Type: NameError
Exception Value:
name 'models' is not defined
Exception Location: /Users/papichulo/Documents/DatingApp/dating_app/views.py in mingle, line 113
Python Executable: /Library/Frameworks/Python.framework/Versions/3.7/bin/python3
Python Version: 3.7.3
Python Path:
['/Users/papichulo/Documents/DatingApp',
'/Library/Frameworks/Python.framework/Versions/3.7/lib/python37.zip',
'/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7',
'/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload',
'/Users/papichulo/Library/Python/3.7/lib/python/site-packages',
'/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages']
Server time: Fri, 3 Apr 2020 00:15:57 +0000
SAMPLE code
try:
user = (User.objects.exclude(id=request.user.id).exclude(uservote__voter=request.user).order_by('?')[0])
except IndexError:
user = None
print(User.username)
try:
bio = models.UserProfile.objects.get(user=request.user).bio
except models.UserProfile.DoesNotExist:
create = UserProfile.objects.get_or_create(user = request.user)
return redirect('profile')
friend = models.UserProfile.objects.get(user=request.user).friends.all()
context = dict(user = user, friend = friend)
return render(request, 'index.html', context)
Мои views.py
def mingle(request):
try:
user = (Profile.objects.exclude(id=request.user.id).exclude(uservote__voter=request.user).order_by('?')[0])
except IndexError:
user = None
print(User.username)
try:
description = models.Profile.objects.get(user=request.user).description
except models.Profile.DoesNotExist:
create = Profile.objects.get_or_create(user = request.user)
return redirect('profile')
match = models.Profile.objects.get(user=request.user).matches.all()
context = dict(user = user, match = match)
return render(request, 'dating_app/mingle.html', context)
my models.py
from django.db import models
from django.contrib.auth.models import AbstractBaseUser,BaseUserManager, User
from dating_project import settings
class ProfileManager(BaseUserManager):
def create_user(self, username, email,description,photo, password=None):
if not email:
raise ValueError("You must creat an email")
if not username:
raise ValueError("You must create a username!")
if not description:
raise ValueError("You must write a description")
if not photo:
raise ValueError("You must upload a photo")
user = self.model(
email=self.normalize_email(email),
username = username,
description= description,
photo= photo,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, username, email,description,photo, password):
user = self.create_user(
email=self.normalize_email(email),
password=password,
username=username,
description=description,
photo=photo,
)
user.is_admin=True
user.is_staff=True
user.is_superuser=True
user.save(using=self._db)
return user
class Profile(AbstractBaseUser):
email = models.EmailField(verbose_name="email")
username = models.CharField(max_length=30, unique=True)
date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
last_login = models.DateTimeField(verbose_name='last login', auto_now=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
#what I added
description = models.TextField()
photo = models.ImageField(upload_to='profile_photo',blank=False, height_field=None, width_field=None, max_length=100)
matches = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='+', blank=True)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['description','photo','email']
objects = ProfileManager()
def __str__(self):
return self.username
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self,app_label):
return True
class UserVote(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
voter = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='given_vote', on_delete=models.CASCADE)
vote = models.BooleanField(default=False)
class Meta:
unique_together = (('user', 'voter'))