Django QuerySet filtering not working with views, showing blank view even though there are entries












0















I am attempting to view a particular set of objects with a certain attribute by using QuerySet filtering, however when I use the filter, the view returns blank. Not sure if I'm using this particular filter wrong, or if I'm calling on the attribute wrong, however I accessed other attributes (as seen below, the attribute "status") and found that it worked fine.



views.py:



from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from .models import *
from .forms import *



@login_required
def vendorView(request):
return render(request, 'inv/vendorInventory.html')

@login_required
def consumerView(request):
return render(request, 'inv/consumerInventory.html')

def unauthenticatedView(request):
return render(request, 'inv/unauthenticatedInventory.html')
################ need to edit other views to render consumer/vendor/unauth

def display_drinks(request):
items = Drinks.objects.all()
context = {
'items': items,
'header': 'Drinks',
}

if not request.user.is_authenticated:
items = Drinks.objects.filter(status='AVAILABLE')
context = {
'items': items,
'header': 'Drinks',
}
return render(request, 'inv/unauthenticatedInventory.html', context)

elif request.user.profile.vendor:
items = Drinks.objects.filter(donatorID=request.user.username)
context = {
'items': items,
'header': 'Drinks',
}
return render(request, 'inv/vendorInventory.html', context)

elif not request.user.profile.vendor:
items = Drinks.objects.filter(status='AVAILABLE')
context = {
'items': items,
'header': 'Drinks',
}
return render(request, 'inv/consumerInventory.html', context)


inventory/models.py:



from django.db import models
from django.contrib.auth.models import User
from users.models import *



# Create your models here.

class Donation(models.Model):

description = models.CharField(max_length=200, blank=False, help_text='Describe your donation here')

choices = ( #for status
('AVAILABLE', 'Item ready to be picked up'),
('RESERVED', 'Item reserved'),
)

expiry = models.CharField(max_length=200, blank=False, help_text="Enter expiration date here")
status = models.CharField(max_length=10, choices=choices, default='AVAILABLE')
misc = models.CharField(max_length=50, blank=False, help_text='Miscellaneous info about your donation')
donatorID = models.CharField(max_length=50, default = User.username)



class Meta:
abstract = True

def __str__(self):
return '{0}'.format(self.description)


class Foods(Donation):
pass

class Drinks(Donation):
pass

class MiscObjects(Donation):
pass


As one can see, in models.py, the donatorID is assigned to the Donation object, and is the user's username. In the function display_drinks (in views.py), in the first elif, it should use the user's username to filter whatever items don't have the matching attribute, place items into a QuerySet that do match - however it displays blank, even though there are items that have matching attributes.



Would anyone know why this is occurring?



Thanks.



edit: as requested, here's vendorInventory.html:



{% extends "blog/base.html" %}

{% block body %}



<center> <div class="add_buttons">


<div class="btn-group-vertical">
<a href="{% url 'display_foods' %}" class="btn btn-outline-info" role="button"> View Food</a>
<a href="{% url 'add_food' %}" class="btn btn-outline-info" role="button"> Add Food</a>
</div>

<div class="btn-group-vertical">
<a href="{% url 'display_drinks' %}" class="btn btn-outline-info" role="button">View Drinks</a>
<a href="{% url 'add_drink' %}" class="btn btn-outline-info" role="button"> Add Drink</a>
</div>

<div class="btn-group-vertical">
<a href="{% url 'display_miscObjects' %}" class="btn btn-outline-info" role="button"> View Misc</a>
<a href="{% url 'add_miscObject' %}" class="btn btn-outline-info" role="button"> Add Misc</a>
</div>


</div>

</center>

<div>

<h4>Currently Viewing {{ header }}</h4>
</div>

<table class="table table-hover">
<thead>
<tr>
<th>id</th>
<th>Description</th>
<th>Expiry Date</th>
<th>Status</th>
<th>Misc</th>
<th>Edit/Delete</th>

</tr>
</thead>

<tbody>

{% for item in items %}

<tr>
<td>{{ item.pk }}
<td>{{ item.description }}</td>
<td>{{ item.expiry }} </td>
<td>{{ item.status }}</td>
<td>{{ item.misc }}</td>

{% if header|lower == "drinks" %}
<td>
<a href="{% url 'edit_drink' item.pk %}" class="btn btn-outline-info" role="button" aria-pressed="true" > Edit</a>
<a href="{% url 'delete_drink' item.pk%}" class="btn btn-danger btn-sm" role="button" aria-pressed="true" > x </a>
</td>
{% elif header|lower == "foods" %}
<td>
<a href="{% url 'edit_food' item.pk %}" class="btn btn-outline-info" role="button" aria-pressed="true" > Edit</a>
<a href="{% url 'delete_food' item.pk%}" class="btn btn-danger btn-sm" role="button" aria-pressed="true" > x </a>
</td>
{% else %}
<td>
<a href="{% url 'edit_miscObject' item.pk %}" class="btn btn-outline-info" role="button" aria-pressed="true" > Edit</a>
<a href="{% url 'delete_miscObject' item.pk%}" class="btn btn-danger btn-sm" role="button" aria-pressed="true" > x </a>
</td>
{% endif %}
</tr>

{% endfor %}

</tbody>
</table>

{% endblock %}


forms.py:



from django import forms
from .models import *


class DrinkForm(forms.ModelForm):
class Meta:
model = Drinks
fields = ('description', 'expiry', 'status', 'misc', 'donator')


class FoodForm(forms.ModelForm):
class Meta:
model = Foods
fields = ('description', 'expiry', 'status', 'misc')


class MiscObjectForm(forms.ModelForm):
class Meta:
model = MiscObjects
fields = ('description', 'expiry', 'status', 'misc')

class ReserveDrinkForm(forms.ModelForm):
class Meta:
model = Drinks
fields = ('status',)


class ReserveFoodForm(forms.ModelForm):
class Meta:
model = Foods
fields = ('status',)


class ReserveMiscObjectForm(forms.ModelForm):
class Meta:
model = MiscObjects
fields = ('status',)









share|improve this question




















  • 1





    default = User.username - this definitely does not work

    – Chiefir
    Jan 3 at 11:38











  • NEVER use fields that can change as foreign keys (here user.username), and ALWAYS use explicit foreign keys (use a Models.ForeignKey). Note that this is nothing django-specific but really relational model basic stuff.

    – bruno desthuilliers
    Jan 3 at 13:13











  • How and yes: NEVER use wildcard imports ("from xxx import *") in real-life code either (not even if the module's author says "it's ok" - it's not, definitly). This (mis)feature's use should be restricted to the python shell when you quickly want to test out something. In real code, it will only make your code harder to read, harder to maintain, and prone to unexpected (and not always easy to spot) breakages.

    – bruno desthuilliers
    Jan 3 at 13:16











  • Can you also post vendorInventory.html as this template is specific to the code path with the issue.

    – Will Keeling
    Jan 3 at 13:31











  • @brunodesthuilliers I've applied an explicit foreign key to the attribute now. It says 'donator = models.ForeignKey(User, on_delete=models.CASCADE)'. In my views, the item filter looks like this: ' items = Drinks.objects.filter(donator__username=request.user.username)'. There are two situations I am running into in forms. A) I don't include 'donator' to be included in the form, and I run into an error saying that donator has been left blank or B) I include 'donator', but when it's displayed on the form it has a dropdown with all usernames, and makes the donator choose his own name.

    – studentprog
    Jan 4 at 5:25


















0















I am attempting to view a particular set of objects with a certain attribute by using QuerySet filtering, however when I use the filter, the view returns blank. Not sure if I'm using this particular filter wrong, or if I'm calling on the attribute wrong, however I accessed other attributes (as seen below, the attribute "status") and found that it worked fine.



views.py:



from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from .models import *
from .forms import *



@login_required
def vendorView(request):
return render(request, 'inv/vendorInventory.html')

@login_required
def consumerView(request):
return render(request, 'inv/consumerInventory.html')

def unauthenticatedView(request):
return render(request, 'inv/unauthenticatedInventory.html')
################ need to edit other views to render consumer/vendor/unauth

def display_drinks(request):
items = Drinks.objects.all()
context = {
'items': items,
'header': 'Drinks',
}

if not request.user.is_authenticated:
items = Drinks.objects.filter(status='AVAILABLE')
context = {
'items': items,
'header': 'Drinks',
}
return render(request, 'inv/unauthenticatedInventory.html', context)

