0

im currently trying to figure out how i can check if a status does apply to a users request or not.

models.py

class CategoryRequests(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    status = StatusField()
    STATUS = Choices('Waiting', 'Rejected', 'Accepted')

views.py

def view_profile_categoy_requests_accepted(request, pk=None):
    if pk:
        user = get_user_model.objects.get(pk=pk)
    else:
        user = request.user
    args = {'user': user}
    return render(request, 'myproject/category_request_accepted.html', args)

But at the template this seems to be wrong.

template.html

{% if user.categoryrequests.status == 'Waiting' %}

Thanks in advance

  • What is the value of `status`? Can you do `{{ user.categoryrequests.status }}` to see what it outputs? – xyres Dec 30 '18 at 18:18
  • seems to be empty, do i really have to process this at the views.py? And if so, how? –  Dec 30 '18 at 18:23
  • You can process it anywhere, but if it's empty then it won't ever match with `'Waiting'`. – xyres Dec 30 '18 at 18:31
  • its written at the database but i have no clue why i'm not able to access that field :( –  Dec 30 '18 at 18:35

2 Answers2

0

You could add a related_name argument to ForeignKey in your models.py:

class CategoryRequests(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='status')
    status = StatusField()
    STATUS = Choices('Waiting', 'Rejected', 'Accepted')

Then in the template something like:

{% if user.status.STATUS == 'Waiting' %}

This answer explains more about related_name

v25
  • 7,096
  • 2
  • 20
  • 36
0

There's the problem -- user.categoryrequests. If you haven't set a related_name on the foreignkey field, you can't do reverse lookups like this.

You've two options:

1. EITHER use user.categoryrequests_set to get reverse foreignkey from user.

2. OR, set a related_name on the foreignkey to categoryrequests and then you can do reverse lookup the way you're currently doing.


See the docs about doing reverse lookups.

xyres
  • 20,487
  • 3
  • 56
  • 85
  • {% if user.categoryrequests.cr_status == Waiting %} and author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='cr_status') does the job. thx everybody :D –  Dec 30 '18 at 21:48