У меня тут какие-то проблемы, и я не могу понять, что происходит. Я работаю над сопоставлением двух пользователей, если они проголосуют друг за друга, и затем сохранением их в базе данных на основе их совпадений, а затем их отображением. Если я вручную добавляю пользователей через админ, это работает нормально. Фактически, если бы я удалил 2-й метод create_vote, первый работал бы просто отлично и сохранил голосование в объекте user_vote. Однако, когда я добавляю второй метод create_vote, который мне нужен для создания «совпадений», он не работает и, похоже, у меня возникают проблемы с простым созданием голосования для начала.
трассировщик:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/papichulo/Documents/DatingAppCustom/dating_app/views.py", line 144, in nice
return create_vote(request, profile_id, True)
File "/Users/papichulo/Documents/DatingAppCustom/dating_app/views.py", line 159, in create_vote
vote=vote
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/query.py", line 408, in get
self.model._meta.object_name
dating_app.models.UserVote.DoesNotExist: UserVote matching query does not exist
views.py / методы, которые я использую для сопоставления
def create_vote(request, profile_id, vote):
profile = Profile.objects.get(pk=profile_id)
UserVote.objects.create(
user = profile,
voter = request.user,
vote = vote
)
return redirect('dating_app:mingle')
def nice(request, profile_id):
return create_vote(request, profile_id, True)
def nope(request, profile_id):
return create_vote(request, profile_id, False)
def create_vote(request, profile_id, vote):
profile = Profile.objects.get(pk=profile_id)
UserVote.objects.get(
user=profile,
voter=request.user,
vote=vote
)
if vote:
if UserVote.objects.filter(
user = request.user,
voter=profile,
vote=True
).count():
npm = Profile.objects.get(request.user)
npm.matches.add(Profile.objects.get(username=profile.username))
npm = Profile.objects.get(user=profile)
npm.matches.add(Profile.objects.get(username=request.user))
npm.save()
return render(request, 'dating_app/matches.html', dict(
match=profile,
))
return redirect('dating_app:mingle')
models.py
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):
class Meta:
swappable = 'AUTH_USER_MODEL'
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'))