skip to Main Content

I’m having trouble displaying data from current user. It shows all the shifts that was given to other users also. I don’t have any idea how to do this. Below is my code.

models.py

class User(models.Model):
    user_name = models.CharField(max_length=32, unique=True)
    pass_word = models.CharField(max_length=150)
    is_active = models.BooleanField(default=True)

class Rostering(models.Model):
    name = models.CharField(max_length=64)
    begin_time = models.TimeField(default="")
    end_time = models.TimeField(default="")
    is_active = models.BooleanField(default=True)

class RosteringUser(models.Model):
    rostering_user = models.ForeignKey(Rostering, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)

views.py

def my_shift(request):
    if request.method == 'GET':
        queryset = RosteringUser.objects.all()
        if queryset:
            for obj in queryset:
                id = Rostering.objects.get(rosteringuser=obj.id)
                obj.id = id
            return render(request, 'my_shift.html', {'queryset': queryset})

my_shift.html

{% for obj in queryset %}
<tr>
    <td>{{ obj.user.user_name }}</td>
    <td>{{ obj.id.name }}-{{ obj.id.begin_time }}</td>
    <td>{{ obj.id.name }}-{{ obj.id.end_time }}</td>
</tr>
{% endfor %}

Thank you in advance!

2

Answers


  1. Simply you can try like this:

             if queryset:
                for obj in queryset:
                    id = Rostering.objects.get(rosteringuser=obj.id)
                    obj.id = id
                    querysets = obj
                return render(request, 'my_shift.html', {'querysets': querysets})
    

    And in templates:

    {% for object in querysets %}
    <tr>
        <td>{{ object.user.user_name }}</td>
        <td>{{ object.id.name }}-{{ object.id.begin_time }}</td>
        <td>{{ object.id.name }}-{{ object.id.end_time }}</td>
    </tr>
    {% endfor %}
    
    Login or Signup to reply.
  2. def my_shift(request):
        if request.method == 'GET':
            rost_id = RosteringUser.objects.filter(user_id=request.user.id).values("rostering_user_id").first()
            if rost_id :
               data = Rostering.objects.get(id=rost_id['rostering_user_id'])
               return render(request, 'my_shift.html', {'queryset': data })
    

    in template you can directly display logged in username {{ request.user.first_name }}

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search