Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What does this UWSGI output mean? > "(X switches on core 0)"
I'm running a nginx with uwsgi application with django that used the sqlite structure. When running uwsgi, when a GET or POST request is made, it sends output such as: [pid: 29018|app: 0|req: 39/76] 136.61.69.96 () {52 vars in 1208 bytes} [Wed Jul 19 17:25:12 2017] POST /binaryQuestionApp/?participant=A3AJJHOAV7WIUQ&assignmentId=37QW5D2ZRHPMKY652LHT9QV23ZD8SU => generated 6 bytes in 722 msecs (HTTP/1.1 200) 3 headers in 195 bytes (1 switches on core 0) What does the last bit mean? Sometimes it says 2 switches, sometimes 1. -
Django: CSS and Images (Static Files) loaded successfully but not applied
I'm using Django Dev Server and trying to test some templates I've made. When I visit addresses, I can see from the server prompt that CSS and images are loaded, but when I'm looking in a browser it is not applied. I'm also using Bootstrap and strangely enough, it does get applied. I would really like some help. I've seen (and implemented) the solution from various other threads with no avail. Please Help! Threads I've seen: Django -- Can't get static CSS files to load CSS loaded but not applied Django Static Files - CSS File Won't Load Django CSS Attachment Django - CSS problems CSS loaded but empty -
How to send a body in Swagger Django documentation?
I am trying to use the Swagger documentation in my Django project. However, I am not able to send the body. Furthermore, the List Operations doesn't work. Does Anyone has an idea how to fix it? I only have the default settings: urls.py: from rest_framework_swagger.views import get_swagger_view schema_view = get_swagger_view(title='Title API') urlpatterns = [ url(r'^swagger', schema_view), ] I can only list all of my URLs and log in as admin. Logout doesn't work. At this moment when I choose Expand Operations, I see something like this: It seems to me that problem may be associated with my structure of API. Structure of my all views in views.py looks in the way shown below. Maybe this is causing a problem because swagger isn't working with @api_view? @api_view(['GET', 'POST', 'PUT', 'DELETE']) def UserObject(request, user_id): if request.method == 'POST': try: Object.objects.get(user=user_id) return Response(status=status.HTTP_403_FORBIDDEN) except Object.DoesNotExist: serializer = ObjectSerializer(data=request.data) serializer.fields['user'].required = False if serializer.is_valid(): serializer.save(user_id=user_id) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) try: object = Object.objects.get(user=user_id) except Object.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = ObjectSerializer(object) return Response(serializer.data) elif request.method == 'PUT': serializer = ObjectSerializer(object, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': object.delete() return Response(status=status.HTTP_204_NO_CONTENT) I tried to … -
Celery : Received unregistered task of type
its my first time using celery and I'm having trouble executing some simple functions.I run celery -A IrisOnline worker/beat -l info and it gives me the unregistered type error.Heres the structure of my app: -Iris-Online -IrisOnline -__init__.py -tasks.py -celery_app.py -settings.py -templates -manage.py inside settings.py: BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Manila' CELERYBEAT_SCHEDULE = { 'execute_1_min': { 'task': 'celery_app.printthis', 'schedule': crontab(minute='*/1'), 'args': (16,16) }, } CELERY_IMPORTS = ("IrisOnline.celery_app","IrisOnline.tasks") tasks.py from celery import Celery app = Celery('tasks',backend="redis://localhost:6379") @app.task def print_this(): print("something") celery_app.py from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'IrisOnline.settings') app = Celery('tasks', broker='redis://localhost:6379/0') # Using a string here means the worker don't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings') # Load task modules from all registered Django app configs. app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def printsomething(self): print('this') -
Python Django Dict if in
When im check that 'p' (permission) is in dict permissions_count it always create a new dict with same name. Can you help me with that? So for example i have permssion Pick and in template now i dont have like: Pick: 2 but Pick: 1 Pick: 1 permssions_count = dict() station = Station.objects.extra(where=["packman!=''"]).all() for s in station: emp = Employee.objects.filter(UserLogin=s.packman).first() if emp is not None: perm = EmployeePermission.objects.filter(Employee=emp.id, Have=1).all() for p in perm: if p in permssions_count: permssions_count[p] += 1 else: permssions_count[p] = 1 -
Referencing Variables in Another Django Model with Foreign Key
I have a Project Model where a user can add a Project with an associated Position(s) for the Project. As an example, Website would be project whereas web developer would be the Position. Here are two models. class Project(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='project') created_at = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=255) description = models.TextField() complete = models.BooleanField(default=False) def __str__(self): return self.title.title() class Position(models.Model): project = models.ForeignKey(Project, default='',related_name='positions') name = models.CharField(max_length=140) description = models.TextField() skill = models.ForeignKey(Skill, default='') filled = models.BooleanField(default=False) def __str__(self): return '{} - {}'.format(self.project.title.title(), self.name.title()) I have a view created to show the user's profile and any current or past projects worked on. See below: class ProfileView(LoginRequiredMixin,generic.TemplateView): template_name = 'accounts/profile.html' login_url = settings.LOGIN_REDIRECT_URL def get_context_data(self, **kwargs): context = super(ProfileView, self).get_context_data(**kwargs) lookup = kwargs.get('username') user = models.User.objects.get(username=lookup) profile = models.UserProfile.objects.prefetch_related('skills').get(user=user) context['profile'] = profile context['skills'] = [skill for skill in profile.skills.all()] projects = models.Project.objects.all() context['current_projects'] = projects.filter(Q(owner=user) & Q(complete=False)) context['past_projects'] = projects.filter(Q(owner=user) & Q(complete=True)) return context I'm having trouble figuring out how to reference the position(s) for a particular projects in my html template. I know that if i try in python shell, i can query the position class and get all objects and then grab the project variables from there. I … -
Django Haystack, odd results when filtering by model
I am using django-haystack 2.0.0 with Whoosh 2.4.1 in Django 1.4. When I enter a search term to look across all indexes, it provides correct results. When I filter the same search by model, it provides various duplicates and omits other entries. It also does work correctly locally, this only happens in production. Any ideas what might be the culprit? -
Modifying manage.py for development and production
My project has a base.py, a dev.py and a production.py (pretty self explanatory). On my PC I only keep the dev.py and base.py and on the server I only keep production.py and base.py. While the WSGI isn't an issue, I do find myself always having to go into manage.py after each deployment to change the os.environ.setdefault() setting. I wanted to change this: from __future__ import absolute_import, unicode_literals import os import sys if __name__ == "__main__": try: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings.dev") #or project.settings.production from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) to this: from __future__ import absolute_import, unicode_literals import os import sys if __name__ == "__main__": try: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings.dev") except: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings.production") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) However this still raises an ImportError. Any ideas why? Or do you know a better way of doing this? -
Same bokeh app with different streamed data sources
I've been playing around and trying the bokeh server examples, with success. However I cannot seem to wrap my head around how to proceed to deployment. I currently have a bokeh app which streams data from a data path and updates the figure accordingly. This works well when serving it: bokeh serve --show app.py --args 'datapath/datafile.ext' The additional argument is the path to the data file. My aim is to allow users (on a Django framework) to use the same app, but with different data urls. While spawning an app for each active user 'works', its obviously too expensive and not recommended. I've come across similar threads which I'm including here for reference but they either have not been answered or are similar but use the bokeh client with push sessions (which is not what I'm after). Not answered: https://groups.google.com/a/continuum.io/forum/#!topic/bokeh/lk6um1OAnnI Use bokeh client (1): Sending URL parameter from Flask to a Bokeh server Use bokeh client (2): How to reuse a Bokeh App with different data on an embedded Bokeh Server -
Django : How to pass objects from template to views?
This is similar to my question but the answer didn't work for me. I create the object 'mark' and use it to instantiate a form as follows: mark = marklist.objects.filter(subject=facultyuser.sub)[0] form = MarklistForm(instance=mark) I then pass it to my template . Now from the template how can I pass the 'mark' object to another view as an argument ? I need to use it as an instance in the other view like this - form = MarklistForm(data=request.POST, instance=mark) Help will be appreciated.Thank you -
Difference between self and self.object
class ContractAsHtmlView(DetailView): model = Contract pk_url_kwarg = 'uuid' def get_object(self, queryset=None): try: return self.model.objects.get( signature_uuid=self.kwargs.get('uuid')) except self.model.DoesNotExist: return None def render_to_response(self, context, **response_kwargs): if self.request.GET.get('lang'): lang = self.request.GET.get('lang') else: lang = translation.get_language_from_request(self.request) if self.object.template.language == lang: template = self.object.template else: try: template = ContractTemplate.objects.get( slug=self.object.template.slug, language=lang) except ContractTemplate.DoesNotExist: template = self.object.template html = render_html_contract( template, self.object.customer, self.object.product) return HttpResponse(html) In this class view, they use self and self.object. I know that self is simply an object of type ContractAsHtmlView, but what is the meaning of self.object? Is it an object of type Contract? -
Upload File django MultiValueDictKeyError
I am trying to upload a file, the url is uploaded to the database on certain occasions. But the file is not uploaded and it shows the error MultiValueDictKeyError at. I've tried doing it in so many ways but none save the file to me in the static directory Forms class Localidad(models.Model): idlocalidad = models.AutoField(db_column='idLocalidad', primary_key=True) cod_emplazamiento = models.CharField(max_length=45,) cod_sitio = models.CharField(max_length=45, blank=True, null=True) url = models.FileField(upload_to='static/img/%Y/%m/%d', blank=True, null=True) models class Actualizar_LocalidadForms(forms.Form): cod_emplazamiento = forms.CharField(max_length=100,) cod_sitio = forms.CharField(max_length=100) url = forms.FileField(label='Seleccione Archivo',help_text='max. 42 megabytes',required=False ) views def actualizar_locativo_view(request,var1): if not request.user.is_authenticated: return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path)) locativo = Localidad.objects.filter(pk=var1) form = Actualizar_LocalidadForms(request.POST or None, request.FILES) if form.is_valid() and request.method == 'POST': form_data = form.cleaned_data obj = Localidad.objects.get(pk=var1) obj.codemplazamiento = form_data.get("cod_emplazamiento").upper() obj.cod_sitio= form_data.get("cod_sitio").upper() obj = Localidad(url=request.FILES['url']) obj.save() return HttpResponseRedirect('/detalle/%s/' % var1) context = { "form": form, "localidad":locativo, } return render(request, "locativo/actualizar_locativo.html", context) html {% for x in localidad %} <form method="post" enctype="multipart/form-data">{% csrf_token %} <table><td style="background-color: #dbdadc"><b>Foto Sitio:</b></td> <td>{% render_field form.url value=x.url %}{{ x.url }}</td> </table> {% endfor %} -
How to use django-tastypie with django-axes
Settings: django==1.8 django-tastypie==0.13 django-axes==2.3 I've got login resource through tastypie what looks like below from django.contrib.auth import login class LoginResource(Resource): class Meta: resource_name = 'login' allowed_methods = ['post'] def obj_create(self, bundle, **kwargs): form = AuthForm(data=bundle.data) if form.is_valid(): request.session.set_expiry(0) if form.get_user(): login(bundle.request, form.get_user()) raise ImmediateHttpResponse(response=HttpResponse(status=200)) raise ImmediateHttpResponse(response=http.HttpBadRequest(status=400) And I can't figure out how to log these login attempts in django-axes. -
Serving Django and Channels with Daphne
I have a Django project on Google Compute Engine. Here is the structure of my Django project. example_channels ├── db.sqlite3 ├── example │ ├── admin.py │ ├── apps.py │ ├── consumers.py │ ├── __init__.py │ ├── migrations │ │ │ ├── models.py │ ├── templates │ │ └── example │ │ ├── _base.html │ │ └── user_list.html │ ├── tests.py │ ├── urls.py │ └── views.py ├── example_channels │ ├── asgi.py │ ├── __init__.py │ ├── routing.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── manage.py Following the tutorialsб I made an asgi.py: import os from channels.asgi import get_channel_layer os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_project.settings") channel_layer = get_channel_layer() I use asgi_redis as a back-end. The settings file looks like this: CHANNEL_LAYERS = { 'default': { 'BACKEND': 'asgi_redis.RedisChannelLayer', 'CONFIG': { 'hosts': [('localhost', 6379)], }, 'ROUTING': 'example_channels.routing.channel_routing', } } I then try to start the server. I run python manage.py runworker & and get: ~/websockets_prototype/example_channels$ 2017-07-19 16:04:19,204 - INFO - runworker - Usi ng single-threaded worker. 2017-07-19 16:04:19,204 - INFO - runworker - Running worker against channel layer default (asgi_redis.core.RedisCha nnelLayer) 2017-07-19 16:04:19,205 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconne ct, websocket.receive And then run Daphne: ~/websockets_prototype/example_channels$ 2017-07-19 16:05:28,619 INFO … -
How to get the count of records for a django model property
I need to display the count of get_followers and get_following for my model in my admin. My model is called application and each app has a number of followers and following. I need to display the count for the followers and following. I tried to use the .count function in a separate function but I am missing something. This is what I have now: And this is what I am trying to get, I just can't figure out how to get the count. RELATIONSHIP_FOLLOWING = 1 RELATIONSHIP_BLOCKED = 2 RELATIONSHIP_STATUSES = ( (RELATIONSHIP_FOLLOWING, 'Following'), (RELATIONSHIP_BLOCKED, 'Blocked'), ) class Application(TimeStampModel): name = models.CharField(verbose_name='CI Name', max_length=100, unique=True) relationships = models.ManyToManyField('self', through='Relationship', symmetrical=False, related_name='related_to') def get_following(self): return ", ".join(str(x) for x in self.get_relationships(RELATIONSHIP_FOLLOWING)) getting the count of "get_following" def get_following_count(self): return ", ".join(str(x) for x in self.get_relationships(RELATIONSHIP_FOLLOWING).count()) but the above doesn't work. def get_followers(self): return ",".join(str(x) for x in self.get_related_to(RELATIONSHIP_FOLLOWING)) def get_friends(self): return self.relationships.filter( to_apps__status=RELATIONSHIP_FOLLOWING, to_apps__from_application=self, from_apps__status=RELATIONSHIP_FOLLOWING, from_apps__to_application=self) def get_friends_display(self): return ", ".join(str(x) for x in self.get_friends()) -
Server DNS address could not be found, Django-Heroku
I have been trying to fix an error setting up my DNS for www.hivetrade.io however I keep getting the error "Server DNS address could not be found." I have followed the steps on the heroku website found here: https://devcenter.heroku.com/articles/route-53#nakedroot-domain Step 1) Create hosted zone, -> www.hivetrade.io Step 2) create CNAME record set that links to my Heroku app -> Value: myapp.herokuapp.com Step 3) create S3 bucket for www.hivetrade.io and set Redirect all requests to: www.hivetrade.io Step 4) Create record set -> Type: A, Alias = Yes, Target = www.hivetrade.io (from s3) I registered my domain with route53, and the NamedServers are identical in hivetrade.io's record set. When I try http://www.hivetrade.io I get the DNS error and am unsure what I have done wrong. -
ImportError: cannot import name find_spec when deploying to openshift
I'm trying to deploy my Django project at openshift using Python 3.3 (because my project is made only for python3). Here we found an error ImportError: cannot import name find_spec when I check the log file. [Wed Jul 19 10:53:25 2017] [error] [client 127.2.83.1] from importlib.util import find_spec as importlib_find [Wed Jul 19 10:53:25 2017] [error] [client 127.2.83.1] ImportError: cannot import name find_spec As following these issues https://stackoverflow.com/a/34648720/6396981 and https://code.djangoproject.com/ticket/25868. Django recommended to upgrade my Python, but in this case openshift is only available for python 3.3.2. [myapp-foobar.rhcloud.com 596f5f3822s71edsf000ad]\> python Python 3.3.2 (default, Aug 5 2016, 06:46:58) [GCC 4.4.7 20120313 (Red Hat 4.4.7-9)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> When I check at the cartridges, Python 3.5 isn't available: ➜ openshift git:(openshift) rhc app create When creating an application, you must provide a name and a cartridge from the list below: Short Name Full name ========== ========= diy-0.1 Do-It-Yourself 0.1 jbossas-7 JBoss Application Server 7 jboss-dv-6.1.0 JBoss Data Virtualization 6 jbosseap-6 JBoss Enterprise Application Platform 6 jboss-unified-push-1 JBoss Unified Push Server 1.0.0.Beta1 jboss-unified-push-2 JBoss Unified Push Server 1.0.0.Beta2 jenkins-1 Jenkins Server nodejs-0.10 Node.js 0.10 perl-5.10 Perl 5.10 php-5.3 PHP 5.3 php-5.4 PHP 5.4 zend-6.1 … -
Maintain SQL operator precedence when construction Q objects in Django
I am trying to construct a complex query in Django by adding Q objects based on a list of user inputs: from django.db.models import Q q = Q() list = [ {'opertor': 'or', 'field': 'f1', 'value': 1} {'opertor': 'or', 'field': 'f2', 'value': 2} {'opertor': 'and', 'field': 'f3', 'value': 3} {'opertor': 'or', 'field': 'f4', 'value': 4} ] for item in list: if item['operator'] == 'and': q.add(Q(**{item['field']=item['value']}), Q.AND ) elif item['operator'] == 'or': q.add(Q(**{item['field']=item['value']}), Q.OR ) Based on this I am expecting to get a query with the following where condition: f1 = 1 or f2 = 2 and f3 = 3 or f4 = 4 which, based on the default operator precedence will be executed as f1 = 1 or (f2 = 2 and f3 = 3) or f4 = 4 however, I am getting the following query: ((f1 = 1 or f2 = 2) and f3 = 3) or f4 = 4 It looks like the Q() object forces the conditions to be evaluated in the order they were added. Is there a way that I can keep the default SQL precedence? Basically I want to tell the ORM not to add parenthesis in my conditions. -
django chat application - scrolled to bottom of page after particular time period
i was created simple django project using: https://github.com/andrewgodwin/channels-examples messages was reloaded but i cannot see first messages because of it reloads every 500ms when i try to scroll top it always shows last messages so how can i solved this issue.? i am using django:1.10.1 and jquery as ui Thanks in advance its always bottom only -
Python : Trouble pickling model using pickle library
Ok, I am trying to dump my ML model using Pickle library but everytime I am trying to use it in my Django app it gives me error "TypeError: must be char, not unicode" I had absolutely no Idea what is the problem so I tried printing my pickled object after dumping and it shows <Class "NoneType" > I thought this might be the reason for the problem. I am dumping the model like this: joblib.dump(clf,open("rec_pickle_3.pkl","wb")) and loading it like this: classifier=joblib.load(open("Recommender/rec_pickle_3.pkl", "rb")) Please help, as I have absolutely no idea how to solve this. -
Django select existing related record, or create new inline
I have a django model 'User' with a foreignkey to a related model 'Group'. I am using a modelForm to render the form for creating a user, which allows the user to select a group from a dropdown of existing groups. However, I'd like the option for the user to create a 'new' Group within that form if they don't find one they want in the list. I know I could do an inline form, but I'm not sure how to accomplish that while retaining the ability to optionally select an existing related record. Any advice? -
ALLOWED_HOSTS and Django
I try to launch Django 1.11 project on production server. When I start app I see error: Invalid HTTP_HOST header: 'bla-bla-bla.bla-bla-vla.com'. You may need to add u'bla-bla-bla.bla-bla-vla.com' to ALLOWED_HOSTS But, host "bla-bla-bla.bla-bla-vla.com" added to ALLOWED_HOSTS in settings.py already! I tried switch DEBUG from False to True and back. Now success. What I doing wrong? -
How to use celery with django and redis [Errno 61]
its my first time using celery and redis. I'm not sure if my configurations are correct but its giving me an OSError: [Errno 61] Connection refused celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'IrisOnline.settings') app = Celery('order_management') # Using a string here means the worker don't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings') # Load task modules from all registered Django app configs. app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) settings.py BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Manila' __init__.py from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ['celery_app'] function I want to execute @periodic_task(run_every=crontab(hour=10, minute=15)) def print_something(root_product): print("something") -
Django | URL Configuration | View | Reverse()
Intro Note, this exercises is purely for practice. I have read a number of posts here on StackOverflow, but I still can't seem to get it to work. I want to avoid hard-coding the URLs in my views. I know this can be achieved with reverse. However, I struggle to implement it. All my attempts resolve with TemplateDoesNotExist urls.py app_name = 'polls' urlpatterns = [ url(r'^$', IndexView.as_view(), name='index'), url(r'^question/(?P<question_id>[0-9]+)', QuestionView.as_view(), name='question') ] views.py class QuestionView(View): def get(self, request, question_id): template_name = 'polls/question.html' question = Question.objects.get(pk=question_id) context = {'question' : question} return render(request, reverse('polls:question', args=(question_id)), context) question.html ... {% if questions %} <ul> {% for question in questions %} <li><a href="{% url 'polls:question' question.id %}">{{question.question_text}}</a></li> {% endfor %} </ul> {% else %} <p>Oops! No questions could be found</p> {% endif %} ... -
How can I filter my Timeline with user posts I follow in Django?
I have the default model of Django 'User', 'UserProfile', 'Post' and 'Connection'. Is there any way to filter in the timeline who I follow? models.py: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(upload_to='avatar', default='avatar/default.png') header = models.ImageField(upload_to='header', default='header/default.png') bio = models.TextField(max_length=140, blank=True) website = models.URLField(max_length=200, blank=True) location = models.CharField(max_length=30, blank=True) date_birth = models.DateField(null=True, blank=True) def __str__(self): return self.user.username @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) instance.userprofile.save() @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.userprofile.save() class Connection(models.Model): following = models.ForeignKey(User, related_name='following') follower = models.ForeignKey(User, related_name='follower') date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return "{} > {}".format(self.following.username, self.follower.username) class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) text = models.CharField(max_length=200) image = models.ImageField(upload_to='posts', blank=True) video = models.URLField(blank=True) date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) class Meta: ordering = ["-date_created"] def __str__(self): return "{} {} (@{}) : {}".format(self.user.first_name,self.user.last_name, self.user.username,self.text) These are the appropriately related models, but the problem is that they do not filter them in the views. views.py: class TimelineListView(LoginRequiredMixin, generic.ListView): model = Post template_name = 'timeline/timeline.html' def get_context_data(self, **kwargs): context = super(TimelineListView, self).get_context_data(**kwargs) context['posts'] = Post.objects.filter() context['users'] = User.objects.all().order_by('?')[:3] return context Is there a way to filter Connection related? There will also be other Timelines but filtered by Connection + media (image and video).