elif request.user.profile.vendor:
items = Drinks.objects.filter(donatorID=request.user.username)
context = {
'items': items,
'header': 'Drinks',
}
return render(request, 'inv/vendorInventory.html', context)

elif not request.user.profile.vendor:
items = Drinks.objects.filter(status='AVAILABLE')
context = {
'items': items,
'header': 'Drinks',
}
return render(request, 'inv/consumerInventory.html', context)


inventory/models.py:



from django.db import models
from django.contrib.auth.models import User
from users.models import *



# Create your models here.

class Donation(models.Model):

description = models.CharField(max_length=200, blank=False, help_text='Describe your donation here')

choices = ( #for status
('AVAILABLE', 'Item ready to be picked up'),
('RESERVED', 'Item reserved'),
)

expiry = models.CharField(max_length=200, blank=False, help_text="Enter expiration date here")
status = models.CharField(max_length=10, choices=choices, default='AVAILABLE')
misc = models.CharField(max_length=50, blank=False, help_text='Miscellaneous info about your donation')
donatorID = models.CharField(max_length=50, default = User.username)



class Meta:
abstract = True

def __str__(self):
return '{0}'.format(self.description)


class Foods(Donation):
pass

class Drinks(Donation):
pass

class MiscObjects(Donation):
pass


As one can see, in models.py, the donatorID is assigned to the Donation object, and is the user's username. In the function display_drinks (in views.py), in the first elif, it should use the user's username to filter whatever items don't have the matching attribute, place items into a QuerySet that do match - however it displays blank, even though there are items that have matching attributes.



Would anyone know why this is occurring?



Thanks.



edit: as requested, here's vendorInventory.html:



{% extends "blog/base.html" %}

{% block body %}



<center> <div class="add_buttons">


<div class="btn-group-vertical">
<a href="{% url 'display_foods' %}" class="btn btn-outline-info" role="button"> View Food</a>
<a href="{% url 'add_food' %}" class="btn btn-outline-info" role="button"> Add Food</a>
</div>

<div class="btn-group-vertical">
<a href="{% url 'display_drinks' %}" class="btn btn-outline-info" role="button">View Drinks</a>
<a href="{% url 'add_drink' %}" class="btn btn-outline-info" role="button"> Add Drink</a>
</div>

<div class="btn-group-vertical">
<a href="{% url 'display_miscObjects' %}" class="btn btn-outline-info" role="button"> View Misc</a>
<a href="{% url 'add_miscObject' %}" class="btn btn-outline-info" role="button"> Add Misc</a>
</div>


</div>

</center>

<div>

<h4>Currently Viewing {{ header }}</h4>
</div>

<table class="table table-hover">
<thead>
<tr>
<th>id</th>
<th>Description</th>
<th>Expiry Date</th>
<th>Status</th>
<th>Misc</th>
<th>Edit/Delete</th>

</tr>
</thead>

<tbody>

{% for item in items %}

<tr>
<td>{{ item.pk }}
<td>{{ item.description }}</td>
<td>{{ item.expiry }} </td>
<td>{{ item.status }}</td>
<td>{{ item.misc }}</td>

{% if header|lower == "drinks" %}
<td>
<a href="{% url 'edit_drink' item.pk %}" class="btn btn-outline-info" role="button" aria-pressed="true" > Edit</a>
<a href="{% url 'delete_drink' item.pk%}" class="btn btn-danger btn-sm" role="button" aria-pressed="true" > x </a>
</td>
{% elif header|lower == "foods" %}
<td>
<a href="{% url 'edit_food' item.pk %}" class="btn btn-outline-info" role="button" aria-pressed="true" > Edit</a>
<a href="{% url 'delete_food' item.pk%}" class="btn btn-danger btn-sm" role="button" aria-pressed="true" > x </a>
</td>
{% else %}
<td>
<a href="{% url 'edit_miscObject' item.pk %}" class="btn btn-outline-info" role="button" aria-pressed="true" > Edit</a>
<a href="{% url 'delete_miscObject' item.pk%}" class="btn btn-danger btn-sm" role="button" aria-pressed="true" > x </a>
</td>
{% endif %}
</tr>

{% endfor %}

</tbody>
</table>

{% endblock %}


forms.py:



from django import forms
from .models import *


class DrinkForm(forms.ModelForm):
class Meta:
model = Drinks
fields = ('description', 'expiry', 'status', 'misc', 'donator')


class FoodForm(forms.ModelForm):
class Meta:
model = Foods
fields = ('description', 'expiry', 'status', 'misc')


class MiscObjectForm(forms.ModelForm):
class Meta:
model = MiscObjects
fields = ('description', 'expiry', 'status', 'misc')

class ReserveDrinkForm(forms.ModelForm):
class Meta:
model = Drinks
fields = ('status',)


class ReserveFoodForm(forms.ModelForm):
class Meta:
model = Foods
fields = ('status',)


class ReserveMiscObjectForm(forms.ModelForm):
class Meta:
model = MiscObjects
fields = ('status',)









share|improve this question




















  • 1





    default = User.username - this definitely does not work

    – Chiefir
    Jan 3 at 11:38











  • NEVER use fields that can change as foreign keys (here user.username), and ALWAYS use explicit foreign keys (use a Models.ForeignKey). Note that this is nothing django-specific but really relational model basic stuff.

    – bruno desthuilliers
    Jan 3 at 13:13











  • How and yes: NEVER use wildcard imports ("from xxx import *") in real-life code either (not even if the module's author says "it's ok" - it's not, definitly). This (mis)feature's use should be restricted to the python shell when you quickly want to test out something. In real code, it will only make your code harder to read, harder to maintain, and prone to unexpected (and not always easy to spot) breakages.

    – bruno desthuilliers
    Jan 3 at 13:16











  • Can you also post vendorInventory.html as this template is specific to the code path with the issue.

    – Will Keeling
    Jan 3 at 13:31











  • @brunodesthuilliers I've applied an explicit foreign key to the attribute now. It says 'donator = models.ForeignKey(User, on_delete=models.CASCADE)'. In my views, the item filter looks like this: ' items = Drinks.objects.filter(donator__username=request.user.username)'. There are two situations I am running into in forms. A) I don't include 'donator' to be included in the form, and I run into an error saying that donator has been left blank or B) I include 'donator', but when it's displayed on the form it has a dropdown with all usernames, and makes the donator choose his own name.

    – studentprog
    Jan 4 at 5:25
















0












0








0








I am attempting to view a particular set of objects with a certain attribute by using QuerySet filtering, however when I use the filter, the view returns blank. Not sure if I'm using this particular filter wrong, or if I'm calling on the attribute wrong, however I accessed other attributes (as seen below, the attribute "status") and found that it worked fine.



views.py:



from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from .models import *
from .forms import *



@login_required
def vendorView(request):
return render(request, 'inv/vendorInventory.html')

@login_required
def consumerView(request):
return render(request, 'inv/consumerInventory.html')

def unauthenticatedView(request):
return render(request, 'inv/unauthenticatedInventory.html')
################ need to edit other views to render consumer/vendor/unauth

def display_drinks(request):
items = Drinks.objects.all()
context = {
'items': items,
'header': 'Drinks',
}

if not request.user.is_authenticated:
items = Drinks.objects.filter(status='AVAILABLE')
context = {
'items': items,
'header': 'Drinks',
}
return render(request, 'inv/unauthenticatedInventory.html', context)

elif request.user.profile.vendor:
items = Drinks.objects.filter(donatorID=request.user.username)
context = {
'items': items,
'header': 'Drinks',
}
return render(request, 'inv/vendorInventory.html', context)

elif not request.user.profile.vendor:
items = Drinks.objects.filter(status='AVAILABLE')
context = {
'items': items,
'header': 'Drinks',
}
return render(request, 'inv/consumerInventory.html', context)


inventory/models.py:



from django.db import models
from django.contrib.auth.models import User
from users.models import *



# Create your models here.

class Donation(models.Model):

description = models.CharField(max_length=200, blank=False, help_text='Describe your donation here')

choices = ( #for status
('AVAILABLE', 'Item ready to be picked up'),
('RESERVED', 'Item reserved'),
)

expiry = models.CharField(max_length=200, blank=False, help_text="Enter expiration date here")
status = models.CharField(max_length=10, choices=choices, default='AVAILABLE')
misc = models.CharField(max_length=50, blank=False, help_text='Miscellaneous info about your donation')
donatorID = models.CharField(max_length=50, default = User.username)



