Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to rewrite django test case to avoid unpredictable occasional failures
I have a test case that's written exactly like this def test_material_search_name(self): """ Tests for `LIKE` condition in searches. For both name and serial number. """ material_one = MaterialFactory(name="Eraenys Velinarys", serial_number="SB2341") material_two = MaterialFactory(name="Nelaerla Velnaris", serial_number="TB7892") response = self.client.get(reverse('material-search'), {'q': 'vel'}) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data['count'], 2) self.assertEqual(response.data['results'][0]['name'], material_one.name) self.assertEqual(response.data['results'][1]['name'], material_two.name) My error message is : line 97, in test_material_search_name self.assertEqual(response.data['results'][0]['name'], material_one.name) AssertionError: 'Nelaerla Velnaris' != 'Eraenys Velinarys' - Nelaerla Velnaris + Eraenys Velinarys Then when i re-run without changing any code, it becomes successful. This error happens occasionally not always. I was wondering if there's a better way to achieve the objectives of the test case without having that weird failure once in a while. The frequency this error occurs is around 1 every 50 times I run the test. The typical test command I use : python manage.py test app_name.tests --keepdb -
Is there a way to maintain the serializer order?
If I write this order for AddressRegionDetailSerializer and AvailableAreaSerializer: class AddressRegionDetailSerializer(ModelSerializer): """ 地域详情(包含可用区域) """ availableareas = AvailableAreaSerializer(many=True, read_only=True) class Meta: model = AddressRegion fields = "__all__" class AvailableAreaSerializer(ModelSerializer): """ 可用地区 """ class Meta: model = AvailableArea fields = "__all__" There will report NameError issue: NameError: name 'AvailableAreaSerializer' is not defined in this line: availableareas = AvailableAreaSerializer(many=True, read_only=True) So, I must put the AvailableAreaSerializer in the front. But however in my idea, I want to write the Serializer as the Models order, I don't want to break this law. So, is there a simple way to maintain this order? -
Choose where to save the image when you call save_frame() in MoviePy
I'm using MoviePy to save a frame from an uploaded video (the specific function in MoviePy is save_frame() source). This works successfully, however I want the image to save in my media folder (Django's conventional folder for saving uploaded files). At the moment it saves in the project root (where manage.py is). There doesn't seem to be a settings file so I'm not sure how to change this. Any suggestions appreciated. -
Key Error - Synapse Documentation error - Django
I have a Django app and I am trying to integrate the synapse API into my project. I want to verify a user by added a CIP document and a verification or validation source through last 4 of ssn. I am using the api documentation and the github examples to try to get it to work, but I am getting an issue using the Synapse example in the github repo. A user is being created but the real issue is comming after the base document is added. It is sending the request to Synapse and then the error comes up for the day key.... Here is the error I am getting with trace: KeyError at /verify_profile/ 'day' Request Method: POST Request URL: http://127.0.0.1:8000/verify_profile/ Django Version: 1.11.5 Exception Type: KeyError Exception Value: 'day' Exception Location: /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/synapse_pay_rest/models/users/base_document.py in create, line 107 /Users/omarjandali/Desktop/Yap/Yap/general/views.py in ProfileVerification createUserSynapse(request) ... /Users/omarjandali/Desktop/Yap/Yap/general/views.py in createUserSynapse base_document = create_user.add_base_document(**options) ... /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/synapse_pay_rest/models/users/user.py in add_base_document return BaseDocument.create(self, **kwargs) ... /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/synapse_pay_rest/models/users/base_document.py in create birth_day=kwargs['day'], ... Here is my code in the views.py file: args = { 'email':str(currentUser.email), 'phone_number':str(currentProfile.phone), 'legal_name':str(legal_name), 'note': str(note), 'supp_id':str(supp_id), 'is_business':False, 'cip_tag':cip_tag, } create_user = SynapseUser.create(client, **args) print(create_user) # in order to verify the user and transfer money phone = … -
How to create a Event in Django-Scheduler while creating a Product or any Inserting data in any table?
I am a total newbie in Python and new on StackOverFlow. If I am missing something please let me know This is Django-scheduler App:- https://github.com/llazzaro/django-scheduler It giver various options to create events and occurrences Documentation is here:- http://django-scheduler.readthedocs.io/en/latest/ I have a model known as Product in Django. Which is defined as below `class Products(models.Model): product_choice = ( ('1' ,'sightseeing'), ('2','daytour'), ('3','activity'), ('3','experience'), ('4','rentals'), ('3','multidaytrip'), ) product_type = models.CharField(max_length=20,choices=product_choice, null=True) category = models.ForeignKey(Category, null=True) title = models.CharField(max_length=100, blank=True, default='') pic1 = models.ImageField(upload_to='media', default='media/ross-island-2.jpg') pic2 = models.ImageField(upload_to='media', default='media/ross-island-2.jpg') pic3 = models.ImageField(upload_to='media', default='media/ross-island-2.jpg') shared_code = models.BooleanField(blank=True, default=False) age_requirements = models.CharField(max_length=100, blank=True, default='') time_slots = models.CharField(max_length=100 ,blank=True, default='') location = models.CharField(max_length=100 ,blank=True, default='') duration = models.CharField(max_length=100 ,blank=True, default='') affiliated_institutions = models.CharField(max_length=100, null=True) includes = models.TextField(blank=True) excludes = models.TextField(blank=True) medical_requirements = models.CharField(max_length=100, blank=True, default='') perks_included = models.CharField(max_length=100, blank=True, default='') product_detail = models.TextField() vender_name = models.CharField(max_length=100, blank=False) user = models.ManyToManyField(settings.AUTH_USER_MODEL) vendor_id = models.IntegerField(blank=True) about_vender = models.TextField() price = models.IntegerField(default=0) child_price = models.IntegerField(default=0) infant_price = models.IntegerField(default=0) product_detail = models.TextField(blank=True) slug = models.SlugField(unique=True, blank=True) total_slots = models.IntegerField(blank=True, null=True) open_slots = models.IntegerField(blank=True , null=True) cancellation_policy = models.TextField(blank=True) def __unicode__(self): return str(self.title) def __str__(self): return str(self.title) ` I have installed the Django-Scheduler in my Django Application, however it is installed … -
Ideal Architecture for Django Projects
I'm getting into a rather extensive project and it popped into my head that I don't know what the accepted\proper architecture for a Django is these days. I'll describe what prompted this question. I am making a, what I think is a simple web site that, for all intents and purposes, is made for small companies, or even single entity LLC type companies. In this project the front page is a simple sell of the company with some additional access for customers and employees. Employees would log in, change\adjust\add contacts\companies\address etc. I have this part all done, and I was about to move on to the next part which is filling out of reports. This particular company will have two types of reports - consultation reports and service reports. Now with where I am right now, I could continue to build on the current app\template, or I could start another app. Staying within the current app would certainly seem to make things easier, but definetly not cleaner. So what do you all do? How do you structure your projects? What are the general accepted conventions for decisions like this? Thanks! -
Error in django 1.8.7 version with python 2.7.12
`` I am getting the following trackback message when I run command(python3 manage.py runserver) on ubuntu OS: Traceback (most recent call last): File "manage.py", line 10, in execute_from_command_line(sys.argv) File "/usr/lib/python3/dist-packages/django/core/management/init.py", line 354, in execute_from_command_line utility.execute() File "/usr/lib/python3/dist-packages/django/core/management/init.py", line 303, in execute settings.INSTALLED_APPS I am using the following version of django and python: Django 1.8.7 python: 2.7.12 Can someone please help me to resolve this issue? Because I tried it 10 times from google suggestion but didn't get the right answer. -
dot in `django-admin.py startproject myproject .`
I keep the question in mind when read through Django source codes for weeks. Start project with Django, django-admin.py startproject myproject . # a tailed dot in the end manage.py will be created outside the project folder. if without '.', manage.py will be included in project folders. How does the '.' work? -
is there a faster way to write similar test cases for Django views?
Basically I realise that I am writing a lot of test cases for views that are in this format def test_update_with_only_1_field(self): """ Tests for update only 1 field GIVEN the following shape and related are valid WHEN we update only with just 1 field THEN we expect the update to be successful """ shape_data = { 'name': 'test shape', 'name_en': 'test shape en', 'name_zh_hans': 'test shape zh hans', 'serial_number': 'test shape serial number', 'model_name': { 'some_field': '123' } } data = json.dumps(shape_data) response = self.client.post(reverse('shape-list-create'), data, 'application/json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) some_model = response.data['some_model'] new_some_field = '12345' data = json.dumps({'some_field': new_some_field, 'id': response.data['some_model']['id']}) response = self.client.put(reverse('some-model', args=[some_model['id']]), data, 'application/json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(new_some_field, response.data['some_field']) I need to do this for more than 10 times. Which I have already done so. the only difference each time, is the following phrases "some_model", "some-model", and "some_field" I was wondering if there's a faster way to do this. I can think abstractly two ways: create a template in a text editor that somehow can generate the final test case which I then copy and paste. I am using sublime text 3 though I am okay to switch to another text editor There's a way I can write … -
Django, how do you set the value of a field in a model to be a hash of one of the fields?
This is what my model looks like: class Alert(models.Model): hash = models.CharField(max_length=64, unique=True) raw_line = models.TextField() alert_datetime = models.DateTimeField() datetime_dismissed = models.DateTimeField(null=True) and when I create an Alert, I set the hash value as something. But, I read that I can effectively do this: hash = models.CharField(max_length=64, unique=True, default=some_hash_function) def some_hash_function(): ... return some_hash But the hash I want relies on raw_line, is it possible to have the function hash the raw_line and set it by default? -
How to move up and down
I'm trying to make a ship for alien invaders move up and down but can't seem to make it properly work without messing something up. With my code below what would I need to add? alien_invasion.py: import sys import pygame from settings import Settings from ship import Ship import game_functions as gf def run_game(): #Initialize pygame, settings, and screen object pygame.init() ai_settings = Settings() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Alien Invasion") #Draw the ship ship = Ship(ai_settings, screen) #Start the main loop for the game. while True: #Watch for keyboard and mouse events gf.check_events(ship) ship.update() gf.update_screen(ai_settings, screen, ship) run_game() ship.py: import pygame class Ship(): def __init__(self, ai_settings, screen): """Initialize teh ship and set its starting position""" self.screen = screen self.ai_settings = ai_settings #Load teh ship image and get its rect self.image = pygame.image.load('ship.bmp') self.rect = self.image.get_rect() self.screen_rect = screen.get_rect() #Start each new ship at the bottom center of the screen self.rect.centerx = self.screen_rect.centerx self.rect.bottom = self.screen_rect.bottom # Store a decimal value for the ship's center. self.center = float(self.rect.centerx) # Movement flag self.moving_right = False self.moving_left = False def update(self): """Update the ship's postion based on the movement flag""" # Update the ship's center value, not the rect. if self.moving_right and … -
saving an instance of a model with auto_now_add in Django returns error message Column 'xxx' cannot be null
I must be doing something very wrong or this error doesn't make any sense to me. I have an object Location: class Location(models.Model): class Meta: db_table = 'location' location_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=200) state = models.CharField(max_length=200) country = models.CharField(max_length=200) apt_number = models.CharField(max_length=200, null=True, blank=True) street_address = models.CharField(max_length=200) city = models.CharField(max_length=200) zip_code = models.IntegerField() created = DateTimeField(auto_now_add=True) here this is my code for inserting a new or updating an existing location record: class LocationList(generics.ListCreateAPIView): queryset = Location.objects.all() serializer_class = LocationSerializer def post(self, request, *args, **kwargs): location_dict = request.data if 'location_id' not in location_dict: okStatus = status.HTTP_201_CREATED else: okStatus = status.HTTP_200_OK location = Location(**location_dict) location.save() return Response(LocationSerializer(location).data, status=okStatus) Inserts work fine, but everytime an update happens, I get the error "Column 'created' cannot be null". My online research seems to point me to the fact that this was a bug which has been long fixed. I expect the update to pass since the 'created' field was set to auto_now_add, which means Django should set that field once upon insert and leave it on any subsequent update. I do not know why Django is trying to set that column to null on update. I am using MySQL as database. -
Registered Models not showing in Django Admin
So I boogered up a migrate and decided it would be easier to go with a db reset. So I removed the migrations folder, as well as the database. I then recreated the database, ran python manage.py migrate, createsuperuser, and went ahead and logged into the admin panel - but to my surprise the models that I have registered no longer show up in the panel. They were there before this whole thing. Can anyone give me some insight? I'm sure I've missed something small and stupid. The file structure, outside of the migrations folder, has been untouched. Models.py from django.db import models from django.core.validators import RegexValidator class DetailsModel(models.Model): distance = models.SmallIntegerField() rate = models.DecimalField(max_digits=5, decimal_places=2) class PhoneModel(models.Model): phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phone_number = models.CharField(validators=[phone_regex], max_length=15, blank=True) # validators should be a list class TravelModel(models.Model): mileageRate = models.DecimalField(max_digits=4, decimal_places=3) def __str__(self): return '%s' % (self.mileageRate) class CompanyModel(models.Model): name = models.CharField(max_length=255) details = models.ForeignKey(DetailsModel, on_delete=models.CASCADE) def __str__(self): return '%s' % (self.name) class SiteModel(models.Model): company = models.ForeignKey(CompanyModel, on_delete=models.CASCADE) street1 = models.CharField(max_length=255) street2 = models.CharField(max_length=255) city = models.CharField(max_length=50) state = models.CharField(max_length=2) zipcode = models.IntegerField() country = models.CharField(max_length=50) class PersonModel(models.Model): firstName … -
django: are the view parameters "sticky"?
I have this url matcher: url(r"^(.*)$", views.process) and this view: def process(request, path, context={}): print(context) context["test"] = "test" return HttpResponse("") At first I get context={} as expected, but as I reload the page, I get the process view called with context={"test": "test"}. Does this mean if I make changes to view parameters, it remains sticky? Or is this because of some middleware? -
Is there a more Django way to convert underscore string into Django model?
I wrote my own helper function that will convert a underscore string and return the Django model Django version 1.11 from django.apps import apps def _underscore_string_to_model(in_str, app_name, delim="_"): chunks = in_str.split(delim) chunks[0:] = [_.title() for _ in chunks[0:]] return apps.get_model(app_name, "".join(chunks)) Is there an existing function or library that already does this? I have been looking around but there appears to be none hence i wrote my own. I am happy to keep using this but prefer to re-use existing if possible -
Does Django hit the database when I access an object's attributes?
Background info to follow because the question is fairly straightforward. class Question(models.Model): name=... etc. Does the following code query the database? question_name = question.name My view takes a set of questions and user responses and scores a worksheet. My goal is to execute all of the scoring without going back to the database. Then saving the result of my comparisons (a dictionary) using a background task where it's ok if it takes a little longer. Trying to eliminate any unnecessary database hits. -
How to correctly let a Javascript file in static folder inject an HTML file in the same static folder?
I'm in a very confusing situation... kinda like INCEPTION movie... I'm using an private charting library in a Django 1.10 project. I'll show the file structure of this Django project with the charting library files. These library files came in a structure that I kept under the static folder in Django, excpet by the index.html I put in template folder to be able make some loginc with it. I'll show below how the project files and mark the charting library files with "*". /project settings.py urls.py /static /tdviewer /charting_library* /static* /js* spin.min.js* tv-chart.18168320bd5edaac1e75.html* charting_library.min.js* /tdviewer /templates /tdviewer index.html * urls.py view.py This is /project/settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] This is /project/urls.py urlpatterns = [ url(r'^tdviewer/', include('tdviewer.urls')), url(r'^admin/', admin.site.urls), ] This is /tdviewer/urls.py urlpatterns = [ # /tdviewer/ url(r'^$', views.index, name='index'), ] This is /tdviewer/views.py #/index def index(request): template = loader.get_template('tdviewer/index.html') context = { } response = HttpResponse(template.render(context, request)) return response The library index.html located at /tdviewer/templates/tdviewer/index.html is an example in how to use it and I put it in the template app because I'll need to do some code on server side. This HTML calls the the libraby's javascript in the tag: <!DOCTYPE HTML> {% … -
How to include templates of external libraries?
I'm trying to use django-openinghours template in my template with {% include openinghours/edit_base.html %} but I get TemplateNotFound. django-openinghours was installed using pip into the virtualenv. Any thought appreciated. -
PrimaryKeyRelatedField fields prints ids of foreign table but need values
PrimaryKeyRelatedField fields prints ids of foreign table but api demands to return values. Is there any customized way to get the values class Album(models.Model): album_name = models.CharField(max_length=100) artist = models.CharField(max_length=100) class Track(models.Model): album = models.ForeignKey(Album, related_name='tracks') order = models.IntegerField() title = models.CharField(max_length=100) duration = models.IntegerField() class Meta: unique_together = ('album', 'order') order_by = 'order class AlbumSerializer(serializers.ModelSerializer): tracks = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = Album fields = ('album_name', 'artist', 'tracks') Results : { 'album_name': 'The Roots', 'artist': 'Undun', 'tracks': [ 89, 90, 91, ... ] } Is there any way to get output in the below format: { 'album_name': 'The Roots', 'artist': 'Undun', 'tracks': [ {'order': 1, 'title': 'Public Service Announcement', 'duration': 245}, {'order': 2, 'title': 'What More Can I Say', 'duration': 264}, {'order': 3, 'title': 'Encore', 'duration': 159}, ] } -
Passing a pickled object in Django's HttpRequest
I'm currently attempting to move an sklearn model object from server side to client side. I'm new to django so I'm struggling mightily. Option one is to jsonify all the model parameters, pass them through and reconstruct a fresh model object with those parameters. However, in my attempts to both simplify, and learn a bit about django, I've been trying to pass a pickled object and failing. I originally tried something simple like: result = pickle.dumps({'test':'test'}, pickle.HIGHEST_PROTOCOL) return HttpResponse(pkl) When I got it from the front end API, if I did a simple pickle.loads(api_res) I get a type instance error. When I do: pickle.loads(api_res.read()) It gives me an EOF error. I know there's the potential to also just pickle.dump instead of the string version, but I'm having trouble with djangos content-type etc. I just seem to get gibberish on the way out. The unfortunate icing on the cake is that, it's apparently difficult to find instances of people serializing objects and returning them with django, because almost all the results are about serializing/pickling the django objects themselves. Any help/links would be appreciated. -
Django: ImportError: No module named 'corsheaders'
During my first Django project i encountered a strange problem: ImportError: No module named 'corsheaders'. I have installed django-cors-headers in my virtual enviroment using pip3 install django-cors-headers but with on success. pip3 freeze shows package django-cors-headers as installed, but whenever i run uwsgi it shows exception traceback in log: Traceback (most recent call last): File "./login/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/home/pawel/pythonApp/myappenv/lib/python3.5/site- packages/django/core/wsgi.py", line 13, in get_wsgi_application django.setup(set_prefix=False) File "/home/pawel/pythonApp/myappenv/lib/python3.5/site- packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/pawel/pythonApp/myappenv/lib/python3.5/site- packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/home/pawel/pythonApp/myappenv/lib/python3.5/site- packages/django/apps/config.py", line 94, in create module = import_module(entry) File "/home/pawel/pythonApp/myappenv/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ImportError: No module named 'corsheaders' unable to load app 0 (mountpoint='') (callable not found or import error) I tried installing different corsheaders versions, but with no success either. I am running Django 1.11.7 and Python 3.5.2. Any help would be appreciated. -
Celery not processing tasks from RabbitMQ
I have a Celery 4.1 worker configured to process tasks from a queue called "longjobs", using RabbitMQ as my messaging backend. My Celery configuration and workers are managed through a Django 1.11 project. Nothing throws any errors, but tasks launched from my Django application are never picked up by my worker. My celery.py file looks like: from __future__ import absolute_import import os import sys from celery import Celery from celery._state import _set_current_app import django app = Celery('myproject') app.config_from_object('django.conf:settings', namespace='CELERY') _set_current_app(app) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings.settings') sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../myproject'))) django.setup() from django.conf import settings app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) My Django Celery settings are: CELERY_IGNORE_RESULT = False CELERY_TRACK_STARTED = True CELERY_IMPORTS = ( 'myproject.myapp.tasks', ) CELERY_RESULT_BACKEND = 'amqp' CELERY_ACCEPT_CONTENT = ['pickle', 'json', 'msgpack', 'yaml'] CELERY_TASK_SERIALIZER = 'pickle' CELERY_RESULT_SERIALIZER = 'pickle' CELERY_RESULT_PERSISTENT = True CELERY_ALWAYS_EAGER = False CELERY_ROUTES = { 'mytask': {'queue': 'longjobs'}, } CELERY_WORKER_PREFETCH_MULTIPLIER = CELERYD_PREFETCH_MULTIPLIER = 1 CELERY_SEND_TASK_ERROR_EMAILS = True CELERY_ACKS_LATE = True CELERY_TASK_RESULT_EXPIRES = 360000 And I launch my worker with: celery worker -A myproject -l info -n longjobs@%h -Q longjobs and in its log file, I see: [2017-11-09 16:51:03,218: INFO/MainProcess] Connected to amqp://guest:**@127.0.0.1:5672/myproject [2017-11-09 16:51:03,655: INFO/MainProcess] mingle: searching for neighbors [2017-11-09 16:51:05,441: INFO/MainProcess] mingle: all alone [2017-11-09 16:51:06,162: INFO/MainProcess] longjobs@localhost ready. indicating that the … -
How can I create an object and associate a User with M2M fields
I have a problem that I haven't been able to find a good post on how to best achieve so I'd hope I could get a pointer on how I could do this. I need a way to create groups via my api endpoint if they do not exist, and associate (.add()) the user with that requested, and now created object. A group in my case is a to_location, from_location, advertised_train_identity and a weekday in iso format. I have bulletpointed a more detailed version down below. Only allow: GET, POST, DELETE methods. This is the flow I have visualized in my mind: Client sends a request with a list of group objects. Since many=True in serializer, list will be split up into object chunks and feed separatly into the serializer. If group object already exists, I need an instance of it so I can associate the requesting user (request.user) with the already existing object. If it does not exist, create the group as per request, and add the requesting user onto it. As for the DELETE: query the instance of the group object, if requesting is the only currently added user to the group object - then unsubscribe, and delete … -
Django 1.11 order by field on related model duplicate results workaround
In Django 1.11 I have a parent and child model (one to many relationship) simplified below: class Conversation(models.Model): name = models.CharField(max_length=150) class Comment(models.Model): comment_text = models.TextField() submitted_date = models.DateTimeField() conversation = models.ForeignKey(Conversation, on_delete=models.CASCADE) class Meta: ordering = ['-submitted_date'] A conversation can have many comments. Now what I want to do is order conversations by which one has the most recent comments. I attempted to add this to the Conversation model: class Meta: ordering = ['-comment__submitted_date'] And this sort of works, but it returns duplicates in the queryset - this duplicate behavior is well documented in Django and why it happens - https://docs.djangoproject.com/en/1.11/ref/models/querysets/#order-by - but it doesn't say anything about how to work around it. I'm looking for a way to work around this limitation. The overall goal is: have conversations sorted by most recent comment (submitted_date). I've tried multiple variations, but it either doesn't sort at all, or it returns duplicates (which isn't useful to me). distinct() won't work either, which is also documented in the link. I could add an 'updated_at' or similar field to Conversation, and update that whenever a comment is created/updated, but that feels really hacky and unclean to me, and I'd rather avoid it if … -
I can't get the data from the database by using _set.all on Django. Where am I doing it wrong?
This is the related part of the models.py: from django.db import models class Author(models.Model): author_name = models.CharField(max_length=50) def __str__(self): return self.author_name class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) book_title = models.CharField(max_length=250) book_image = models.ImageField(max_length=1000) book_link = models.URLField() def __str__(self): return self.book_title And this is the related part of the template in which I'm trying to get the information: <ul> {% for book in author.book_set.all %} <li><a href="{{ book.book_link }}">{{ book.book_title }}</a></li> {% endfor %} </ul> I've also checked if the information is available in the database, and it looks like everyting's okay. This is the only part I'm having trouble.