如何在网址中传递多个参数

时间:2020-04-20 17:47:26

标签: django

所以我是一名开发人员,正在从头开始构建我的第一个项目。我目前正在为我的应用构建消息系统。它应该如何工作是用户转到检查其当前对话的链接,因此显示对话。然后,在对话中,有一个链接将其带到显示该对话内容的页面。但是我在这里遇到了问题,因为当我尝试获取另一个用户的pk显示其消息时,我的代码改为获取request.user pk并获取当前用户正在进行的所有消息,而不仅仅是该特定对话中有2位用户。现在,当我手动进行操作时,我的意思是键入要检查的特定用户的实际pk,并与该用户一起发送消息,当我在http中手动输入其pk编号时,便可以获取正确的消息和独家消息。目前,我的href链接正在传递conversation.pk,但我还没有弄清楚如何获取其他用户pk。我尝试过的所有事情都使我的request.user PK保持了通过。 所以我想我要问的是如何让其他用户的pk与我的URL一起传递?我假设我需要保留session.pk,并将其他用户pk添加为另一个参数。或者,还有另一种方法吗?也许在我看来有一些额外的逻辑?还是在模板中?我宁愿被困在这里。

views.py/消息和消息

#displays active conversations
def messages(request,profile_id):


    conversations = Conversation.objects.filter(
        members= request.user
    ).annotate(
        last_message=Max('instantmessage__date')
    ).prefetch_related('members').order_by(
        '-last_message'
    )


#displays contents of conversations, messages 
def message(request, profile_id):


    receiver = get_object_or_404(Profile,id=profile_id)

    exclusive_conversations = Conversation.objects.filter(members= request.user ).filter(members= receiver)


    messages = InstantMessage.objects.filter(receiver__in=exclusive_conversations)


    context = {'messages' : messages, }

    return render(request, 'dating_app/message.html', context)

urls.py/消息,消息

path('message/<int:profile_id>/', views.message, name='message'),
    path('messages/<int:profile_id>/', views.messages, name='messages'),
]

messages.html

{% for conversation in conversations%}
    <li class="text-right list-group-item">
        {% for member in conversation.members.all %}{% if member != user %}
            {{ member.username }}
            <a href="{% url 'dating_app:message' conversation.pk %}">Start messaging </a>
            <br><br>
        {% endif %}{% endfor %}

    </li>
{%endfor %}

message.html

{% for message in messages %}

        {% if message.sender_id == request.user.id  %}
        <li class="text-right list-group-item"> {{ message.message }}<br>{{ message.date }} </li>
        {% else %}
        <li class="text-left list-group-item"> {{ message.message }}<br>{{ message.date }} </li>

        {% endif %}



{%endfor %}

** 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'))


class Conversation(models.Model):
    members = models.ManyToManyField(settings.AUTH_USER_MODEL)




class InstantMessage(models.Model):

    sender = models.ForeignKey(settings.AUTH_USER_MODEL, related_name= 'senderr',on_delete=models.CASCADE )
    receiver = models.ForeignKey(Conversation, on_delete=models.CASCADE)
    message = models.TextField()
    date = models.DateTimeField(auto_now_add=True)


    def __unicode__(self):
        return self.message

    #tests to see if messages are exclusive between sender, receiver 
    @classmethod
    def find_messages_exclusive_to_profile(cls,sender,receiver):
        #members = receiver AND sender, not receiver or sender 
        exclusive_conversations = Conversation.objects.filter(members= receiver ).filter(members= sender)


        exclusive_messages = InstantMessage.objects.filter(receiver__in=exclusive_conversations)

        return exclusive_messages

1 个答案:

答案 0 :(得分:1)

好吧,我最终弄清楚了自己的问题。好的,所以我做错的是传递Conversation.pk而不是其他用户 pk。通过传递对话pk,我不能只过滤两个用户之间的消息,但是我得到的消息不是两个用户之间的唯一。并且,会话PK总是比用户少。可能有3个对话对象,但5个用户的pk不同。无论如何,解决方案就是像在messages.html中那样简单地将conversation.pk更改为member.pk

{% for conversation in conversations%}
<li class="text-right list-group-item">
    {% for member in conversation.members.all %}{% if member != user %}
        {{ member.username }}
        <a href="{% url 'dating_app:messages' member.pk %}">Start messaging </a>
        <br><br>
    {% endif %}{% endfor %}

</li>
{%endfor %}

然后,我调整了message.html以在request.userother_user之间进行过滤

{% for message in messages %}



        {% if message.sender_id == request.user.id %}
        <li class="text-right list-group-item"> {{ message.message }}<br>{{ message.date }} </li>
        {% elif message.sender_id == profile.id %}
        <li class="text-left list-group-item"> {{ message.message }}<br>{{ message.date }} </li>

        {% endif %}



{%endfor %}