class Meta:
abstract = True

def __str__(self):
return '{0}'.format(self.description)


class Foods(Donation):
pass

class Drinks(Donation):
pass

class MiscObjects(Donation):
pass


As one can see, in models.py, the donatorID is assigned to the Donation object, and is the user's username. In the function display_drinks (in views.py), in the first elif, it should use the user's username to filter whatever items don't have the matching attribute, place items into a QuerySet that do match - however it displays blank, even though there are items that have matching attributes.



Would anyone know why this is occurring?



Thanks.



edit: as requested, here's vendorInventory.html:



{% extends "blog/base.html" %}

{% block body %}



<center> <div class="add_buttons">


<div class="btn-group-vertical">
<a href="{% url 'display_foods' %}" class="btn btn-outline-info" role="button"> View Food</a>
<a href="{% url 'add_food' %}" class="btn btn-outline-info" role="button"> Add Food</a>
</div>

<div class="btn-group-vertical">
<a href="{% url 'display_drinks' %}" class="btn btn-outline-info" role="button">View Drinks</a>
<a href="{% url 'add_drink' %}" class="btn btn-outline-info" role="button"> Add Drink</a>
</div>

<div class="btn-group-vertical">
<a href="{% url 'display_miscObjects' %}" class="btn btn-outline-info" role="button"> View Misc</a>
<a href="{% url 'add_miscObject' %}" class="btn btn-outline-info" role="button"> Add Misc</a>
</div>


</div>

</center>

<div>

<h4>Currently Viewing {{ header }}</h4>
</div>

<table class="table table-hover">
<thead>
<tr>
<th>id</th>
<th>Description</th>
<th>Expiry Date</th>
<th>Status</th>
<th>Misc</th>
<th>Edit/Delete</th>

</tr>
</thead>

<tbody>

{% for item in items %}

<tr>
<td>{{ item.pk }}
<td>{{ item.description }}</td>
<td>{{ item.expiry }} </td>
<td>{{ item.status }}</td>
<td>{{ item.misc }}</td>

{% if header|lower == "drinks" %}
<td>
<a href="{% url 'edit_drink' item.pk %}" class="btn btn-outline-info" role="button" aria-pressed="true" > Edit</a>
<a href="{% url 'delete_drink' item.pk%}" class="btn btn-danger btn-sm" role="button" aria-pressed="true" > x </a>
</td>
{% elif header|lower == "foods" %}
<td>
<a href="{% url 'edit_food' item.pk %}" class="btn btn-outline-info" role="button" aria-pressed="true" > Edit</a>
<a href="{% url 'delete_food' item.pk%}" class="btn btn-danger btn-sm" role="button" aria-pressed="true" > x </a>
</td>
{% else %}
<td>
<a href="{% url 'edit_miscObject' item.pk %}" class="btn btn-outline-info" role="button" aria-pressed="true" > Edit</a>
<a href="{% url 'delete_miscObject' item.pk%}" class="btn btn-danger btn-sm" role="button" aria-pressed="true" > x </a>
</td>
{% endif %}
</tr>

{% endfor %}

</tbody>
</table>

{% endblock %}


forms.py:



from django import forms
from .models import *


class DrinkForm(forms.ModelForm):
class Meta:
model = Drinks
fields = ('description', 'expiry', 'status', 'misc', 'donator')


class FoodForm(forms.ModelForm):
class Meta:
model = Foods
fields = ('description', 'expiry', 'status', 'misc')


class MiscObjectForm(forms.ModelForm):
class Meta:
model = MiscObjects
fields = ('description', 'expiry', 'status', 'misc')

class ReserveDrinkForm(forms.ModelForm):
class Meta:
model = Drinks
fields = ('status',)


class ReserveFoodForm(forms.ModelForm):
class Meta:
model = Foods
fields = ('status',)


class ReserveMiscObjectForm(forms.ModelForm):
class Meta:
model = MiscObjects
fields = ('status',)









share|improve this question
















I am attempting to view a particular set of objects with a certain attribute by using QuerySet filtering, however when I use the filter, the view returns blank. Not sure if I'm using this particular filter wrong, or if I'm calling on the attribute wrong, however I accessed other attributes (as seen below, the attribute "status") and found that it worked fine.



views.py:



from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from .models import *
from .forms import *



@login_required
def vendorView(request):
return render(request, 'inv/vendorInventory.html')

@login_required
def consumerView(request):
return render(request, 'inv/consumerInventory.html')

def unauthenticatedView(request):
return render(request, 'inv/unauthenticatedInventory.html')
################ need to edit other views to render consumer/vendor/unauth

def display_drinks(request):
items = Drinks.objects.all()
context = {
'items': items,
'header': 'Drinks',
}

if not request.user.is_authenticated:
items = Drinks.objects.filter(status='AVAILABLE')
context = {
'items': items,
'header': 'Drinks',
}
return render(request, 'inv/unauthenticatedInventory.html', context)

elif request.user.profile.vendor:
items = Drinks.objects.filter(donatorID=request.user.username)
context = {
'items': items,
'header': 'Drinks',
}
return render(request, 'inv/vendorInventory.html', context)

elif not request.user.profile.vendor:
items = Drinks.objects.filter(status='AVAILABLE')
context = {
'items': items,
'header': 'Drinks',
}
return render(request, 'inv/consumerInventory.html', context)


inventory/models.py:



from django.db import models
from django.contrib.auth.models import User
from users.models import *



# Create your models here.

class Donation(models.Model):

description = models.CharField(max_length=200, blank=False, help_text='Describe your donation here')

choices = ( #for status
('AVAILABLE', 'Item ready to be picked up'),
('RESERVED', 'Item reserved'),
)

expiry = models.CharField(max_length=200, blank=False, help_text="Enter expiration date here")
status = models.CharField(max_length=10, choices=choices, default='AVAILABLE')
misc = models.CharField(max_length=50, blank=False, help_text='Miscellaneous info about your donation')
donatorID = models.CharField(max_length=50, default = User.username)



class Meta:
abstract = True

def __str__(self):
return '{0}'.format(self.description)


class Foods(Donation):
pass

class Drinks(Donation):
pass

class MiscObjects(Donation):
pass


As one can see, in models.py, the donatorID is assigned to the Donation object, and is the user's username. In the function display_drinks (in views.py), in the first elif, it should use the user's username to filter whatever items don't have the matching attribute, place items into a QuerySet that do match - however it displays blank, even though there are items that have matching attributes.



Would anyone know why this is occurring?



Thanks.



edit: as requested, here's vendorInventory.html:



{% extends "blog/base.html" %}

{% block body %}



<center> <div class="add_buttons">


<div class="btn-group-vertical">
<a href="{% url 'display_foods' %}" class="btn btn-outline-info" role="button"> View Food</a>
<a href="{% url 'add_food' %}" class="btn btn-outline-info" role="button"> Add Food</a>
</div>

<div class="btn-group-vertical">
<a href="{% url 'display_drinks' %}" class="btn btn-outline-info" role="button">View Drinks</a>
<a href="{% url 'add_drink' %}" class="btn btn-outline-info" role="button"> Add Drink</a>
</div>

<div class="btn-group-vertical">
<a href="{% url 'display_miscObjects' %}" class="btn btn-outline-info" role="button"> View Misc</a>
<a href="{% url 'add_miscObject' %}" class="btn btn-outline-info" role="button"> Add Misc</a>
</div>


</div>

</center>

<div>

<h4>Currently Viewing {{ header }}</h4>
</div>

<table class="table table-hover">
<thead>
<tr>
<th>id</th>
<th>Description</th>
<th>Expiry Date</th>
<th>Status</th>
<th>Misc</th>
<th>Edit/Delete</th>

</tr>
</thead>

<tbody>

{% for item in items %}

<tr>
<td>{{ item.pk }}
<td>{{ item.description }}</td>
<td>{{ item.expiry }} </td>
<td>{{ item.status }}</td>
<td>{{ item.misc }}</td>

