简体   繁体   English

如何在我的 Url 中传递多个参数

[英]How can I pass in multiple parameters in my Url

So I'm a developer noobie, and building my first project from scratch.所以我是一个开发新手,从头开始构建我的第一个项目。 I'm currently building a messaging system for my app.我目前正在为我的应用程序构建一个消息传递系统。 How it's supposed to work is that A user goes to a link that checks their current conversations, so conversations are displayed.它的工作原理是用户转到一个链接来检查他们当前的对话,因此会显示对话。 Then FROM the conversations, there is a link that takes them to a page that displays the contents of that conversation.然后从对话中,有一个链接将他们带到显示该对话内容的页面。 But I'm having a problem here, because when I try to get the other user's pk to display their messages, my code is instead getting request.user pk and getting ALL the messages that the current user has going on not exclusively between 2 users within that specific conversation.但是我在这里遇到了一个问题,因为当我尝试让其他用户的 pk 显示他们的消息时,我的代码改为获取request.user pk 并获取当前用户不完全在 2 个用户之间进行的所有消息在那个特定的对话中。 Now, when I manually, and by manually I mean typing the actual pk of the specific user I want to check on that has messages with my user, when I manually enter their pk number in the http, I am able to get the correct messages and exclusive messages.现在,当我手动和手动输入我想要检查的特定用户的实际 pk 时,当我在 http 中手动输入他们的 pk 号时,我能够得到正确的消息和独家消息。 Currently, my href link is passing conversation.pk and I haven't figured out how to get the other users pk.目前,我的href链接正在传递conversation.pk ,我还没有弄清楚如何让其他用户pk。 Everything I have tried has kept passing my request.user pk.我尝试过的一切都通过了我的request.user pk。 So I guess what I'm asking is how can I get the other users pk passed in with my url?所以我想我要问的是如何让其他用户 pk 与我的 url 一起传递? I am assuming I need to keep conversation.pk, and add the other users pk as another parameter.我假设我需要保留 conversation.pk,并将其他用户 pk 添加为另一个参数。 Or, is there another way to do this?或者,还有其他方法可以做到这一点吗? Perhaps putting some extra logic in my view?也许在我看来可以添加一些额外的逻辑? Or in the template?还是在模板中? I'm rather stuck here.我比较卡在这里。

views.py/ message and messages 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/message, messages urls.py/message,消息

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

messages.html消息.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消息.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 ** **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

Ok I ended up figuring out my own problem.好的,我最终找出了自己的问题。 Ok, so what I was doing wrong was passing the Conversation.pk rather than the other users pk.好的,所以我做错的是传递Conversation.pk而不是其他用户pk。 By passing in the conversation pk, I wasn't able to exclusively filter through only messages between the two users, but I was getting messages that weren't exclusive between the two users.通过传入对话 pk,我无法仅过滤两个用户之间的消息,但我收到的消息不是两个用户之间的专有消息。 And, the conversation PK will always have fewer pk's than users.而且,会话 PK 的 pk 总是比用户少。 There may be 3 conversation objects, but 5 users with differing pk's.可能有 3 个对话对象,但 5 个用户的 pk 不同。 Anyhow, the solution was simply to change conversation.pk to member.pk like so in messages.html无论如何,解决方案只是将conversation.pk更改为member.pk ,就像在 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:messages' member.pk %}">Start messaging </a>
        <br><br>
    {% endif %}{% endfor %}

</li>
{%endfor %}

And then, I tweaked my message.html to filter between request.user and other_user然后,我调整了我的 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 %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM