Я пытаюсь запросить мои Conversation
объекты и получить объект convo, который может быть уже создан или не создан между двумя пользователями. Затем я хочу получить get_or_create один проход в двух пользователей. Теперь я получаю объект запроса не может. Используйте профиль "... не уверен, почему это так. Я должен возвращать список, который я могу добавить, или, если он не может его получить, он должен его создать. Conversation
объект имеет поле ManyToMany с именем Members
. Profile
- это моя пользовательская модель, которую я создал.
** ошибка **
ValueError at /message/2/
Cannot use QuerySet for "Conversation": Use a QuerySet for "Profile".
Request Method: GET
Request URL: http://localhost:8000/message/2/
Django Version: 2.2.3
Exception Type: ValueError
Exception Value:
Cannot use QuerySet for "Conversation": Use a QuerySet for "Profile".
Exception Location: /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/sql/query.py in check_related_objects, line 1081
Python Executable: /Library/Frameworks/Python.framework/Versions/3.7/bin/python3
Python Version: 3.7.3
Python Path:
['/Users/papichulo/Documents/DatingAppCustom',
'/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']
views.py / Message
def message (request, profile_id):
other_user = get_object_or_404(Profile,id=profile_id)
members_query = Conversation.objects.filter(members= request.user).filter(members= other_user)
conversation, created = Conversation.objects.get_or_create( members = members_query)
if request.method == 'POST':
form = MessageForm(request.POST, instance= request.user, sender=request.user, conversation = conversation, message=message, date=date)
if form.is_valid():
form.save()
return redirect ('dating_app:messages.html')
else:
conversation, created = Conversation.objects.get_or_create( members= [request.user, other_user])
form = MessageForm(instance= request.user, sender=request.user, conversation= conversation, message=message, date=date)
context = {'form' : form }
return render(request, 'dating_app:messages.html', context)
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 Conversation(models.Model):
members = models.ManyToManyField(settings.AUTH_USER_MODEL)