Не уверен, что здесь происходит не так. Если два пользователя проголосовали "за" друг против друга, следовательно, оба имеют атрибут голосования "Истина", я пытаюсь добавить их обоих в свою базу данных матчей. Но это не работает, и я не понимаю, почему. Посмотрел немного на другие подобные посты, все еще застрял.
** ошибка **
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 148, in nope
return create_vote(request, profile_id, False)
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 422, in create
obj.save(force_insert=True, using=self.db)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/base.py", line 741, in save
force_update=force_update, update_fields=update_fields)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/base.py", line 779, in save_base
force_update, using, update_fields,
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/base.py", line 870, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/base.py", line 908, in _do_insert
using=using, raw=raw)
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 1186, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1335, in execute_sql
cursor.execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/utils.py", line 99, in execute
return super().execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/utils.py", line 67, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 383, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: UNIQUE constraint failed: dating_app_uservote.user_id, dating_app_uservote.voter_id
views.py / create_vote
def create_vote(request, profile_id, vote):
profile = Profile.objects.get(pk=profile_id)
UserVote.objects.create(
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(User.objects.get(username=profile.username))
npm = Profile.objects.get(user=profile)
npm.matches.add(User.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'))
смешаться. html
{% extends "dating_app/base.html" %}
{% load bootstrap4 %}
{% block content %}
<div class="tindero">
{% if profile %}
<div class="container content is-child box column is-4 is-offset-4">
<img src="{{ profile.photo.url }}" width="300">
<p style="font-size: 25px">{{profile.username}}</p>
<b>Bio:</b>
<p>{{profile.description}}</p>
<div class="columns has-text-centered">
<div class="column is-half">
<a href="{% url 'dating_app:nope' profile.id %}" class="button is-danger" style="width: 100%"> Dislike </a>
</div>
<div class="column">
<a href="{% url 'dating_app:nice' profile.id %}" class="button is-primary" style="width: 100%"> Like </a>
</div>
</div>
</div>
{% else %}
<br><br>
<p>Wait for more people to join!</p>
<p>Help us get more user. Share this link to your friends! <a href="http://localhost:8000/">http://localhost:8000/</a></p>
{% endif %}
{% endblock %}
все views.py
def home(request):
return render(request, 'dating_app/home.html')
def profiles(request):
"Shows a list of profiles that have been created"
profiles = Profile.objects.order_by('date_joined')
context = {'profiles' : profiles}
return render(request, 'dating_app/profiles.html',context)
def profile(request, profile_id):
"""show a single profile"""
profile = get_object_or_404(Profile,id=profile_id)
context = {'profile' : profile}
return render(request, 'dating_app/profile.html', context)
# Below is related to users
def logout_view(request):
"""Log out the user """
logout(request)
return HttpResponseRedirect(reverse('dating_app:home'))
def register(request, profile_id):
user =User.objects.get(pk=profile_id)
user.profile.bio = 'fjfjfjjf'
user.save()
def register(request):
#Register a new user
context = {}
if request.POST:
form = RegistrationForm(request.POST, request.FILES)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
email = form.cleaned_data.get("email")
description = form.cleaned_data.get("description")
photo = form.cleaned_data.get("photo")
raw_password = form.cleaned_data.get('password1')
profile = authenticate(username=username,email=email,description=description, photo=photo, password=raw_password)
login(request, profile)
return redirect ('dating_app:home')
else:
context['registration_form'] = form
else: #get request
form = RegistrationForm()
context['registration_form'] = form
return render(request, 'dating_app/register.html', context)
def update_account(request, profile_id):
#Edit an existing profile
profile = get_object_or_404(Profile,id=profile_id)
update_form = ProfileUpdateForm(request.POST, request.FILES)
if request.method != 'POST':
#Initial request; prefil form with current entry
update_form = ProfileUpdateForm(instance=profile)
else:
#POST data submitted;process data.
update_form = ProfileUpdateForm(instance=profile, data=request.POST, files=request.FILES)
if update_form.is_valid():
update_form.save()
return HttpResponseRedirect(reverse('dating_app:profile', args=[profile.id]))
context = {'profile' : profile, 'update_form' : update_form}
return render(request, 'dating_app/update.html', context)
#matching
def mingle(request):
try:
profile = (Profile.objects.exclude(id=request.user.id).exclude(uservote__voter=request.user).order_by('?')[0])
except IndexError:
profile = None
print(Profile.username)
try:
description = request.user.description
except Profile.DoesNotExist:
create = Profile.objects.get_or_create(request.user)
return redirect('profile')
match = request.user.matches.all()
context = dict(profile = profile, match = match)
return render(request, 'dating_app/mingle.html', context)
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.create(
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(user=request.user)
npm.matches.add(User.objects.get(username=profile.username))
npm = Profile.objects.get(user=profile)
npm.matches.add(User.objects.get(username=request.user))
npm.save()
return render(request, 'dating_app/matches.html', dict(
match=profile,
))
return redirect('dating_app:mingle')
def view_matches(request,profile_id):
match = request.user.matches.all()
profile = get_object_or_404(Profile,id=profile_id)
context = {'match' : match, 'profile' : profile}
return render(request, 'dating_app/matches.html', context)