Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 1.8-1.11 upgrade error, AttributeError: type object 'DemoModel' has no attribute 'lower'
I am upgrading my app from Django 1.8 to 1.11. When I try to run migrations or tests I am getting the following error. On debugging I can see that method is_referenced_by_foreign_key is expecting f.related_model to be string, but in my case its actually an instance. Can some one please help with this. ipdb> c Traceback (most recent call last): File "formtastic/manage.py", line 11, in <module> execute_from_command_line(sys.argv) File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/core/management/commands/test.py", line 29, in run_from_argv super(Command, self).run_from_argv(argv) File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/core/management/commands/test.py", line 62, in handle failures = test_runner.run_tests(test_labels) File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/test/runner.py", line 601, in run_tests old_config = self.setup_databases() File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/test/runner.py", line 546, in setup_databases self.parallel, **kwargs File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/test/utils.py", line 187, in setup_databases serialize=connection.settings_dict.get('TEST', {}).get('SERIALIZE', True), File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/db/backends/base/creation.py", line 69, in create_test_db run_syncdb=True, File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/core/management/__init__.py", line 131, in call_command return command.execute(*args, **defaults) File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 163, in handle pre_migrate_state = executor._create_project_state(with_applied_migrations=True) File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/db/migrations/executor.py", line 81, in _create_project_state migration.mutate_state(state, preserve=False) File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/db/migrations/migration.py", line 92, in mutate_state operation.state_forwards(self.app_label, new_state) File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/db/migrations/operations/fields.py", line 209, in state_forwards not … -
Change button on "<a>" element. Bootstrap 4, html, Django
I am trying to add logout options in my bootstrap menu. After adding, an awful uneven button is created (as in the picture below). How to add the logout form below so that you do not create such a button. <form method="post" action="{% url 'account_logout' %}"> {% csrf_token %} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}"/> {% endif %} <button type="submit">{% trans 'Sign Out' %}</button> </form> My template.html <div class="dropdown-menu dropdown-menu-sm dropdown-menu-right"> <h6 class="dropdown-header">Menu użytkownika</h6> <a class="dropdown-item" href="#"> <i class="fas fa-user"></i>Ustawienia konta </a> <a class="dropdown-item" href="#"> <span class="float-right badge badge-primary">4</span> <i class="fas fa-car"></i>Ogłoszenia </a> <a class="dropdown-item" href="#"> <span class="float-right badge badge-warning">2</span> <i class="far fa-times-circle"></i>Zakończone </a> <!-- I try change this element on my hidden log out form--> <div class="dropdown-divider" role="presentation"></div> <a class="dropdown-item" href="#"> <i class="fas fa-sign-out-alt">Log out</i> </a> </div> Any help will be appreciated -
Django login() doesn't persist after HttpResponseRedirect
I have custom Django login forms that, since upgrading from Django 1.8 to 2.2, no longer keep user logged in after HttpResponseRedirect. Here's is a generalized sample of the code: @render_with('users/login.html') def login_view(request, campaign_id=None): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] password = form.cleaned_data['password'] # Login user user = authenticate(request, email=email, password=password) if user: if user.is_active: login(request, user) return HttpResponseRedirect('/redirect-user/') I know that login() is working properly because if I use render instead of HttpResponseRedirect, the user is logged in. However, I want to redirect the user to a different view after login. What is the best way to do this? -
From views, how do I pass both context and registration form to my registration template?
I'm fairly new to Django and I'm trying to pass both the context and my registration form. I know how to pass either the context, or the form, but not both. Check the last line of the code, that's what I'm trying to figure out. I've tried: return render(request, 'users/register.html', context, {'form': form}) and it doesn't work. There's something wrong with the syntax. from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegisterForm def register(request): context = { 'title': "Register", 'page_title': "Golf App - Register", 'login_title': "Login" } if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account Created for {username}!') return redirect('golf-home') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) I'm trying to get it so that I can use both the context and form in the template. -
How can I find the hostname and port in the settings django for the full path of the image to be displayed in the email?
So I am trying to give the absolute path for the static folder. Can you point what I am doing wrong? My template looks like <img src="{{ALLOWED_HOSTS}}{% static 'assets/img/logo-ST.png' %}" alt="logo" border="0" width="102"> And in the Settings ALLOWED_HOSTS = env.list('DJANGO_ALLOWED_HOSTS', str) I know I'm doing something wring with the hostname and port, can you please help? -
How to solve the problem of Application labels aren't unique, duplicates: users?
I am trying to makemigrations but it is giving me problem but where are duplicates? settings.py AUTH_USER_MODEL = 'users.User' INSTALLED_APPS = [ 'django.contrib.admin', 'users.apps.UsersConfig', 'firstapp.apps.FirstappConfig', 'crispy_forms', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users' ] admin.py admin.site.register(User) models.py from django.contrib.auth.models import AbstractUser from django import forms class User(AbstractUser): Id_card_number = forms.CharField(max_length=15, required=True) -
Django- Dependent Dropdown Form results in "invalid choice" on POST
I'm using this tutorial: https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html to add a dependent dropdown to my form, but when I post the data it comes back form invalid with an invalid choice error. In my form's init override, if I eliminate the dropdown queryset then it works, but that defeats the purpose. My view: def add_have(request, id=None): if request.method == "POST": print("User: {}".format(request.user)) for key, value in request.POST.items(): print('{}: {}'.format(key, value) ) form = HaveForm(request.POST) if form.is_valid(): model_instance = form.save(commit=False) model_instance.profile = request.user model_instance.save() else: print(form.errors) print("FORM IS INVALID") return redirect('display_have_list') else: form = HaveForm() return render(request, 'add_have.html', {'form': form}) My form: class HaveForm(forms.ModelForm): class Meta: model = Have fields = ['category', 'item'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['category'].queryset=Category.objects.all() self.fields['item'].queryset = Items.objects.none() The error message I'm getting implies that it's not loading the item: web_1 | User: <my_username> web_1 | csrfmiddlewaretoken: <my_token> web_1 | category: 1 web_1 | item: 4496 web_1 | <ul class="errorlist"><li>item<ul class="errorlist"><li>Select a valid choice. That choice is not one of the available choices.</li></ul></li></ul> web_1 | FORM IS INVALID web_1 | [31/Jul/2019 09:01:24] "POST /trade/add_have/ HTTP/1.1" 302 0 web_1 | [31/Jul/2019 09:01:24] "GET /trade/display_have_list/ HTTP/1.1" 200 2638 web_1 | [31/Jul/2019 09:01:24] "GET /static/css/styles.css HTTP/1.1" 404 1767 If I elimitante the … -
Is it possible to set up a web app that runs a Python script on a schedule?
I have no experience in web app development, but I want to make a project like the following: My school dorm requires you to make a leave request online on Monday in order to leave the dorm on the weekends. My friends and I always forget to do this. I want to make a web app that basically if the user inputs their information, it would automatically make a leave request every Monday for that user. I have a leave request script written, and I'm sure I can figure out how to make a website and store user data in the database. My question is, is it possible in a Django web app to schedule a script to run once every week? I'm planning on deploying to Heroku, would I have to schedule it in Heroku or Django? If this isn't possible in Django, what would I use in order to go about implementing it? I'm sorry for such a vague question, I'm just not sure where to start and I'm very new to web app development. Any help is appreciated! -
How to create modal signup form in Django?
Home Page Screen Shot Modal Screen Shot I'm fairly new to Django so not sure how to solve my problem. I've created a simple UserCreationForm in a view function to sign up new users. However, I can't seem to display the form in a boostrap modal or in my index.html template. I'm thinking by creating a separate view for the sign up form I need to have a separate template and url path to register new users. I'd like to have the sign up modal on the home page and not direct the user to a separate signup page. {% extends "myapp/base.html" %} {% block navbar %} <li class="nav-item active"> <a class="nav-link" href="#"> Home <span class="sr-only">(current)</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="#">Log In</a> </li> <li class="nav-item"> <a class="btn btn-primary nav-item" href="#" role="button" data-toggle="modal" data-target="#myModal"> Sign Up </a> </li> <!-- The Modal --> <div class="modal fade" id="myModal"> <div class="modal-dialog"> <div class="modal-content"> <!-- Modal Header --> <div class="modal-header"> <h4 class="modal-title">Sign Up</h4> <button type="button" class="close" data-dismiss="modal"> &times; </button> </div> <!-- Modal body --> <div class="modal-body"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Join today</legend> {{ form.as_p }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Sign Up</button> </form> <div class="border-top pt-3"> <small … -
How to: Run Django Project in Subpath
Okay, so I'd like to start by saying that I am not running NGINX like many of the other questions I've seen.I'm running Gunicorn alongside Whitenoise. My task is to implement scientific plots in a separate directory of an existing website. My problem is getting the django project to not run in the root directory of the website. I need it to run in a directory like 'example.com/app',so that I can call the plotting application from there as opposed to the main webpage. I tried changing the application urls.py to say 'example.com/app/pretty_plots' and navigating to the page that way, but it fails to load all of the resources. Everything works as expected if I change the web access path of the app to '/' (eliminating the original homepage), and navigating to example.com/pretty_plots, but I'd like to leave the home page intact. FORCE_SCRIPT_NAME = '/app' did not do the trick for me either. URLConf mysite/urls.py from django.contrib import admin from django.urls import path, include import plots.plotly_apps urlpatterns = [ path('admin/', admin.site.urls), path('plots/', include('plots.urls')), path('django_plotly_dash/', include('django_plotly_dash.urls')), ] The above code works from the root, but not anywhere else. I see no options of configuring Whitenoise to run Django from a subpath. The … -
MultichoiceField in ModelForm for Django with DB relations
This is my first post ever on Stackoverflow so please ignore mistakes. Before posting I had tried a dozen solutions bun none worked. I have table relations in models for users. I need to create a ModelForm to let customer select multiple users for any project from the frontend. I am having hard time implementing it in code. Also for another field I need to limit the choice to one user. Following is the code. Models: class Project(models.Model): project_name = models.CharField(max_length=100) project_users = models.ManyToManyField(User) project_team_lead = models.OneToOneField(User, on_delete=models.CASCADE, related_name='lead') def init(self): return str(self.project_name) Form. class ProjectForm(forms.ModelForm) class Meta: fields = ['project_name', 'project_users', 'project_lead'] View: def projects(request): template = 'projects/projects.html' if request.method == 'POST': form = ProjectForm(request.POST) if form.is_valid(): form.save() else: form = ProjectForm() return render(request, template, {'form': form}) HTML: <form action='' method='post'> {% csrf_token %} {{ form }} <button type='submit' class='btn btn-primary'>Submit</button> </form> Some help is highly appreciated. -
Django/Python how to define different required fields for different actions?
I can't figure out the "best" way (or the way with least cons) to do this. For example I have a Realestate model and FlatProfile which has a ForeignKey to the Realestate. There are some actions in the system which can or cannot be done according to filled (not null) fields. For example, to be visible on presentation page, the fields name,seller,flatprofile.rooms_count must be filled. On the other hand, to be in a list of Realestates on brochure, different set of fields has to be filled and this set can contain even related fields like flatprofile.rooms_count. My solution: I define two methods on Realestate model. def can_be_on_presentation(self): lst = ["name","seller","flatprofile__rooms"] for fieldname in lst: # check if the field is not null # if null raise Exception Is there a built in way or some pattern to do such thing? This has many cons like the fields are in string format so static analysis won't show error if there is no such field etc... -
How i can register on Django admin a field for upload of files
I'm trying use a lib boto3 for upload files in django admin, but i dont think i doing this correctly. I'm trying to create a form class, and use it inside admin to upload This my forms.py from django import forms from django.conf import settings from .models import Invoice import boto3 from botocore.exceptions import ClientError class InvoiceForm(forms.ModelForm): file = forms.FileField(label='Arquivo', required=False) class Meta: fields = '__all__' model = Invoice def upload(): s3 = boto3.client('s3') try: s3.upload_fileobj(file, settings.UPLOAD_BUCKET) except ClientError as e: logging.error(e) return False return True And this my admin from .forms import InvoiceForm class InvoicesAdmin(admin.ModelAdmin): search_fields = ['name', 'user'] list_display = ['name', 'user','value', 'installment', 'due_date', 'status', 'file'] exclude = ['updated_by', 'created_by', 'attributes'] autocomplete_fields = ['user'] form = InvoiceForm admin.site.register(models.Invoice, InvoicesAdmin) I don't get an error, but the file is not saved to aws-s3 -
What is the format for strptime() to get datetime objects serialized in DjangoJSONEncoder()?
I didn t manage to get datetime objects from strings generated from dates serialized through DjangoJSONEncoder() The problematic part is the timezone with +HH:MM (as defined in ECMA-262). I don't see the strptime equivalent in http://strftime.org/ I only see %z for "+HHMM" and %Z for time zone name. Code : d = DjangoJSONEncoder().encode(localtime(now())) print(d) # "2019-07-31T16:48:19.665+02:00" import datetime d_no_timezone="2019-07-31T17:04:00.282" datetime.datetime.strptime(d_no_timezone, '%Y-%m-%dT%H:%M:%S.%f') d # "2019-07-31T17:04:00.282+02:00" datetime.datetime.strptime(d, '%Y-%m-%dT%H:%M:%S.%f%z') #ValueError, does not match format datetime.datetime.strptime(d, '%Y-%m-%dT%H:%M:%S.%f%Z') #ValueError, does not match format datetime.datetime.strptime(d, '%Y-%m-%dT%H:%M:%S.%fz') #ValueError, does not match format datetime.datetime.strptime(d, '%Y-%m-%dT%H:%M:%S.%fZ') #ValueError, does not match format PS : using Python 3.6.8 and Django 2.2.3. -
How to point Django app to new DB without dropping the previous DB?
I am working on Django app on branch A with appdb database in settings file. Now I need to work on another branch(B) which has some new DB changes(eg. new columns, etc). The easiest for me is to point branch B to a different DB by changing the settings.py and then apply the migrations. I did the migrations but I am getting error like 1146, Table 'appdb_b.django_site' doesn't exist. So how can I use a different DB for my branchB code without dropping database appdb? -
create a form and model to rate countries
I am new to django and I work on data science project, that require to rate some countries by users , how I can do it ? some thing like that -
My comment system in Django is not working as expected
I'm creating an application where a user can create their own posts, and other users can comment on the posts. I have already tried retrieving comments from the database, and displaying them for that certain post, however this has been unsuccessful Here is my code to tackle this problem: views.py def comment(request, pk): form = CommentForm() comments = Comment.objects.filter(post=pk) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = Comment() comment.body = form.cleaned_data['body'] comment.user = request.user comment.post = Post.objects.get(pk=pk) comment.save() return redirect('home') return render(request, 'posts/comments.html') else: return render(request, 'posts/comments.html', {'error': 'Please submit valid data'}) else: return render(request, 'posts/comments.html', {'form': form}, {'comments': comments}) comments.html {% block content %} <div class="container"> {% for com in comments.all %} <p>{{ com.body }}</p> <br> {% endfor %} {% if error %} {{ error }} <br> <br> {% endif %} <br> <br> <br> <br> <br> <form method="post"> <h2> Comment</h2> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-primary"> Comment</button> </form> </div> {% endblock %} models.py class Comment(models.Model): body = models.CharField(max_length=130) user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) def __str__(self): return self.body This is expected to display a posts comments when a button is pressed to view the post, however the comments do not … -
What the best way to pass in a user-facing attribute and print it in html?
When my errors get caught by is_valid() in django, I print them in html. I'd like to add a friendly user-facing html title that prints along with the error so they know which form is invalid. I thought I could just add a custom attribute and print it, but the only attribute html can print is "name" for some reason. Django abstracts it away, but in this case the "name" attribute in the html object = end_date. I'd just like to print the "friendly" attribute but html prints nothing instead. Here is the form declaration: end_date = forms.DateField(widget=forms.TextInput(attrs={'id':"datepicker", 'autocomplete':"off", 'friendly':"End Date"}), required=True) Here is the un-abstracted html for this object that gets printed on the page error reload, you can see "End Date" right there, but it is still null on the page: <tr><th><label for="datepicker">End date:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input autocomplete="off" friendly="End Date" id="datepicker" name="end_date" type="text" /></td></tr> The error printing. {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="alert alert-danger"> <strong>{{ field.name }}: {{ error|escape }} </strong></strong> </div> {% endfor %} {% endfor %} {% for error in form.non_field_errors %} <div class="alert alert-danger"> <strong>{{ error|escape }} </strong> </div> {% endfor %} … -
DRF: Making external requests and building serializers
I'm using Django rest framework and on a POST request need to make an external request to a SOAP server which outputs weather reports. I receive something like this to my API { 'city': 'Manchester', 'country': 'GB', 'locality': 'EU' } Now this is the data I get. Serializing this data is fine and I get that. However since the SOAP address requires me to make a request within the following format I get confused. I haven't really tried anything but looking for a best solution in this. { 'geopgrahpy': { 'country': 'GB', 'city': 'Manchester', }, 'locality': 'EU', 'userID': '123', 'password': 'xxxxx' } My question is what would be the best solution? Manually building a util function which will return the userID, password (from the request) or build another serializer matching to the soap server needs. Also bear in mind I know SOAP is XML but the Zeep library converts it to and from XML. -
twilio multi factor authentication - Django Python
I am trying to implement a multi factor authentication on my Django web app , I went over some guides and answers but i am still confused , I want that after a user is login with his user name and password to have another step where he will get an SMS with one time token he will put it in the login and then he will be able to continue to the web app. I opened an account on Twillo , but here i got confused , in some example you need Authy and in some you dont ,i installed the Django OTP and Django two factor Auth , and i wasnt be able to bind them all together . Will relay appreciate an explanation on the different terms and how to bind them together. Thanks, Nir -
How to deserialize dates saved into Django s
I came across the “datetime.datetime not JSON serializable” error and wanted a clean Django solution for it So I tried to use DjangoJSONEncoder, but I didn t manage to deserialize the data after serializing it (I want to store it in a JSONField). I get a DeserializationError. What am I doing wrong ? This is what I came up so far : from django.utils.timezone import localtime, now from django.core.serializers.json import DjangoJSONEncoder from django.core.serializers import deserialize a = DjangoJSONEncoder().encode(localtime(now())) print(a) # "2019-07-31T16:48:19.665+02:00" b = deserialize("json",a) print(b) # <generator object Deserializer at 0x0000006CD0F35A40> for c in b : print(c) # django.core.serializers.base.DeserializationError PS : using Python 3.6.8 and Django 2.2.3. -
How to use TinyMCE 5 with Django?
There are no packages to support TinyMCE 5 for Django. The only available packages are version 3 or 4. I tried this guide https://www.tiny.cloud/docs/quick-start/ TinyMCE forms use native HTML and you have initialized it with javascript but Django forms work a different way. You have to make them in Views and I'm not that advanced to modify it. How should I go about that? -
Django query ValueError: hour must be in 0..23
I'm making a query through Django querysets and it's returning "ValueError: hour must be in 0..23" filtering the dates: In models.py: class handoff_model(models.Model): batch = models.ForeignKey(batch_def_model, on_delete=models.CASCADE) date = models.DateField(blank=True, null=True) class batch_def_model(models.Model): name = models.CharField(max_length=200) start_time = models.TimeField(blank=True, null=True) In views.py: def ho_open(request): date = '2019-07-29' all_b = batch_def_model.objects.all() for b in all_b: if not handoff_model.objects.filter(date=date, batch=b.name).exists(): batch = handoff_model(batch=b, date=date) batch.save() handoff_list = handoff_model.objects.filter(date=date,batch__start_time__lt='08:00') return handoff_list I already have a few "batch_def_model" objects in my database. Every time you run "ho_open" (changing the hardcoded date) it should create the handoff_models same as "batch_def_model" but for the hardcoded date. When I set the date as "2019-07-29" it works correctly. Whith date as "2019-07-30" or "2019-07-31" I get the following error: File "/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 151, in typecast_time return datetime.time(int(hour), int(minutes), int(seconds), int((microseconds + '000000')[:6])) ValueError: hour must be in 0..23 I'm not sure why it's not working with those dates because the entire month is working correctly. I've tested by filtering with date__contains=date without success. Do you have any hint? -
Why do the fields of the selected form return the value "none" and "null" in the database?
I am trying to save a value in the field 2 fields, but when saving them I change the value to "none" and in the db also in the field it shows me "null" I have tried to change the parentheses by the square brackets, seeing if the 2 values of the form are taken to the database, but I don't quite understand the difference between "form.cleaned_data () and form.cleaned_data []", but by doing so with the square brackets, it sends me an error my views.py def solit(request): if request.method == 'POST' and request.is_ajax(): form = addiForm(request.POST) if form.is_valid(): peticion = form.save(commit=False) peticion.usuario = request.user peticion.save() peticion.usuario.d_pendientes = form.cleaned_data.get('d_pendientes') peticion.usuario.h_pendientes = form.cleaned_data.get('h_pendientes') peticion.usuario.save() print (peticion.usuario.d_pendientes) print (peticion.usuario.h_pendientes) return JsonResponse({'status': 'true', 'msg': 'Procesado Correctamente'}) else: return JsonResponse({'status': 'false', 'msg': 'Los datos no son validos'}) form = addiForm() return render(request, 'plantillas/adicionar.html', {'form':form}) my models.py class Usuarios(AbstractUser): numero_empleado = models.IntegerField(null= True, blank= True) area = models.CharField(max_length = 200, null= True, blank= True) d_pendientes = models.IntegerField(null= True, blank= False) h_pendientes = models.IntegerField(null= True, blank= False) f_init = models.DateField(max_length = 200,null= True, blank= True) init_vac = models.DateField(max_length = 200, null= True, blank= True) fin_vac = models.DateField(max_length = 200, null= True, blank= True) ul_vac_tomadas = models.IntegerField(null= … -
Django: M2M database annotation query
Given the following models: User -------- Thread -------- Post -------- thread: ForeignKey(Thread) read_by: ManyToManyField(User) Now, I would like to retrieve all posts for a specific thread annotated if they are read by the currently logged in user. So, I start with fetching the posts: Post.objects.filter(thread=self.thread) Now, I am not sure how I can annotate with the read/unread flag set to True/False. The currently logged in user is available using the variable self.request.user.