Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
queryset empty when iterating it
I have a strange error, I have a queryset which apparently have items In [13]: Product.objects.all() Out[13]: <QuerySet [.... In [14]: Product.objects.all().count() Out[14]: 77 But looks like its really empty? In [15]: [p for p in Product.objects.all()] Out[15]: [] I was using it on a rest api view, and noticed it when it was returning empty products but the database has products: class ProductList(generics.ListAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer permission_classes = [ permissions.AllowAny, ] filter_backends = (filters.DjangoFilterBackend,) -
Django ImageField keep original Image ratio while processing
at my models.py i got a class named Post with and ImageField called postcover. I want to save every image in PNG format which is working fine so far but i have no idea how i could keep the actual image aspectio ratio after processing the image because currently i staticaly convert it into 4:3 format ratio while saveing it as 500 by 375 pixels. def save(self, *args, **kwargs): super(Post, self).save(*args, **kwargs) if self.postcover: if os.path.exists(self.postcover.path): imageTemproary = Image.open(self.postcover) outputIoStream = BytesIO() imageTemproaryResized = imageTemproary.resize((500, 375)) imageTemproaryResized.save(outputIoStream, format='PNG') outputIoStream.seek(0) self.postcover = InMemoryUploadedFile(outputIoStream, 'ImageField', "%s.png" % self.postcover.name.split('.')[0], 'image/png', sys.getsizeof(outputIoStream), None) super(Post, self).save(*args, **kwargs) is there any way how i could set a max width and height while i keep the format? -
How to get data from forms?
I have the following view def get_context_data(self, *args, **kwargs): ctx=super(ProductsCreate, self).get_context_data(*args, **kwargs) ctx['special_form'] = SpeciallyPriceForm() return ctx def get(self, request, *args, **kwargs): self.object = None if kwargs.get('slug'): category = Category.objects.filter(slug=kwargs.get('slug')).first() self.initial.update({'category': category}) return self.render_to_response(self.get_context_data()) def post(self, request, *args, **kwargs): self.object = None form = self.get_form() special_form = SpeciallyPriceForm(self.request.POST) print(special_form) if form.is_valid() and special_form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) forms def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') user = self.request.user provider = Provider.objects.filter(user=user.id).last() self.fields['category'] = ModelMultipleChoiceField(queryset=provider.category.all()) def clean(self): cleaned_data = super(ProductCreateForm, self).clean() cd_category = cleaned_data.get('category') How can I get data from a form (ProductCreateForm)? If I write form = self.get_form(), then I just get a form template, where some data is selected, and some are not (select especially). If I write form = ProductCreateForm(request.POST), then I get an error saying that the request was not found. Perhaps this is due to the fact that I set the request in get_context_data() and work with them in the __init__ method in the forms.py. I process the data in the clean method in the forms.py. -
Is there a way to have both CAS and normal login system in django admin?
I've integrated my django admin application with django-cas-ng. Everything works fine, but after entering the page, django automatically redirects me to the CAS - as it should be doing anyway. However, I would like to have two auth systems - CAS and django. In short, it would be nice if user had a choice. I was thinking about creating another page where user would choose login system (this page would be placed between django login and CAS), but as far as i know it's impossible since admin site points to ' ' and automatically redirects to 'accounts/login' - any change in this mappings would break the system: urlpatterns = [ path('', admin.site.urls), path('accounts/login', django_cas_ng.views.login, name='cas_ng_login'), path('accounts/logout', django_cas_ng.views.logout, name='cas_ng_logout'), path('accounts/callback', django_cas_ng.views.callback, name='cas_ng_proxy_callback'), ] So, is there any recommended way to achieve this? I was thinking about overriding an AdminSite, but I believe this is not good practice. Any help would be highly appreciated! -
How to access Django Model field value?
The following html code fails to switch between "Bookmark" and "Unbookmarked" if there is more than 1 video being bookmarked with the same user. How can I changed the following if loop to check if this specific user has bookmarked this specific video rather than a user having a bookmarked video in general ? <td> <form method='POST' action="{% url 'view:favourite' details.id %}"> {% csrf_token %} <input type='hidden'> {% if user.fav_videos.exists %} <button type='submit'>UnBookmark</button> {% else %} <button type='submit'>Bookmark</button> {% endif %} </form> </td> -
I am trying to take user input values to display on my chart.js
i am trying to take user input from the front end html and save it to a variable and pass that value into the chart.js to display those values in the form of a chart but i am not able to do it i feel the data is being stored in the variable but it is not showing the output some times it says post method not allowed please help i am trying to sace the value in the variable text and its not happening views.py class HomeView(View): def get(self, request, *args, **kwargs): form = Homeform() return render(request, 'chart.html', {'form': form}) class ChartData(APIView): authentication_classes = [] permission_classes = [] def post(self, request): form = Homeform(request.POST) if form.is_valid(): text = form.cleaned_data['post'] user_count = User.objects.all().count() amount = [user_count, text, 6, 2, 1] lables = ["users", "fruits", "tot", "dtot", "one"] data = { "lables": lables, "default": amount, } return Response(data) -
Editing data without removing previously added. Django using 'forms.Form'
How can I edit data without deleting what has been added before. In my situation, I want to use forms.Form which looks like this class SecondForm(forms.Form): data_1 = forms.ChoiceField(choices=CHOICES, label="") data_2 = forms.ChoiceField(choices=CHOICES, label="") data_3 = forms.ChoiceField(choices=CHOICES, label="") In my views.py id = #some object number if request.method =="POST": second_form = SecondForm(request.POST) if second_form.is_valid(): cd = second_form.cleaned_data object = Valuation(pk=object_id) object.data_1 = cd['data_1'] object.data_2 = cd['data_2'] object.data_3 = cd['data_3'] object.save() return HttpResponseRedirect(reverse('app:valuation_third', args=[forwarding])) else: second_form = SecondForm() In this situation, if my model looks like this: class Valuation(models.Model): data_added_before = models.CharField() data_1 = models.CharField() data_2 = models.CharField() data_3 = models.CharField() Every time a field 'data_added_before' it's cleaned. How to avoid it. So that the information added earlier in this field has been preserved. And new data from the current form added to existing ones. Any help will be appreciated. -
Combining filter and exlude in Django query on related objects gives empty results
I want to do the following query in Django to find car objects that don't exist in manufacturers table and have a specific country code: ids = Cars.objects.all() Cars.objects.filter(group__manufacturer__country=123).exclude(group__manufacturer__id__in=ids) Unfortunately this gives me an empty query result. But executing the filter and exclude query alone gives non empty results where some of the objects are the same (i.e. fullfill both conditions). Therefore I'm wondering how to combine the queries to get the correct subset. I also tried using Djangos Q objects but unfortunately with the same results. If possible I would want to avoid using raw sql. -
Django file object is closing when it moves out of function scope - Python3
I have a below django view from io import TextIOWrapper def get_header_data(file_obj): # perform some operations like text_file = TextIOWrapper(file_obj) reader = csv.reader(text_file) ..... ..... file_obj.seek(0) print(file_obj.closed, "--> Inside get_header_data method") return some_data def upload(request): file_obj = request.FILES["file"] print(file_obj.closed, "--> Inside upload before entering in to get_header_data method") # Get some headers header_data = get_header_data(file_obj) # Facing an error at this point file_obj.seek(0) print(file_obj.closed, "--> Inside upload after returned from get_header_data method") file_obj.seek(0) Output: False--> Inside upload before entering in to get_header_data method False--> Inside get_header_data method True--> Inside upload after returned from get_header_data method ValueError: I/O operation on closed file at line 5 (file_obj.seek(0)) inside upload method The problem here is, in case of python3, the file_obj which I sent to get_header_data from upload method is getting closed by python when the interpreter moved out of upload function(when it got returned). The same code is working fine in Python 2.7, so what could be the problem here and why the file_obj is getting closed when the interpreter moved out of get_header_data method -
Django Model Enumerations
models.py: class enumerations(models.Model): Description = models.CharField(max_length=80) Field = models.CharField(max_length=80) Parent = models.IntegerField(help_text='ID des Vater von diesem Eintrag') class A(models.Model): Field1 = models.Foreignkey(enumerations,on_delete=models.CASCADE, null=True,) Field2 = models.Foreignkey(enumerations,on_delete=models.CASCADE, null=True,) Field3 = models.CharField(max_length=80) now i have in enumerations datasets: 1. Description="Enum1", Field="Field1", Parent= "0" 2. Description="Enum2", Field="Field1", Parent= "0" 3. Description="Enum1", Field="Field2", Parent= "0" Now i want in my HTML Template all Entrys from class A and 2 Select Fields form Field1 and Field 2 with the Description. How can i do that? Regards -
How to create a drop down to filter rows in specific columns
I have a table with over 600 rows of data. The columns headers for this table are Name, Office, Address, Primary_Role, Secondary_Role, Other_Role. I would like to create a drop down within my HTML that will have each unique role as an option and will filter through Primary_Role, Secondary_Role and Other_Role. So far I have created a drop down with each unique role as an option but I am not sure how to go about connecting it to the table so that I may get the desired outcome once an option is chosen. HTML Code <select class="filter" data-col="0"> <option value="">None</option> <option value="Assistant">Assistant</option> <option value="2">Associate</option> <option value="3">Compliance Officer for Finance and Administration</option> <option value="4">Compliance Officer for Legal Practice</option> <option value="5">Consultant</option> <option value="6">Designated Partner</option> <option value="7">Director</option> <option value="8">Employee</option> <option value="9">In-house Solicitor</option> <option value="10">Locum</option> <option value="11">Member</option> <option value="12">Non-member Partner</option> <option value="13">Partner</option> <option value="14">Professional Support Lawyer</option> <option value="15">Prosecutor</option> <option value="16">Role not specified</option> <option value="17">SRA-approved manager - Director</option> <option value="18">SRA-approved manager - Member</option> <option value="19">SRA-approved manager - Partner</option> <option value="20">SRA-approved manager - Sole Practitioner</option> </select> <table class="table table-striped" style='width:150%'> <thead> <tr> <th>Solicitor</th> <th>Office</th> <th>Address</th> <th>Primary_Role</th> <th>Secondary_Role</th> <th>Other_Role</th> </tr> </thead> <tbody id="tls_table"> <tr> {% block content %} {% endblock %} </tr> </tbody> </table> </div> -
How to get revision dates for first and last update for multiple objects?
I need to make a bulk query for all instances of SomeModel, annotating them with the date of their creation and last update. Here's what I tried and is terribly slow: query = SomeModel.objects.all() for entry in query: last_updated_date = entry.details.history.last().history_date created_date = entry.details.history.first().history_date csv_writer.writerow([entry.name, last_updated_date, created_date]) How could I optimize the code? I imagine that the problem is that I'm making a lot of SELECT queries, when probably a single bit more complex one would do. -
Django custom FileSystemStorage works in development server but not in Apache server
I have a customized a FileSystemStorage class to allow overwriting existent uploaded files in a subfolder of MEDIA_ROOT when files are uploaded via the admin change interface. However, it works fine in Django development server but in Apache no file is created when the user uploads a file and no errors are reported (neither in Apache error.log or by the Django logging system). The corresponding server folder and sub-folders have the appropriate R/W permissions for both the www-data user and group. Here is the code: class MyFileStorage(FileSystemStorage): def get_available_name(self, name, max_length=None): #pudb.set_trace() return name def _save(self, name, content): full_path = self.path(name) # Create any intermediate directories that do not exist. directory = os.path.dirname(full_path) logger = logging.getLogger('fileupload') if not os.path.exists(directory): try: if self.directory_permissions_mode is not None: # os.makedirs applies the global umask, so we reset it, # for consistency with file_permissions_mode behavior. old_umask = os.umask(0) try: os.makedirs(directory, self.directory_permissions_mode) finally: os.umask(old_umask) else: logger.debug("MyFileStorage::_save: Trying to create directory: %s" % (directory,)) os.makedirs(directory) except FileNotFoundError: # There's a race between os.path.exists() and os.makedirs(). # If os.makedirs() fails with FileNotFoundError, the directory # was created concurrently. pass # If the file already exists we delete it, so we can re-upload a file # with the … -
Django Symmetric Many-to-Many In Both Tables
One thing I found frustrating in Django is the seemingly required asymmetry when defining many-to-many relationships. I teach Django and would really like to find the "most elegant" way to describe and teach many-to-many relationships in Django. One of my students used the technique of putting the class name in as a string in making her many-to-many model. This allows her to avoid less-than-intuitive techniques like related-name. This is my simplified version of her model - the key is that Person and Course are strings, not class names. class Person(models.Model): email = models.CharField(max_length=128, unique=True) courses = models.ManyToManyField('Course', through='Membership') class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.CASCADE) class Course(models.Model): title = models.CharField(max_length=128, unique=True) members = models.ManyToManyField('Person', through='Membership') But while this looks pretty to me, I am concerned that I have messed things up. I have done some basic testing and see no downsides to this style of model definition, but I am concerned that I messed something up that I don't even understand. So I submit this as a question, "What is wrong with this picture?" -
can i create a chrome extension in django or flasks if yes send me some reference or answer with some examples
I want to create a chrome extension in django or flask which can save some important text and display it on the same page with all previous entered text .I have created it in javascript but i didnt know how to create it in these frameworks.Please answer it with some examples. -
Django:The value of id is coming None when adding new profile
I have the below models: class Profile(models.Model): date = models.DateTimeField(auto_now_add=True) full_name = models.CharField(max_length=32,blank=True) name = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) e_mail = models.EmailField(max_length=70,blank=True) permanant_address = models.TextField(blank=True) subscribed_products = models.ManyToManyField(Product,related_name='products_subscribed',blank=True) The profile is created by the below signal: @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(name=instance) When I add a new user it doesnot creates a new profile and when I try to add profile manually the value of the primary key field is coming None.. Can anyone tell me what is wrong? Thank you -
Change language in automaticlly generated by Django-bootstrap 4 buttons in formset
Hello Does anyone know how to change language in automaticlly generated by Django-bootstrap 4 buttons in formset from Russian to English? I dont know where Django-bootstrap 4 gets language information. I read the documentation fully and there nothing about this. project langage settings as bellow: LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Europe/Moscow' USE_I18N = True USE_L10N = True USE_TZ = True SHORT_DATE_FORMAT = "j.m.Y" # i have tried to change USE_I18N = True USE_L10N = True to False - no difference tenplate code: <div class="form-container container col-md-6 bg-light"> <div class="row"> <div class="col-md-12"> <h1 class="form__section-title">{{ title }}</h1> </div> <div class="col-md-12"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {% bootstrap_form form1 layout='inline' size="small" label_class="form-label col-md-3"%} {% bootstrap_formset form2 layout='horizontal' size="small" label_class="form-label col-md-3"%} <div class="row"> <div class="col-12 text-center"> {% buttons %} <button type="submit" class="form-button btn btn-light"> Submit </button> <button type="reset" class="form-button btn btn-light"> Reset </button> {% endbuttons %} </div> </div> </form> </div> </div> </div> -
operational error in django database connection
I have setup the mysql database in django. but i am getting the operational error such as unknown database. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', #'ENGINE': 'mysql.connector.django', 'NAME': os.path.join(BASE_DIR, 'dbname'), 'USER':'root', 'PASSWORD':'********' } } But it throws following error: OperationalError: (1049, "Unknown database 'c:\users\brahmareddy\desktop\djangotable\checkingapp\dbname'") -
Sentry vs MANAGERS and ADMINS in Django, what's the correct setup?
I'm using Sentry to collect exceptions from my Django application. Recently I learned about the ADMINS and MANAGERS setting for Django, so, I added them to my settings.py. I don't want to miss anything going wrong in my server. Adding them had an unintended consequence, as far as I can see: some exceptions go to Sentry, but some go to the admins (or managers*). To get those exceptions back in Sentry, I need to make ADMINS blank again. Is this the correct setup? Are there any notifications I would lose by having ADMINS blank? Is it possible to set ADMINS and have Sentry still be used to report all notifications? * I'm not sure because I set them to the same value. -
Why do I have the issue 'property assigment expected' when I want to display a chart on my web page using highcharts
I have an issue when I want to display a chart on my web page using django and highcharts. This is my detail.html file. I have an error called property assignment expected on the side of my curly brackets here : _dateList={{dateList|safe}}; _price={{price.room.actual_rate.amount}}; _availability={{availability}}; Here is the all file <h1>{{property.name}}</h1> <h2>{{roomtype.name}}</h2> <div id="container"></div> <script src="https://code.highcharts.com/highcharts.js"></script> <script src="https://code.highcharts.com/modules/series-label.js"></script> <script src="https://code.highcharts.com/modules/exporting.js"></script> <script src="https://code.highcharts.com/modules/export-data.js"></script> <script> _dateList={{dateList|safe}}; _price={{price.room.actual_rate.amount}}; _availability={{availability}}; Highcharts.chart('container', { title: { text: 'Pricing model prevision' }, xAxis: { categories: _dateList }, yAxis: [{ title: { text: 'Price', style: { color: Highcharts.getOptions().colors[2] } }, labels: { style: { color: Highcharts.getOptions().colors[2] } } }, { title:{ text:'Occupancy', style:{ color: Highcharts.getOptions().colors[0] } }, labels:{ style:{ color: Highcharts.getOptions().colors[0] } }, opposite: true }], legend: { layout: 'vertical', align: 'right', verticalAlign: 'middle' }, plotOptions: { series: { label: { connectorAllowed: false }, pointStart: 2010 } }, series: [{ name: 'price', data: _price }, { name: 'availabilty', data: _availability }], responsive: { rules: [{ condition: { maxWidth: 500 }, chartOptions: { legend: { layout: 'horizontal', align: 'center', verticalAlign: 'bottom' } } }] } }); </script> <ul> {% for day in dayList %} {% if day.availability.room %} <li>{{day.date}}:{{day.allotment}}:{{day.pricing.room.actual_rate.amount}} </li> {% else %} <li>{{day.date}}:0 </li> {% endif %} {% endfor … -
Return related_instance for elasticsearch
I have a model named Book and Author,Location, UserReadHistory as related_models. My models.py goes like this, class Author(TimeStamp): author = models.CharField(max_length=100, null=True, blank=True) location = models.ForeignKey(Location,on_delete=models.CASCADE,null=True,blank=True) def __unicode__(self): return "Author details: {}" .format(self.title) class Location (TimeStamp): """Book model defined location = models.CharField(max_length=100,null=True,blank=True) coordinate = models.IntegerField(null=True,blank=True) class Book(TimeStamp): """Book model defined here""" title = models.CharField(max_length=100,null=True,blank=True) isbn = models.CharField(max_length=100,null=True,blank=True) category = models.CharField(max_length=100,null=True,blank=True) language = models.CharField(max_length=100,null=True,blank=True) price = models.IntegerField(null=True,blank=True) author = models.ForeignKey(Author,on_delete=models.CASCADE,null=True,blank=True) my documents.py is like, @book.doc_type class BookDocument(DocType): #connecting book and author where author is foreign key of book author = fields.ObjectField(properties={ 'author': fields.StringField(), 'country':fields.StringField() }) class Meta: model = Book related_models = [Author,Location] fields = ['title', 'isbn', 'category', 'language','price'] def get_instances_from_related(self, related_instance): if isinstance(related_instance, Author): return related_instance.author_set.all() elif isinstance(related_instance, Location): return related_instance.location_set.all() So when i try to update Author i am getting error, 'Author' object has no attribute 'author_set' How should i write my return statement such that it will updte my elasticsearch -
django chain list objects filter
I merged the base models and then filtered it but got it error My first language is not English my browser AttributeError at /search 'list' object has no attribute 'filter' Request Method: GET Request URL: http://127.0.0.1:8000/search?category=1&submit=%D9%BE%DB%8C%D8%AF%D8%A7+%DA%A9%D9%86%21 Django Version: 2.1.7 Exception Type: AttributeError Exception Value: 'list' object has no attribute 'filter' Exception Location: /Users/sammahdavian/Desktop/prg/djangotest/OurTripsTour/PR_ott/app_search/views.py in search, line 25 Python Executable: /Users/sammahdavian/.virtualenvs/PR_ott/bin/python Python Version: 3.7.2 views.py from django.shortcuts import render from app_adventure.models import * from app_cultural.models import * from app_children.models import * from app_base.choices import Tour_type_choices, Destination_choices, Day_choices, Month_choices from itertools import chain # Create your views here. # search def search(request): adventure = AdventureTor.objects.all() cultural = CulturalTor.objects.all() children = ChildTor.objects.all() queryset_list = list(chain(adventure, cultural, children)) # search by category if 'category' in request.GET: category = request.GET['category'] if category: queryset_list = queryset_list.filter(category__icontains=category) # mitonest iexact bashe context = { 'Tour_type_choices': Tour_type_choices, 'Destination_choices': Destination_choices, 'Day_choices': Day_choices, 'Month_choices': Month_choices, 'search': queryset_list, } return render(request, 'search/search.html', context) I want to collect all the models of all my applications and then filter them -
Advice on managing database table triggers when using django model save
We have a legacy SQL Server based database that has triggers set to update created_by, created_on, modified_by and modified_on columns when a row is created and if it is later modified. Default values are set for the created* columns and triggers have been setup for the modified* columns. This has been done to manage creation and update events occurring via different front-ends and even via SQL Server Tool Sets (SSMS) should that occur. I am now building an internal Django based front-end application over some of these tables and am initially using the Django Admin Interface for CRUD based activities over these tables. The issue I have come across is that since the Django Web App is connecting to the database using a Windows Service Account with database privledges the ModifiedBy Trigger is using that servicce user account rather than the WebApp End-User account to identify 'who' has updated a row. I understand why. But would like to know if anyone has been able to somehow force the trigger to use the originating webapp end-user rather than the account used to establish the connection from within Django? The setup is a Windows environment with Apache providing the web hosting for … -
Humanize not working for floats in template
I'm working on a Django APP that has LANGUAGE_CODE set to es for Spanish. I'm trying to format how the numbers are rendered in the templates. Right now they're rendered like:S/ 18,00 when S/ 18.00 is needed. I've search and found this other related question: Format numbers in django templates But after applying Humanize, I'm not getting the desired result: template.html: {% load humanize %} <p>El total de su pedido es: S/ {{ total|intcomma }}</p> #renders S/ 18,00 settings.py: # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'shop', 'django.contrib.humanize', ] I've also tried these other solutions: 1) <p>El total de su pedido es: S/ {{ total|floatformat:'2' }}</p> Doesn't work, renders: S/ 18,00 when S/ 18.00 is needed. 2) <p>El total de su pedido es: S/ {{ total|stringformat:"f" }}</p> Works but uses more than 2 decimals: S/ 18.00000000 when S/ 18.00 is needed. 3) <p>El total de su pedido es: S/ {{ total|stringformat:"2f" }}</p> This does not work, also returns: S/ 18.00000000 when S/ 18.00 is needed. models.py: class Order(models.Model): token = models.CharField(max_length=100, blank=True, null=True) first_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) total = models.DecimalField(max_digits=10, decimal_places=2) views.py def thanks_deposit_payment(request): order_number = Order.objects.latest('id').id total = … -
How to create a fixture containing a GenericRelation?
I'm trying to create a fixture for my test cases. However, I keep getting an error when I run python manage.py test and python manage.py loaddata: TypeError: Problem installing fixture ... 'GenericRelatedObjectManager' object is not iterable I've used exclude to remove the contenttypes when creating the json file, but I still run into this error. python manage.py dumpdata --exclude=contenttypes --exclude=auth --natural-foreign --natural-primary --format=json --indent=4 > website/fixtures/website.json Going through the traceback, the error occurs at: File "C:\Users\Name\Anaconda3\lib\site-packages\django\contrib\contenttypes\fields.py", line 614, in set objs = tuple(objs) It was trying to iterate through a field called 'favorite' which has a generic relationship. The data stored the following 'favorite':<django.contrib.contenttypes.fields.create_generic_related_manager.<locals>.GenericRelatedObjectManager object at 0x000001C758C25470> Here are my models: class Activity(models.Model): FAVORITE = 'F' ACTIVITY_TYPES = ( (FAVORITE, 'Favorite'), ) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) activity_type = models.CharField(max_length=1, choices=ACTIVITY_TYPES) date = models.DateTimeField(auto_now_add=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() def __str__(self): return self.activity_type class Page(models.Model): #need to see how to use pk of user already signed in user = models.ForeignKey(CustomUser , on_delete=models.CASCADE) name = models.CharField(max_length=100) description = models.TextField(blank=False, null=False) favorite = GenericRelation(Activity, related_query_name='favorite') ratings = GenericRelation(Rating, related_query_name='object_list') def __str__(self): return self.recipeName def description_list(self): return self.description.split('\r\n') I use Django 1.10.5