{% if header|lower == "drinks" %}
<td>
<a href="{% url 'edit_drink' item.pk %}" class="btn btn-outline-info" role="button" aria-pressed="true" > Edit</a>
<a href="{% url 'delete_drink' item.pk%}" class="btn btn-danger btn-sm" role="button" aria-pressed="true" > x </a>
</td>
{% elif header|lower == "foods" %}
<td>
<a href="{% url 'edit_food' item.pk %}" class="btn btn-outline-info" role="button" aria-pressed="true" > Edit</a>
<a href="{% url 'delete_food' item.pk%}" class="btn btn-danger btn-sm" role="button" aria-pressed="true" > x </a>
</td>
{% else %}
<td>
<a href="{% url 'edit_miscObject' item.pk %}" class="btn btn-outline-info" role="button" aria-pressed="true" > Edit</a>
<a href="{% url 'delete_miscObject' item.pk%}" class="btn btn-danger btn-sm" role="button" aria-pressed="true" > x </a>
</td>
{% endif %}
</tr>

{% endfor %}

</tbody>
</table>

{% endblock %}


forms.py:



from django import forms
from .models import *


class DrinkForm(forms.ModelForm):
class Meta:
model = Drinks
fields = ('description', 'expiry', 'status', 'misc', 'donator')


class FoodForm(forms.ModelForm):
class Meta:
model = Foods
fields = ('description', 'expiry', 'status', 'misc')


class MiscObjectForm(forms.ModelForm):
class Meta:
model = MiscObjects
fields = ('description', 'expiry', 'status', 'misc')

class ReserveDrinkForm(forms.ModelForm):
class Meta:
model = Drinks
fields = ('status',)


class ReserveFoodForm(forms.ModelForm):
class Meta:
model = Foods
fields = ('status',)


class ReserveMiscObjectForm(forms.ModelForm):
class Meta:
model = MiscObjects
fields = ('status',)






django django-models django-views






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 4 at 6:15







studentprog

















asked Jan 3 at 11:32









studentprogstudentprog

155




155








  • 1





    default = User.username - this definitely does not work

    – Chiefir
    Jan 3 at 11:38











  • NEVER use fields that can change as foreign keys (here user.username), and ALWAYS use explicit foreign keys (use a Models.ForeignKey). Note that this is nothing django-specific but really relational model basic stuff.

    – bruno desthuilliers
    Jan 3 at 13:13











  • How and yes: NEVER use wildcard imports ("from xxx import *") in real-life code either (not even if the module's author says "it's ok" - it's not, definitly). This (mis)feature's use should be restricted to the python shell when you quickly want to test out something. In real code, it will only make your code harder to read, harder to maintain, and prone to unexpected (and not always easy to spot) breakages.

    – bruno desthuilliers
    Jan 3 at 13:16











  • Can you also post vendorInventory.html as this template is specific to the code path with the issue.

    – Will Keeling
    Jan 3 at 13:31











  • @brunodesthuilliers I've applied an explicit foreign key to the attribute now. It says 'donator = models.ForeignKey(User, on_delete=models.CASCADE)'. In my views, the item filter looks like this: ' items = Drinks.objects.filter(donator__username=request.user.username)'. There are two situations I am running into in forms. A) I don't include 'donator' to be included in the form, and I run into an error saying that donator has been left blank or B) I include 'donator', but when it's displayed on the form it has a dropdown with all usernames, and makes the donator choose his own name.

    – studentprog
    Jan 4 at 5:25
















  • 1





    default = User.username - this definitely does not work

    – Chiefir
    Jan 3 at 11:38











  • NEVER use fields that can change as foreign keys (here user.username), and ALWAYS use explicit foreign keys (use a Models.ForeignKey). Note that this is nothing django-specific but really relational model basic stuff.

    – bruno desthuilliers
    Jan 3 at 13:13











  • How and yes: NEVER use wildcard imports ("from xxx import *") in real-life code either (not even if the module's author says "it's ok" - it's not, definitly). This (mis)feature's use should be restricted to the python shell when you quickly want to test out something. In real code, it will only make your code harder to read, harder to maintain, and prone to unexpected (and not always easy to spot) breakages.

    – bruno desthuilliers
    Jan 3 at 13:16











  • Can you also post vendorInventory.html as this template is specific to the code path with the issue.

    – Will Keeling
    Jan 3 at 13:31











  • @brunodesthuilliers I've applied an explicit foreign key to the attribute now. It says 'donator = models.ForeignKey(User, on_delete=models.CASCADE)'. In my views, the item filter looks like this: ' items = Drinks.objects.filter(donator__username=request.user.username)'. There are two situations I am running into in forms. A) I don't include 'donator' to be included in the form, and I run into an error saying that donator has been left blank or B) I include 'donator', but when it's displayed on the form it has a dropdown with all usernames, and makes the donator choose his own name.

    – studentprog
    Jan 4 at 5:25










1




1





default = User.username - this definitely does not work

– Chiefir
Jan 3 at 11:38





default = User.username - this definitely does not work

– Chiefir
Jan 3 at 11:38













NEVER use fields that can change as foreign keys (here user.username), and ALWAYS use explicit foreign keys (use a Models.ForeignKey). Note that this is nothing django-specific but really relational model basic stuff.

– bruno desthuilliers
Jan 3 at 13:13





NEVER use fields that can change as foreign keys (here user.username), and ALWAYS use explicit foreign keys (use a Models.ForeignKey). Note that this is nothing django-specific but really relational model basic stuff.

– bruno desthuilliers
Jan 3 at 13:13













How and yes: NEVER use wildcard imports ("from xxx import *") in real-life code either (not even if the module's author says "it's ok" - it's not, definitly). This (mis)feature's use should be restricted to the python shell when you quickly want to test out something. In real code, it will only make your code harder to read, harder to maintain, and prone to unexpected (and not always easy to spot) breakages.

– bruno desthuilliers
Jan 3 at 13:16





How and yes: NEVER use wildcard imports ("from xxx import *") in real-life code either (not even if the module's author says "it's ok" - it's not, definitly). This (mis)feature's use should be restricted to the python shell when you quickly want to test out something. In real code, it will only make your code harder to read, harder to maintain, and prone to unexpected (and not always easy to spot) breakages.

– bruno desthuilliers
Jan 3 at 13:16













Can you also post vendorInventory.html as this template is specific to the code path with the issue.

– Will Keeling
Jan 3 at 13:31





Can you also post vendorInventory.html as this template is specific to the code path with the issue.

– Will Keeling
Jan 3 at 13:31













@brunodesthuilliers I've applied an explicit foreign key to the attribute now. It says 'donator = models.ForeignKey(User, on_delete=models.CASCADE)'. In my views, the item filter looks like this: ' items = Drinks.objects.filter(donator__username=request.user.username)'. There are two situations I am running into in forms. A) I don't include 'donator' to be included in the form, and I run into an error saying that donator has been left blank or B) I include 'donator', but when it's displayed on the form it has a dropdown with all usernames, and makes the donator choose his own name.

– studentprog
Jan 4 at 5:25







@brunodesthuilliers I've applied an explicit foreign key to the attribute now. It says 'donator = models.ForeignKey(User, on_delete=models.CASCADE)'. In my views, the item filter looks like this: ' items = Drinks.objects.filter(donator__username=request.user.username)'. There are two situations I am running into in forms. A) I don't include 'donator' to be included in the form, and I run into an error saying that donator has been left blank or B) I include 'donator', but when it's displayed on the form it has a dropdown with all usernames, and makes the donator choose his own name.

– studentprog
Jan 4 at 5:25














2 Answers
2






active

oldest

votes


















1














replace this in model
donatorID = models.ForeignKey(User, on_delete=models.CASCADE)



While saveing the data pass Users Object : variable_name = User.objects.get(username=request.user)






