Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
user.is_authenticated always returns False for inactive users on template
In my template, login.html, I have: {% if form.errors %} {% if user.is_authenticated %} <div class="alert alert-warning"><center>Your account doesn't have access to this utility.</center></div> {% else %} <div class="alert alert-warning"><center>Incorrect username or password!</center></div> {% endif %} {% endif %} What I am trying to do is, if after form submission, user is inactive then display a different error message and if user is simply not authenticated then display Incorrect username password error message. This doesn't work. However inside a view, user.is_authenticated returns True even for inactive users. -
Django admin models
Good day, help please with architecture I have models class Filters(models.Model): def __unicode__(self): return format('%s' % self.title) title = models.CharField(max_length=255,verbose_name='Name filter') class FilterValue(models.Model): value = models.CharField(max_length=255,verbose_name='value filter') filter = models.ForeignKey(Filters) class Casino(models.Model): title = models.CharField(max_length=255,verbose_name='Name Casino') filters = models.ManyToManyField(Filters) In admin class AdminCasino(admin.ModelAdmin): fields= ['title','filters'] How can i get view in admin multiselect: Name Filter --value filter of this name and so on -
How to display the corrected field in a form in Django?
Let's say I have a Person model which has for example 2 attributes : a name and some job experiences (a textarea). I have a form to create a Person and I have created a custom validation rule for the TextField (the job experiences). I would like to display the errors associated to the TextField (the job experiences) (I have already done that. And I would like to display the content of the TextField but corrected : I just don't know how to display it. For example, here are some job experiences entered by the user : Work at McDonalds for 2 years, Study Customer Service for 1 year When the user submit the form, this would be invalid because of my custom validation rule for the TextField. I just would like to display the corrected input in the form page (not in the TextField but just below as a paragraph for example) : - Work at McDonalds for 2 years - Study Customer Service for 1 year I have tried this : class PersonCreate(CreateView): model = Person form_class = PersonForm success_url = 'my_site/success.html' def get_context_data(self, **kwargs): # I have an error with the following line : 'NoneType' object has … -
Can't load Django static files in view
I'm a new player in Django and Python. I want to load the static files from the project level static folder. The problem is I can't but I still can load the static of an app. This is the structure of my project: Yaas __init__.py settings.py urls.py wsgi.py templates base.html static style.css auction templates auction index.html static auction style.css __init__.py apps.py models.py urls.py views.py The thing is it works with static file of auction, like this in base.html: {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'auction/style.css' %}" /> But it returns 404 with the project static file: {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'style.css' %}" /> settings.py STATIC_URL = "/static/" STATIC_ROOT = os.path.join(BASE_DIR, "static") I tried other solutions and document on Django but it still didn't work. I am using Django 1.10. -
Selecting file in input file field doesn't show file selected
I have the following field in my html <input id="files" type="file" name="files"> and I'm using jquery fileupload to post it on the server, however when you select a file it triggers the upload but on the page there file doesn't show it's been selected and it's confirmed on the json reply. The Django view that accepts the file function @csrf_exempt def create_event(request): context = RequestContext(request) response_data = {} response_data['status'] = False if request.method == 'POST': try: data = json.loads(request.body) except: if request.FILES == None: response_data['status_message'] = 'No File Detected' return HttpResponse( json.dumps(response_data), content_type="application/json" ) else: file_str = str(request.FILES) response_data['status_message'] = 'File Detected' response_data['file_det'] = file_str return HttpResponse( json.dumps(response_data), content_type="application/json" ) venue, event_name, description, category, contact, email = data['venue'], data['event_name'], data['description'], data['category'], data['contact'], data['email'] phone_number, website, free_status, ticket_price, start_dates, start_times = data['phone_number'], data['website'], data['free_status'], data['ticket_price'], data['start_dates'], data['start_times'] end_times, end_dates, recurring, ticket_details = data['end_times'], data['end_dates'], data['recurring'], data['ticket_details'] The response {"status": false, "file_det": "<MultiValueDict: {}>", "status_message": "File Detected"} suggests likely no file was uploaded Live example here from the server end request.FILES has an empty dictionary -
Django form: WARNING:root:Could not resolve form field
I'm using django v1.8 in python 2.7 In a table in models.py I have class Diagnosis(models.Model): diagnosis_circumstances = models.CharField(max_length=150) diagnosis_circumstances_date = models.DateField('Date of diagnosis',null=True,blank=True) date_of_input= models.DateField(null=True,blank=True) pub_date = models.DateTimeField(auto_now=True) author = models.ForeignKey(User) patient = models.ForeignKey(Demographic) When I'm trying to show pub_date field in forms.py like: class DiagnosisForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(DiagnosisForm, self).__init__(*args, **kwargs) self.helper=FormHelper(form=self) self.helper.field_class = 'col-md-8' self.helper.label_class = 'col-md-3' # self.helper.form_class = 'forms-horizontal' self.helper.layout = Layout( Fieldset( '<b>Latest update</b>', Div( Div('pub_date', css_class='col-md-8'), css_class='row', ), ), FormActions( Submit('submit', "Save changes"), Submit('cancel',"Cancel") ), ) self.helper.form_tag = False self.helper.form_show_labels = True class Meta: model = Diagnosis exclude = ['patient', 'author'] list_display = ('patient', 'pub_date', 'author') I get the message: WARNING:root:Could not resolve form field 'pub_date'. Traceback (most recent call last): File "C:\Python27\lib\site-packages\crispy_forms\utils.py", line 92, in render_f ield field_instance = form.fields[field] KeyError: u'pub_date' Do you have any idea how to fix this? -
maximum recursion depth exceeded getter Django
I have some class with custom getter for specific attr: class Item(a, b, c, d, models.Model): title = Field() description = Field() a = Field() _custom_getter = ['title','description'] def __getattribute__(self, name): if name in self.custom_getter: return 'xxx' else: return super(Item, self).__getattribute__(name) this code raise RunetimeError: maximum recursion depth exceeded while calling a Python object but when i use this piece of code: class Item(a, b, c, d, models.Model): title = Field() description = Field() a = Field() def __getattribute__(self, name): custom_getter = ['title','description'] if name in custom_getter: return 'xxx' else: return super(Item, self).__getattribute__(name) all works like I want. Wher is my mistake in first piece of code ? -
Calendar.getTime() to Date object
I've an instance of a Calendar setted with UTC time zone, I need to be UTC becouse I've to sync with a server that is UTC. I need to create a Date object from this Calendar, and I use Calendar.getTime(). But when I try to print out the Date object I see it with a different TimeZone (CEST instead of UTC) TimeZone timeZone = TimeZone.getTimeZone("UTC"); Calendar cal = Calendar.getInstance(timeZone); cal.setTime(timeMillisecond); Date d = cal.getTime(); Log.d("TAG", d.toString()); EDIT: When I pass the date object to the server, I get it with CEST timezone instead of UTC time zone. -
django rest framework access item by lookup field instead of pk 3.4 DRF
I need to have lookup field in order my frontend sends email which should be deleted but i get item not found. I've reserched alot about this problem but i cant figure out which drf version what supports. class EmailReminderSerializer(serializers.ModelSerializer): city = serializers.CharField(max_length=255) url = serializers.HyperlinkedIdentityField( view_name='web:email_reminder-detail', ) class Meta: model = EmailReminder fields = '__all__' extra_kwargs = { 'url': {'lookup_field': 'email'} } Now i have url but it points to instance pk, not by my desired lookup field. Any suggestions of how it works in 3.4 version or do you have any other solutions to some lower version >=3.0? -
Could anybody please help me to assign a foreignkey relation with django rest framework, my code is as follows
models.py class LenderProfile(models.Model): user = models.OneToOneField(User) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) mobile_number = models.PositiveIntegerField(_('Mobile Number'),) email_id = models.EmailField(max_length=100) profession = models.CharField(max_length=100) home_address = models.CharField(max_length=100) work_contact_number = models.IntegerField(_('Mobile Number'),) def __unicode__(self): return str(self.user) class LenderOtp(models.Model): otp = models.CharField(max_length=10, default="123456") lenderprofile = models.ForeignKey(LenderProfile) serializers.py class LenderProfileSerializer(serializers.ModelSerializer): url = serializers.HyperlinkedIdentityField() class Meta: model = LenderProfile fields = [ 'url', 'first_name', 'last_name', 'mobile_number', 'email_id', 'profession', 'home_address', 'work_contact_number', 'bank_account_details', ] class LenderProfileOtpSerializer(serializers.ModelSerializer): lenderprofile_set = LenderProfileSerializer(many=True, read_only=True) class Meta: model = LenderOtp fields = [ 'lenderprofile_set', 'otp', ] views.py class LenderProfileOtpCreate(CreateAPIView): queryset = LenderOtp.objects.all() serializer_class = LenderProfileOtpSerializer authentication_classes = [SessionAuthentication] def perform_create(self, serializer): serializer.save(user=self.request.user) This is giving me a type error, I want link the otp to lenderprofile and same time the same user should do be able to perform it, please help to solve this, thank you in advance. -
`ImportError: No module named settings.postgres` when trying to deploy Django on Heroku
I'm trying to deploy my own instance of readthedocs.org on Heroku, and I am having a little bit of trouble getting the settings right. Heroku crashes with Error H10 every time: 2016-10-12T07:03:24.448237+00:00 app[web.1]: self._wrapped = Settings(settings_module) 2016-10-12T07:03:24.448237+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/django/conf/__init__.py", line 92, in __init__ 2016-10-12T07:03:24.448238+00:00 app[web.1]: mod = importlib.import_module(self.SETTINGS_MODULE) 2016-10-12T07:03:24.448239+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/importlib/__init__.py", line 37, in import_module 2016-10-12T07:03:24.448239+00:00 app[web.1]: __import__(name) 2016-10-12T07:03:24.448240+00:00 app[web.1]: ImportError: No module named settings.postgres 2016-10-12T07:03:24.448241+00:00 app[web.1]: Traceback (most recent call last): 2016-10-12T07:03:24.448241+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/arbiter.py", line 507, in spawn_worker 2016-10-12T07:03:24.448242+00:00 app[web.1]: worker.init_process() 2016-10-12T07:03:24.448242+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/workers/base.py", line 114, in init_process 2016-10-12T07:03:24.448243+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2016-10-12T07:03:24.448244+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/app/base.py", line 66, in wsgi 2016-10-12T07:03:24.448244+00:00 app[web.1]: self.callable = self.load() 2016-10-12T07:03:24.448245+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 65, in load 2016-10-12T07:03:24.448246+00:00 app[web.1]: return self.load_wsgiapp() 2016-10-12T07:03:24.448246+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp 2016-10-12T07:03:24.448247+00:00 app[web.1]: return util.import_app(self.app_uri) 2016-10-12T07:03:24.448247+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/util.py", line 356, in import_app 2016-10-12T07:03:24.448248+00:00 app[web.1]: __import__(module) 2016-10-12T07:03:24.448249+00:00 app[web.1]: File "/app/readthedocs/wsgi.py", line 9, in <module> 2016-10-12T07:03:24.448249+00:00 app[web.1]: application = get_wsgi_application() 2016-10-12T07:03:24.448250+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/django/core/wsgi.py", line 14, in get_wsgi_application 2016-10-12T07:03:24.448250+00:00 app[web.1]: django.setup() 2016-10-12T07:03:24.448251+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/django/__init__.py", line 17, in setup 2016-10-12T07:03:24.448252+00:00 app[web.1]: configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) 2016-10-12T07:03:24.448252+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/django/conf/__init__.py", line 48, in __getattr__ 2016-10-12T07:03:24.448253+00:00 app[web.1]: self._setup(name) 2016-10-12T07:03:24.448254+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/django/conf/__init__.py", line 44, in … -
How to rename (exposed in API) filter field name using django-filters?
As the question states - I'm trying to rename the filter field name exposed in my API. I have the following models: class Championship(Model): ... class Group(Model): championship = ForeignKey(Championship, ...) class Match(Model): group = ForeignKey(Group, ...) I have exposed all of these models in REST API. I've defined filter_fields for the Match model: class MatchViewSet(ModelViewSet): filter_fields = ['group__championship'] ... This way, I can filter for specific championship's matches (tested and working): curl /api/matches/?group__championship=1 Is is possible to use some kind of alias for the exposed filter so I can use the following: curl /api/matches/?championship=1 where championship in this case will be an alias for group__championship? pip freeze returns: django-filter==0.15.2 (...) I've also tried implementing custom FilterSet with ModelChoiceFilter and custom lookup method: class MatchFilterSet(FilterSet): championship = ModelChoiceFilter(method='filter_championship') def filter_championship(self, queryset, name, value): return queryset.filter(group__championship=value) class Meta: model = Match fields = ['championship'] With view: class MatchViewSet(ModelViewSet): filter = MatchFilterSet (...) But with no luck. The filter_championship method was neveer called. -
Dependency from django app to jquery plugin
I write a reusable django app. This app uses the are-you-sure jquery library. Goal Installing my app with all dependencies should be easy. Use Case If a developer wants to use my app, then the following line should install the whole app (including the are-you-sure plugin): pip install myreusableapp Question What is the common solution to pull in this dependency? Not part of the question Depedencies to other python code gets done via install_requires in setup.py. Works fine. Pushing my django code to pypi is not part of the question. Works fine. -
Saving images with pixels in django
I want to save images with specific pixels, when someone uploads image on django models it will be resized and then save according to id.I want them to be saved in path product/medium/id.I have tried defining path in it which saves image but not on path i want here is my models.py class Product(models.Model): product_name = models.CharField(max_length=100) product_description = models.TextField(default=None, blank=False, null=False) product_short_description = models.TextField(default=None,blank=False,null=False,max_length=120) product_manufacturer = models.CharField(choices=MANUFACTURER,max_length=20,default=None,blank=True) product_material = models.CharField(choices=MATERIALS,max_length=20,default=None,blank=True) No_of_days_for_delivery = models.IntegerField(default=0) product_medium = models.ImageField(upload_to='product/id/medium',null=True,blank=True) def save(self, *args, **kwargs): self.slug = slugify(self.product_name) super(Product, self).save(*args, **kwargs) Now on this i want to resize image get there id and save in path product/medium/id/image.jpg Please help me... Thanks in advance -
Django print passed parameters in class based views
I'm unable to print passed parameters to Django console. class ProjectCreateView(CreateView): model = Project form_class = ProjectForm def form_valid(self, form): print form.cleaned_data['name'] return super(ProjectCreateView, self).form_valid(form) Documentation here suggest to use ModelFormMixin def form_valid(self, form): """ If the form is valid, save the associated model. """ self.object = form.save() return super(ModelFormMixin, self).form_valid(form) Any ideas? -
Django model choice field Select a valid choice. That choice is not one of the available choices
I have a model choice field(Many to many relation), When I try to submit the form it throws an error Select a valid choice. That choice is not one of the available choices. I have also added in forms __init__ but still facing same error. I think the error is due to string, integer in checkbox value. Can anyone help me to fix this one. Posting my code here class CustomSignupForm(forms.ModelForm): telephone = forms.CharField(label=_('Telephone'), required=False) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(CustomSignupForm, self).__init__(*args, **kwargs) self.fields['categories'] = forms.ModelChoiceField(queryset=Category.objects.filter(status=True), widget=forms.CheckboxSelectMultiple) for name, field in self.fields.iteritems(): attr = {'class': 'custom-class'} if field.label: attr['placeholder'] = field.label field.widget.attrs.update(attr) Categories is the field with many to many selection, which is not allowing me to submit the form. -
Fix flask "python manage.py db migrate" causing error
When i run "python manage.py db migrate" after "python manage.py db init" it raises error "File "migrations/env.py", line 23, in target_metadata = current_app.extensions['migrate'].db.metadata AttributeError: 'module' object has no attribute 'metadata'" I am using sqlalchemy and postgresql Do anyone know how to fix this? -
What is the following error and how to solve this
django.db.utils.OperationalError: (com_error(-2147352567, 'Exception occurred.', (0, 'ADODB.Connection', 'Provider cannot be found. It may not be properly installed.', 'C:\Windows\HELP\ADO270.CHM', 1240655, -2146824582), None), 'Error opening connection: DATA SOURCE=192.168.0.69,1434;Network Library=DBMSSOCN;Initial Catalog=test;UID=sa;PWD=******;PROVIDER=sqlncli10;DataTypeCompatibility=80;MARS Connection=True') -
How to store list of objects that have different properties in django db?
It is straightforward to store in mysql data like [ { 'name': 'Object1', 'color': 'red', 'shape': 'ellipse' }, { 'name': 'Object2', 'color': 'green', 'shape': 'circle' } ] But what if object has different number of attributes (attributes are flat, they are not nested)? [ { 'name': 'Object1', 'color': 'red', 'shape': 'ellipse', 'eccentricity': 0.5 }, { 'name': 'Object2', 'color': 'green', 'shape': 'circle' 'radius': 5 } ] There are many attributes, so sub-classing is not solution. How do I handle it in mysql? Or if this is not possible, maybe postgresql? What about non-relational databases, what is the best to use? I need to make queries based on those attributes. Thanks in advance. -
overwrite attribute as function Django
I have class A(models.Model) with attr name. I use it in template and view as obj_a.name. I need overwrite name attr as function and when I write obj_a.name I would get response from function getName. How can I do it in Django and Python ? In Laravel PHP it is $this->getNameAttribute() and I can overwrite returning name from object. Name is only example and I want use it with almost all attr given class. -
How to do first migration in flask?
Hello i am working on an new project which is already developed in flask and i have no knowledge in flask. My company gave the project to me because i have Django experience. this is the structure of the project. models -db.py -model1.py -model2.py - .. static - .. templates - .. myapp.py myapp.py contain all config files and server init code with all other functionality like for home page and sign up page. when i run pyhton myapp.py its running good but the tables are not created automatically ( i found that first migration has to be done ) i have no idea how to do it. the project make use of postgresql and SQLAlchemy form flask_sqlalchemy Modules. db.py file contain from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() all model has from db import db myapp file contain # =================================================================== # SQL ALCHEMY # =================================================================== if (SERVER_MODE == RUN_MODE.PRODUCTION): app.config['SQLALCHEMY_DATABASE_URI'] = ( os.environ["DATABASE_URL"] ) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False else: app.config['SQLALCHEMY_DATABASE_URI'] = ( 'postgresql://' + 'creathiveswebapp:creathives' + '@' + 'localhost/cl_creathives_pgdb' ) app.config['SQLALCHEMY_ECHO'] = False app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True db.init_app(app) and ... # =================================================================== # START SERVER # =================================================================== if __name__ == "__main__": port = int(os.environ.get('PORT', 5000)) if (SERVER_MODE == RUN_MODE.PRODUCTION): # TODO: … -
Django migrate and makemigrate automatic yes on prompt
Is there a way to automatically specify YES as the default option on manage.py makemigrations myAPp and manage.py migrate commands i tried the --noinput option on migrate but i think it defaults to NO not YES -
gunicorn "configuration cannot be imported"
I'm migrating a project that has been on Heroku to a DO droplet. Install went smoothly, and everything is working well when I python manage.py runserver 0.0.0.0:8000. I'm now setting up gunicorn using these instructions: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-14-04 I activate the virtual environment, and then try --bind 0.0.0.0:3666 myproject.wsgi:application. I get the following error: Traceback (most recent call last): File "/var/www/myproject/venv/local/lib/python2.7/site-packages/gunicorn/arbiter.py", line 515, in spawn_worker worker.init_process() File "/var/www/myproject/venv/local/lib/python2.7/site-packages/gunicorn/workers/base.py", line 122, in init_process self.load_wsgi() File "/var/www/myproject/venv/local/lib/python2.7/site-packages/gunicorn/workers/base.py", line 130, in load_wsgi self.wsgi = self.app.wsgi() File "/var/www/myproject/venv/local/lib/python2.7/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/var/www/myproject/venv/local/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 65, in load return self.load_wsgiapp() File "/var/www/myproject/venv/local/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp return util.import_app(self.app_uri) File "/var/www/myproject/venv/local/lib/python2.7/site-packages/gunicorn/util.py", line 357, in import_app __import__(module) File "/var/www/myproject/myproject/wsgi.py", line 6, in <module> from configurations.wsgi import get_wsgi_application File "/var/www/myproject/venv/local/lib/python2.7/site-packages/configurations/wsgi.py", line 3, in <module> importer.install() File "/var/www/myproject/venv/local/lib/python2.7/site-packages/configurations/importer.py", line 54, in install importer = ConfigurationImporter(check_options=check_options) File "/var/www/myproject/venv/local/lib/python2.7/site-packages/configurations/importer.py", line 73, in __init__ self.validate() File "/var/www/myproject/venv/local/lib/python2.7/site-packages/configurations/importer.py", line 122, in validate raise ImproperlyConfigured(self.error_msg.format(self.namevar)) ImproperlyConfigured: Configuration cannot be imported, environment variable DJANGO_CONFIGURATION is undefined. My wsgi.py looks like this: # -*- coding: utf-8 -*- import os from configurations.wsgi import get_wsgi_application application = get_wsgi_application() I didn't set up the project initially, so I'm not sure what is different, or where to look. -
using urls in ModelViewSet
I practice in Django REST Framework, and can't figure out how to use urls in ModelViewSet. When i go to url of certain ViewSet i can see this line: Allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS How can i use this this methods, if i have urls only for detail and list: ^api/ ^ ^photos/$ [name='photo-list'] ^api/ ^ ^photos.(?P[a-z0-9]+)/?$ [name='photo-list'] ^api/ ^ ^photos/(?P[^/.]+)/$ [name='photo-detail'] ^api/ ^ ^photos/(?P[^/.]+).(?P[a-z0-9]+)/?$ [name='photo-detail'] And if i can use only this methods, when will be called perform_create method? My ViewSet: class PhotoViewSet(viewsets.ModelViewSet): queryset = Photo.objects.all() serializer_class = PhotoSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,) def perform_create(self, serializer): if serializer.owner.is_authenticated(): serializer.save(owner=self.request.user) else: raise ValidationError('User not authenticated') My Serializer: class PhotoSerializer(serializers.HyperlinkedModelSerializer): album = serializers.HyperlinkedRelatedField(view_name='album-detail', queryset=Album.objects) owner = serializers.HyperlinkedRelatedField(view_name='user-detail', queryset=User.objects) class Meta: model = Photo fields = ('pk', 'name', 'image', 'creation_date', 'owner', 'album') read_only_fields=('creation_date') -
Django join on multiple foreign fields (left join)
I'm using django 1.10 and have the following two models class Post(models.Model): title = models.CharField(max_length=500) text = models.TextField() class UserPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) approved = models.BooleanField(default=False) How do I get a list of all the posts including the 'approved' property for the logged in user if exists? So instead of multiple queries, it would be one left join query, pseudo-code: select * from posts as p left join user_posts as up on up.post_id = p.post_id and up.user_id = 2 Output post_id | title | text | user_id | approved 1 | 'abc' | 'abc' | 2 | true 2 | 'xyz' | 'xyz' | null | null 3 | 'foo' | 'bar' | 2 | true I created the models this way because the 'approved' property belongs to the user. Every user can approve/reject a post. The same post could be approved and rejected by other users. Should the models be setup differently? Thanks