share|improve this answer































    1














    # models.py
    from django.db import models
    from users.models import *
    # or if User model is not overwritten: from django.contrib.auth.models import User


    class Donation(models.Model):
    choices = ( # for status
    ('AVAILABLE', 'Item ready to be picked up'),
    ('RESERVED', 'Item reserved'),
    )

    description = models.CharField(max_length=200, help_text='Describe your donation here')
    expiry = models.CharField(max_length=200, help_text="Enter expiration date here")
    status = models.CharField(max_length=10, choices=choices, default='AVAILABLE')
    misc = models.CharField(max_length=50, help_text='Miscellaneous info about your donation')
    donator = models.ForeignKey(User, on_delete=models.CASCADE)

    class Meta:
    abstract = True

    def __str__(self):
    return self.description


    class Foods(Donation):
    pass

    class Drinks(Donation):
    pass

    class MiscObjects(Donation):
    pass


    # views.py
    from django.shortcuts import render, redirect, get_object_or_404
    from django.contrib.auth.decorators import login_required
    from users.models import *
    # or if User model is not overwritten: from django.contrib.auth.models import User
    from .models import *
    from .forms import *



    @login_required
    def vendorView(request):
    return render(request, 'inv/vendorInventory.html')

    @login_required
    def consumerView(request):
    return render(request, 'inv/consumerInventory.html')

    def unauthenticatedView(request):
    return render(request, 'inv/unauthenticatedInventory.html')
    ################ need to edit other views to render consumer/vendor/unauth

    def display_drinks(request):
    items = Drinks.objects.all()
    context = {
    'items': items,
    'header': 'Drinks',
    }

    if not request.user.is_authenticated:
    items = Drinks.objects.filter(status='AVAILABLE')
    context = {
    'items': items,
    'header': 'Drinks',
    }
    return render(request, 'inv/unauthenticatedInventory.html', context)

    elif request.user.profile.vendor:
    items = Drinks.objects.filter(donator__username=request.user.username)
    context = {
    'items': items,
    'header': 'Drinks',
    }
    return render(request, 'inv/vendorInventory.html', context)

    elif not request.user.profile.vendor:
    items = Drinks.objects.filter(status='AVAILABLE')
    context = {
    'items': items,
    'header': 'Drinks',
    }
    return render(request, 'inv/consumerInventory.html', context)


    This will work, BUT better to use class-based views here for example:
    official documentation: https://docs.djangoproject.com/en/dev/topics/class-based-views/



    from django.contrib.auth.mixins import LoginRequiredMixin
    from django.views.generic import TemplateView
    from django.views.generic.list import ListView

    # Better naming for model will be a "Drink" instead of "Drinks" (Django code style)
    from .models import Drinks


    class VendorView(LoginRequiredMixin, TemplateView):
    # better to use 'inv/vendor_inventory.html' naming style for PEP8 compatibility.
    template_name = 'inv/vendorInventory.html'


    class ConsumerView(LoginRequiredMixin, TemplateView):
    template_name = 'inv/consumerInventory.html'

    # Name for view, I think looks terrible ;)
    class UnauthenticatedView(TemplateView):
    template_name = 'inv/unauthenticatedInventory.html'


    class DrinksListView(ListView):
    model = Drinks
    context_object_name = 'items' # Variable in template, better to use something like: context_object_name = 'drinks'

    def get_queryset(self):
    if self.request.user.is_authenticated():
    return Drinks.objects.filter(status='AVAILABLE')
    elif self.request.user.profile.vendor:
    return Drinks.objects.filter(donator__username=self.request.user.username)
    # Better to use "else:" here instead of "elif" (for all other logic).
    elif not self.request.user.profile.vendor:
    return Drinks.objects.filter(status='AVAILABLE')


    Answers for questions from comments:



    If you want to add automatically user for every new Drinks object, you should do something like this:
    First of all, you should exclude field "donator" in your form:



    # forms.py
    class MyForm(forms.ModelForm):
    #.....
    class Meta:
    model = Drinks
    exclude = ('donator', )


    If you use function-based views:
    you should add something like this:



    # views.py
    if request.GET:
    form = MyForm()
    if request.POST:
    form = MyForm(request.POST)
    if form.is_valid():
    drinks = form.save(commit=False)
    drinks.donator = request.user
    drinks.save()
    return render(request, 'my_temlate.html', {'form': form})


    If you use class-based views: you should overwrite "post" method same way. You can find out more here, also there are examples: How do I use CreateView with a ModelForm






    share|improve this answer





















    • 1





      I have to totally disagree with the "better to use class-based views" part - unless you have a need for specialisation (which is actually not the most common case, by far), class-based-views only make simple things MUCH more complicated than they need to be. With all due respect to Django's authors, the decision to force-feed CBVs on users is IMHO one of the most misguided move they made...

      – bruno desthuilliers
      Jan 3 at 13:10











    • Thanks for the comment. First of all class-based views really make simple things much more complicated, because their main use-case is big projects and big parts of the code , so if you have a code base with 100k+ lines of code which was written using class-based views, it looks more readable and predictably than function-based views code. So function-based views good for simple logic, but in big projects better way will be to use class-based views IMHO.

      – om2c0de
      Jan 3 at 13:32











    • I've been using django since the first (0.9.something) public release, I've done literally dozens of (real-life, production) projects with it, the current one being near 500Kloc - is that "big" enough for you ? FWIW I do use CBVs when appropriate (notably for parts of this project - the parts where we do need specialisation). And I maintain that for most cases, CBVs are not only useless but also harmful wrt readability / maintainability. Now I won't go any further about this here (it's getting totally OT) but you can join me in private if you want to discuss this further

      – bruno desthuilliers
      Jan 3 at 13:40











    • @om2c0de, thanks for your help! I've applied the former code right now, and it comes back with no errors, however it does not assign the user's username as an attribute to the Drink object - it only allows for selection of a username from the tables I have.

      – studentprog
      Jan 3 at 20:42











    • Sounds great! I updated the answer, hope it will help you.

      – om2c0de
      Jan 4 at 11:51











    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54021458%2fdjango-queryset-filtering-not-working-with-views-showing-blank-view-even-though%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    replace this in model
    donatorID = models.ForeignKey(User, on_delete=models.CASCADE)



    While saveing the data pass Users Object : variable_name = User.objects.get(username=request.user)






    share|improve this answer




























      1














      replace this in model
      donatorID = models.ForeignKey(User, on_delete=models.CASCADE)



      While saveing the data pass Users Object : variable_name = User.objects.get(username=request.user)






      share|improve this answer


























        1












        1








        1







        replace this in model
        donatorID = models.ForeignKey(User, on_delete=models.CASCADE)



        While saveing the data pass Users Object : variable_name = User.objects.get(username=request.user)






        share|improve this answer













        replace this in model
        donatorID = models.ForeignKey(User, on_delete=models.CASCADE)



        While saveing the data pass Users Object : variable_name = User.objects.get(username=request.user)







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jan 3 at 12:03









        Clifton Avil D'SouzaClifton Avil D'Souza

        184311




        184311

























            1














            # models.py
            from django.db import models
            from users.models import *
            # or if User model is not overwritten: from django.contrib.auth.models import User


            class Donation(models.Model):
            choices = ( # for status
            ('AVAILABLE', 'Item ready to be picked up'),
            ('RESERVED', 'Item reserved'),
            )

            description = models.CharField(max_length=200, help_text='Describe your donation here')
            expiry = models.CharField(max_length=200, help_text="Enter expiration date here")
            status = models.CharField(max_length=10, choices=choices, default='AVAILABLE')
            misc = models.CharField(max_length=50, help_text='Miscellaneous info about your donation')
            donator = models.ForeignKey(User, on_delete=models.CASCADE)

            class Meta:
            abstract = True

            def __str__(self):
            return self.description


            class Foods(Donation):
            pass

            class Drinks(Donation):
            pass

            class MiscObjects(Donation):
            pass


            # views.py
            from django.shortcuts import render, redirect, get_object_or_404
            from django.contrib.auth.decorators import login_required
            from users.models import *
            # or if User model is not overwritten: from django.contrib.auth.models import User
            from .models import *
            from .forms import *



            @login_required
            def vendorView(request):
            return render(request, 'inv/vendorInventory.html')

            @login_required
            def consumerView(request):
            return render(request, 'inv/consumerInventory.html')

            def unauthenticatedView(request):
            return render(request, 'inv/unauthenticatedInventory.html')
            ################ need to edit other views to render consumer/vendor/unauth

            def display_drinks(request):
            items = Drinks.objects.all()
            context = {
            'items': items,
            'header': 'Drinks',
            }

            if not request.user.is_authenticated:
            items = Drinks.objects.filter(status='AVAILABLE')
            context = {
            'items': items,
            'header': 'Drinks',
            }
            return render(request, 'inv/unauthenticatedInventory.html', context)

            elif request.user.profile.vendor:
            items = Drinks.objects.filter(donator__username=request.user.username)
            context = {
            'items': items,
            'header': 'Drinks',
            }
            return render(request, 'inv/vendorInventory.html', context)

            elif not request.user.profile.vendor:
            items = Drinks.objects.filter(status='AVAILABLE')
            context = {
            'items': items,
            'header': 'Drinks',
            }
            return render(request, 'inv/consumerInventory.html', context)


            This will work, BUT better to use class-based views here for example:
            official documentation: https://docs.djangoproject.com/en/dev/topics/class-based-views/



            from django.contrib.auth.mixins import LoginRequiredMixin
            from django.views.generic import TemplateView
            from django.views.generic.list import ListView

            # Better naming for model will be a "Drink" instead of "Drinks" (Django code style)
            from .models import Drinks


            class VendorView(LoginRequiredMixin, TemplateView):
            # better to use 'inv/vendor_inventory.html' naming style for PEP8 compatibility.
            template_name = 'inv/vendorInventory.html'


            class ConsumerView(LoginRequiredMixin, TemplateView):
            template_name = 'inv/consumerInventory.html'

            # Name for view, I think looks terrible ;)
            class UnauthenticatedView(TemplateView):
            template_name = 'inv/unauthenticatedInventory.html'


            class DrinksListView(ListView):
            model = Drinks
            context_object_name = 'items' # Variable in template, better to use something like: context_object_name = 'drinks'

            def get_queryset(self):
            if self.request.user.is_authenticated():
            return Drinks.objects.filter(status='AVAILABLE')
            elif self.request.user.profile.vendor:
            return Drinks.objects.filter(donator__username=self.request.user.username)
            # Better to use "else:" here instead of "elif" (for all other logic).
            elif not self.request.user.profile.vendor:
            return Drinks.objects.filter(status='AVAILABLE')


            Answers for questions from comments:



            If you want to add automatically user for every new Drinks object, you should do something like this:
            First of all, you should exclude field "donator" in your form:



            # forms.py
            class MyForm(forms.ModelForm):
            #.....
            class Meta:
            model = Drinks
            exclude = ('donator', )


            If you use function-based views:
            you should add something like this:



            # views.py
            if request.GET:
            form = MyForm()
            if request.POST:
            form = MyForm(request.POST)
            if form.is_valid():
            drinks = form.save(commit=False)
            drinks.donator = request.user
            drinks.save()
            return render(request, 'my_temlate.html', {'form': form})


            If you use class-based views: you should overwrite "post" method same way. You can find out more here, also there are examples: How do I use CreateView with a ModelForm






            share|improve this answer





















            • 1





              I have to totally disagree with the "better to use class-based views" part - unless you have a need for specialisation (which is actually not the most common case, by far), class-based-views only make simple things MUCH more complicated than they need to be. With all due respect to Django's authors, the decision to force-feed CBVs on users is IMHO one of the most misguided move they made...

              – bruno desthuilliers
              Jan 3 at 13:10











            • Thanks for the comment. First of all class-based views really make simple things much more complicated, because their main use-case is big projects and big parts of the code , so if you have a code base with 100k+ lines of code which was written using class-based views, it looks more readable and predictably than function-based views code. So function-based views good for simple logic, but in big projects better way will be to use class-based views IMHO.

              – om2c0de
              Jan 3 at 13:32











            • I've been using django since the first (0.9.something) public release, I've done literally dozens of (real-life, production) projects with it, the current one being near 500Kloc - is that "big" enough for you ? FWIW I do use CBVs when appropriate (notably for parts of this project - the parts where we do need specialisation). And I maintain that for most cases, CBVs are not only useless but also harmful wrt readability / maintainability. Now I won't go any further about this here (it's getting totally OT) but you can join me in private if you want to discuss this further

              – bruno desthuilliers
              Jan 3 at 13:40











            • @om2c0de, thanks for your help! I've applied the former code right now, and it comes back with no errors, however it does not assign the user's username as an attribute to the Drink object - it only allows for selection of a username from the tables I have.

              – studentprog
              Jan 3 at 20:42











            • Sounds great! I updated the answer, hope it will help you.

              – om2c0de
              Jan 4 at 11:51
















            1














            # models.py
            from django.db import models
            from users.models import *
            # or if User model is not overwritten: from django.contrib.auth.models import User


            class Donation(models.Model):
            choices = ( # for status
            ('AVAILABLE', 'Item ready to be picked up'),
            ('RESERVED', 'Item reserved'),
            )

            description = models.CharField(max_length=200, help_text='Describe your donation here')
            expiry = models.CharField(max_length=200, help_text="Enter expiration date here")
            status = models.CharField(max_length=10, choices=choices, default='AVAILABLE')
            misc = models.CharField(max_length=50, help_text='Miscellaneous info about your donation')
            donator = models.ForeignKey(User, on_delete=models.CASCADE)

            class Meta:
            abstract = True

            def __str__(self):
            return self.description


            class Foods(Donation):
            pass

            class Drinks(Donation):
            pass

            class MiscObjects(Donation):
            pass


            # views.py
            from django.shortcuts import render, redirect, get_object_or_404
            from django.contrib.auth.decorators import login_required
            from users.models import *
            # or if User model is not overwritten: from django.contrib.auth.models import User
            from .models import *
            from .forms import *



            @login_required
            def vendorView(request):
            return render(request, 'inv/vendorInventory.html')

            @login_required
            def consumerView(request):
            return render(request, 'inv/consumerInventory.html')

            def unauthenticatedView(request):
            return render(request, 'inv/unauthenticatedInventory.html')
            ################ need to edit other views to render consumer/vendor/unauth

            def display_drinks(request):
            items = Drinks.objects.all()
            context = {
            'items': items,
            'header': 'Drinks',
            }

            if not request.user.is_authenticated:
            items = Drinks.objects.filter(status='AVAILABLE')
            context = {
            'items': items,
            'header': 'Drinks',
            }
            return render(request, 'inv/unauthenticatedInventory.html', context)

            elif request.user.profile.vendor:
            items = Drinks.objects.filter(donator__username=request.user.username)
            context = {
            'items': items,
            'header': 'Drinks',
            }
            return render(request, 'inv/vendorInventory.html', context)

            elif not request.user.profile.vendor:
            items = Drinks.objects.filter(status='AVAILABLE')
            context = {
            'items': items,
            'header': 'Drinks',
            }
            return render(request, 'inv/consumerInventory.html', context)


            This will work, BUT better to use class-based views here for example:
            official documentation: https://docs.djangoproject.com/en/dev/topics/class-based-views/



            from django.contrib.auth.mixins import LoginRequiredMixin
            from django.views.generic import TemplateView
            from django.views.generic.list import ListView

            # Better naming for model will be a "Drink" instead of "Drinks" (Django code style)
            from .models import Drinks


            class VendorView(LoginRequiredMixin, TemplateView):
            # better to use 'inv/vendor_inventory.html' naming style for PEP8 compatibility.
            template_name = 'inv/vendorInventory.html'


            class ConsumerView(LoginRequiredMixin, TemplateView):
            template_name = 'inv/consumerInventory.html'

            # Name for view, I think looks terrible ;)
            class UnauthenticatedView(TemplateView):
            template_name = 'inv/unauthenticatedInventory.html'


            class DrinksListView(ListView):
            model = Drinks
            context_object_name = 'items' # Variable in template, better to use something like: context_object_name = 'drinks'

            def get_queryset(self):
            if self.request.user.is_authenticated():
            return Drinks.objects.filter(status='AVAILABLE')
            elif self.request.user.profile.vendor:
            return Drinks.objects.filter(donator__username=self.request.user.username)
            # Better to use "else:" here instead of "elif" (for all other logic).
            elif not self.request.user.profile.vendor:
            return Drinks.objects.filter(status='AVAILABLE')


            Answers for questions from comments:



            If you want to add automatically user for every new Drinks object, you should do something like this:
            First of all, you should exclude field "donator" in your form:



            # forms.py
            class MyForm(forms.ModelForm):
            #.....
            class Meta:
            model = Drinks
            exclude = ('donator', )


            If you use function-based views:
            you should add something like this:



            # views.py
            if request.GET:
            form = MyForm()
            if request.POST:
            form = MyForm(request.POST)
            if form.is_valid():
            drinks = form.save(commit=False)
            drinks.donator = request.user
            drinks.save()
            return render(request, 'my_temlate.html', {'form': form})


            If you use class-based views: you should overwrite "post" method same way. You can find out more here, also there are examples: How do I use CreateView with a ModelForm






            share|improve this answer





















            • 1





              I have to totally disagree with the "better to use class-based views" part - unless you have a need for specialisation (which is actually not the most common case, by far), class-based-views only make simple things MUCH more complicated than they need to be. With all due respect to Django's authors, the decision to force-feed CBVs on users is IMHO one of the most misguided move they made...

              – bruno desthuilliers
              Jan 3 at 13:10











            • Thanks for the comment. First of all class-based views really make simple things much more complicated, because their main use-case is big projects and big parts of the code , so if you have a code base with 100k+ lines of code which was written using class-based views, it looks more readable and predictably than function-based views code. So function-based views good for simple logic, but in big projects better way will be to use class-based views IMHO.

              – om2c0de
              Jan 3 at 13:32











            • I've been using django since the first (0.9.something) public release, I've done literally dozens of (real-life, production) projects with it, the current one being near 500Kloc - is that "big" enough for you ? FWIW I do use CBVs when appropriate (notably for parts of this project - the parts where we do need specialisation). And I maintain that for most cases, CBVs are not only useless but also harmful wrt readability / maintainability. Now I won't go any further about this here (it's getting totally OT) but you can join me in private if you want to discuss this further

              – bruno desthuilliers
              Jan 3 at 13:40











            • @om2c0de, thanks for your help! I've applied the former code right now, and it comes back with no errors, however it does not assign the user's username as an attribute to the Drink object - it only allows for selection of a username from the tables I have.

              – studentprog
              Jan 3 at 20:42











            • Sounds great! I updated the answer, hope it will help you.

              – om2c0de
              Jan 4 at 11:51














            1












            1








            1







            # models.py
            from django.db import models
            from users.models import *
            # or if User model is not overwritten: from django.contrib.auth.models import User


            class Donation(models.Model):
            choices = ( # for status
            ('AVAILABLE', 'Item ready to be picked up'),
            ('RESERVED', 'Item reserved'),
            )

            description = models.CharField(max_length=200, help_text='Describe your donation here')
            expiry = models.CharField(max_length=200, help_text="Enter expiration date here")
            status = models.CharField(max_length=10, choices=choices, default='AVAILABLE')
            misc = models.CharField(max_length=50, help_text='Miscellaneous info about your donation')
            donator = models.ForeignKey(User, on_delete=models.CASCADE)

            class Meta:
            abstract = True

            def __str__(self):
            return self.description


            class Foods(Donation):
            pass

            class Drinks(Donation):
            pass

            class MiscObjects(Donation):
            pass


            # views.py
            from django.shortcuts import render, redirect, get_object_or_404
            from django.contrib.auth.decorators import login_required
            from users.models import *
            # or if User model is not overwritten: from django.contrib.auth.models import User
            from .models import *
            from .forms import *



            @login_required
            def vendorView(request):
            return render(request, 'inv/vendorInventory.html')

            @login_required
            def consumerView(request):
            return render(request, 'inv/consumerInventory.html')

            def unauthenticatedView(request):
            return render(request, 'inv/unauthenticatedInventory.html')
            ################ need to edit other views to render consumer/vendor/unauth

            def display_drinks(request):
            items = Drinks.objects.all()
            context = {
            'items': items,
            'header': 'Drinks',
            }

            if not request.user.is_authenticated:
            items = Drinks.objects.filter(status='AVAILABLE')
            context = {
            'items': items,
            'header': 'Drinks',
            }
            return render(request, 'inv/unauthenticatedInventory.html', context)

            elif request.user.profile.vendor:
            items = Drinks.objects.filter(donator__username=request.user.username)
            context = {
            'items': items,
            'header': 'Drinks',
            }
            return render(request, 'inv/vendorInventory.html', context)

            elif not request.user.profile.vendor:
            items = Drinks.objects.filter(status='AVAILABLE')
            context = {
            'items': items,
            'header': 'Drinks',
            }
            return render(request, 'inv/consumerInventory.html', context)


            This will work, BUT better to use class-based views here for example:
            official documentation: https://docs.djangoproject.com/en/dev/topics/class-based-views/



            from django.contrib.auth.mixins import LoginRequiredMixin
            from django.views.generic import TemplateView
            from django.views.generic.list import ListView

            # Better naming for model will be a "Drink" instead of "Drinks" (Django code style)
            from .models import Drinks


            class VendorView(LoginRequiredMixin, TemplateView):
            # better to use 'inv/vendor_inventory.html' naming style for PEP8 compatibility.
            template_name = 'inv/vendorInventory.html'


            class ConsumerView(LoginRequiredMixin, TemplateView):
            template_name = 'inv/consumerInventory.html'

            # Name for view, I think looks terrible ;)
            class UnauthenticatedView(TemplateView):
            template_name = 'inv/unauthenticatedInventory.html'


            class DrinksListView(ListView):
            model = Drinks
            context_object_name = 'items' # Variable in template, better to use something like: context_object_name = 'drinks'

            def get_queryset(self):
            if self.request.user.is_authenticated():
            return Drinks.objects.filter(status='AVAILABLE')
            elif self.request.user.profile.vendor:
            return Drinks.objects.filter(donator__username=self.request.user.username)
            # Better to use "else:" here instead of "elif" (for all other logic).
            elif not self.request.user.profile.vendor:
            return Drinks.objects.filter(status='AVAILABLE')


            Answers for questions from comments:



            If you want to add automatically user for every new Drinks object, you should do something like this:
            First of all, you should exclude field "donator" in your form:



            # forms.py
            class MyForm(forms.ModelForm):
            #.....
            class Meta:
            model = Drinks
            exclude = ('donator', )


            If you use function-based views:
            you should add something like this:



            # views.py
            if request.GET:
            form = MyForm()
            if request.POST:
            form = MyForm(request.POST)
            if form.is_valid():
            drinks = form.save(commit=False)
            drinks.donator = request.user
            drinks.save()
            return render(request, 'my_temlate.html', {'form': form})


            If you use class-based views: you should overwrite "post" method same way. You can find out more here, also there are examples: How do I use CreateView with a ModelForm






            share|improve this answer















            # models.py
            from django.db import models
            from users.models import *
            # or if User model is not overwritten: from django.contrib.auth.models import User


            class Donation(models.Model):
            choices = ( # for status
            ('AVAILABLE', 'Item ready to be picked up'),
            ('RESERVED', 'Item reserved'),
            )

            description = models.CharField(max_length=200, help_text='Describe your donation here')
            expiry = models.CharField(max_length=200, help_text="Enter expiration date here")
            status = models.CharField(max_length=10, choices=choices, default='AVAILABLE')
            misc = models.CharField(max_length=50, help_text='Miscellaneous info about your donation')
            donator = models.ForeignKey(User, on_delete=models.CASCADE)

            class Meta:
            abstract = True

            def __str__(self):
            return self.description


            class Foods(Donation):
            pass

            class Drinks(Donation):
            pass

            class MiscObjects(Donation):
            pass


            # views.py
            from django.shortcuts import render, redirect, get_object_or_404
            from django.contrib.auth.decorators import login_required
            from users.models import *
            # or if User model is not overwritten: from django.contrib.auth.models import User
            from .models import *
            from .forms import *



            @login_required
            def vendorView(request):
            return render(request, 'inv/vendorInventory.html')

            @login_required
            def consumerView(request):
            return render(request, 'inv/consumerInventory.html')

            def unauthenticatedView(request):
            return render(request, 'inv/unauthenticatedInventory.html')
            ################ need to edit other views to render consumer/vendor/unauth

            def display_drinks(request):
            items = Drinks.objects.all()
            context = {
            'items': items,
            'header': 'Drinks',
            }

            if not request.user.is_authenticated:
            items = Drinks.objects.filter(status='AVAILABLE')
            context = {
            'items': items,
            'header': 'Drinks',
            }
            return render(request, 'inv/unauthenticatedInventory.html', context)

            elif request.user.profile.vendor:
            items = Drinks.objects.filter(donator__username=request.user.username)
            context = {
            'items': items,
            'header': 'Drinks',
            }
            return render(request, 'inv/vendorInventory.html', context)

            elif not request.user.profile.vendor:
            items = Drinks.objects.filter(status='AVAILABLE')
            context = {
            'items': items,
            'header': 'Drinks',
            }
            return render(request, 'inv/consumerInventory.html', context)


            This will work, BUT better to use class-based views here for example:
            official documentation: https://docs.djangoproject.com/en/dev/topics/class-based-views/



            from django.contrib.auth.mixins import LoginRequiredMixin
            from django.views.generic import TemplateView
            from django.views.generic.list import ListView

            # Better naming for model will be a "Drink" instead of "Drinks" (Django code style)
            from .models import Drinks


            class VendorView(LoginRequiredMixin, TemplateView):
            # better to use 'inv/vendor_inventory.html' naming style for PEP8 compatibility.
            template_name = 'inv/vendorInventory.html'


            class ConsumerView(LoginRequiredMixin, TemplateView):
            template_name = 'inv/consumerInventory.html'

            # Name for view, I think looks terrible ;)
            class UnauthenticatedView(TemplateView):
            template_name = 'inv/unauthenticatedInventory.html'


            class DrinksListView(ListView):
            model = Drinks
            context_object_name = 'items' # Variable in template, better to use something like: context_object_name = 'drinks'

            def get_queryset(self):
            if self.request.user.is_authenticated():
            return Drinks.objects.filter(status='AVAILABLE')
            elif self.request.user.profile.vendor:
            return Drinks.objects.filter(donator__username=self.request.user.username)
            # Better to use "else:" here instead of "elif" (for all other logic).
            elif not self.request.user.profile.vendor:
            return Drinks.objects.filter(status='AVAILABLE')


            Answers for questions from comments:



            If you want to add automatically user for every new Drinks object, you should do something like this:
            First of all, you should exclude field "donator" in your form:



            # forms.py
            class MyForm(forms.ModelForm):
            #.....
            class Meta:
            model = Drinks
            exclude = ('donator', )


            If you use function-based views:
            you should add something like this:



            # views.py
            if request.GET:
            form = MyForm()
            if request.POST:
            form = MyForm(request.POST)
            if form.is_valid():
            drinks = form.save(commit=False)
            drinks.donator = request.user
            drinks.save()
            return render(request, 'my_temlate.html', {'form': form})


            If you use class-based views: you should overwrite "post" method same way. You can find out more here, also there are examples: How do I use CreateView with a ModelForm







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Jan 4 at 11:49

























            answered Jan 3 at 12:43









            om2c0deom2c0de

            38139




            38139








            • 1





              I have to totally disagree with the "better to use class-based views" part - unless you have a need for specialisation (which is actually not the most common case, by far), class-based-views only make simple things MUCH more complicated than they need to be. With all due respect to Django's authors, the decision to force-feed CBVs on users is IMHO one of the most misguided move they made...

              – bruno desthuilliers
              Jan 3 at 13:10











            • Thanks for the comment. First of all class-based views really make simple things much more complicated, because their main use-case is big projects and big parts of the code , so if you have a code base with 100k+ lines of code which was written using class-based views, it looks more readable and predictably than function-based views code. So function-based views good for simple logic, but in big projects better way will be to use class-based views IMHO.

              – om2c0de
              Jan 3 at 13:32











            • I've been using django since the first (0.9.something) public release, I've done literally dozens of (real-life, production) projects with it, the current one being near 500Kloc - is that "big" enough for you ? FWIW I do use CBVs when appropriate (notably for parts of this project - the parts where we do need specialisation). And I maintain that for most cases, CBVs are not only useless but also harmful wrt readability / maintainability. Now I won't go any further about this here (it's getting totally OT) but you can join me in private if you want to discuss this further

              – bruno desthuilliers
              Jan 3 at 13:40











            • @om2c0de, thanks for your help! I've applied the former code right now, and it comes back with no errors, however it does not assign the user's username as an attribute to the Drink object - it only allows for selection of a username from the tables I have.

              – studentprog
              Jan 3 at 20:42











            • Sounds great! I updated the answer, hope it will help you.

              – om2c0de
              Jan 4 at 11:51














            • 1





              I have to totally disagree with the "better to use class-based views" part - unless you have a need for specialisation (which is actually not the most common case, by far), class-based-views only make simple things MUCH more complicated than they need to be. With all due respect to Django's authors, the decision to force-feed CBVs on users is IMHO one of the most misguided move they made...

              – bruno desthuilliers
              Jan 3 at 13:10











            • Thanks for the comment. First of all class-based views really make simple things much more complicated, because their main use-case is big projects and big parts of the code , so if you have a code base with 100k+ lines of code which was written using class-based views, it looks more readable and predictably than function-based views code. So function-based views good for simple logic, but in big projects better way will be to use class-based views IMHO.

              – om2c0de
              Jan 3 at 13:32











            • I've been using django since the first (0.9.something) public release, I've done literally dozens of (real-life, production) projects with it, the current one being near 500Kloc - is that "big" enough for you ? FWIW I do use CBVs when appropriate (notably for parts of this project - the parts where we do need specialisation). And I maintain that for most cases, CBVs are not only useless but also harmful wrt readability / maintainability. Now I won't go any further about this here (it's getting totally OT) but you can join me in private if you want to discuss this further

              – bruno desthuilliers
              Jan 3 at 13:40











            • @om2c0de, thanks for your help! I've applied the former code right now, and it comes back with no errors, however it does not assign the user's username as an attribute to the Drink object - it only allows for selection of a username from the tables I have.

              – studentprog
              Jan 3 at 20:42











            • Sounds great! I updated the answer, hope it will help you.

              – om2c0de
              Jan 4 at 11:51








            1




            1





            I have to totally disagree with the "better to use class-based views" part - unless you have a need for specialisation (which is actually not the most common case, by far), class-based-views only make simple things MUCH more complicated than they need to be. With all due respect to Django's authors, the decision to force-feed CBVs on users is IMHO one of the most misguided move they made...

            – bruno desthuilliers
            Jan 3 at 13:10





            I have to totally disagree with the "better to use class-based views" part - unless you have a need for specialisation (which is actually not the most common case, by far), class-based-views only make simple things MUCH more complicated than they need to be. With all due respect to Django's authors, the decision to force-feed CBVs on users is IMHO one of the most misguided move they made...

            – bruno desthuilliers
            Jan 3 at 13:10













            Thanks for the comment. First of all class-based views really make simple things much more complicated, because their main use-case is big projects and big parts of the code , so if you have a code base with 100k+ lines of code which was written using class-based views, it looks more readable and predictably than function-based views code. So function-based views good for simple logic, but in big projects better way will be to use class-based views IMHO.

            – om2c0de
            Jan 3 at 13:32





            Thanks for the comment. First of all class-based views really make simple things much more complicated, because their main use-case is big projects and big parts of the code , so if you have a code base with 100k+ lines of code which was written using class-based views, it looks more readable and predictably than function-based views code. So function-based views good for simple logic, but in big projects better way will be to use class-based views IMHO.

            – om2c0de
            Jan 3 at 13:32













            I've been using django since the first (0.9.something) public release, I've done literally dozens of (real-life, production) projects with it, the current one being near 500Kloc - is that "big" enough for you ? FWIW I do use CBVs when appropriate (notably for parts of this project - the parts where we do need specialisation). And I maintain that for most cases, CBVs are not only useless but also harmful wrt readability / maintainability. Now I won't go any further about this here (it's getting totally OT) but you can join me in private if you want to discuss this further

            – bruno desthuilliers
            Jan 3 at 13:40





            I've been using django since the first (0.9.something) public release, I've done literally dozens of (real-life, production) projects with it, the current one being near 500Kloc - is that "big" enough for you ? FWIW I do use CBVs when appropriate (notably for parts of this project - the parts where we do need specialisation). And I maintain that for most cases, CBVs are not only useless but also harmful wrt readability / maintainability. Now I won't go any further about this here (it's getting totally OT) but you can join me in private if you want to discuss this further

            – bruno desthuilliers
            Jan 3 at 13:40













            @om2c0de, thanks for your help! I've applied the former code right now, and it comes back with no errors, however it does not assign the user's username as an attribute to the Drink object - it only allows for selection of a username from the tables I have.

            – studentprog
            Jan 3 at 20:42





            @om2c0de, thanks for your help! I've applied the former code right now, and it comes back with no errors, however it does not assign the user's username as an attribute to the Drink object - it only allows for selection of a username from the tables I have.

            – studentprog
            Jan 3 at 20:42













            Sounds great! I updated the answer, hope it will help you.

            – om2c0de
            Jan 4 at 11:51





            Sounds great! I updated the answer, hope it will help you.

            – om2c0de
            Jan 4 at 11:51


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54021458%2fdjango-queryset-filtering-not-working-with-views-showing-blank-view-even-though%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Monofisismo

            Angular Downloading a file using contenturl with Basic Authentication

            Olmecas