Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django retrieving data from two model with foreign key
I'm just new with django programming and I'm having this designed models class Client(models.Model): lastname = models.CharField(max_length=255) firstname = models.CharField(max_length=255) middlename = models.CharField(max_length=255) accountant = models.ForeignKey(User, on_delete=models.DO_NOTHING) def __str__(self): return self.lastname + ' ' + self.firstname + ' ' + self.middlename + ' | ' + str(self.accountant) + ' | ' + str(self.id) def get_absolute_url(self): return reverse('home') class Consultation(models.Model): accountant = models.ForeignKey(User, on_delete=models.DO_NOTHING) clientid = models.ForeignKey(Client, on_delete=models.DO_NOTHING) concern = models.CharField(max_length=255) def __str__(self): return str(self.clientid) + ' | ' + str(self.accountant) def get_absolute_url(self): return reverse('client_details.html') and my problem is in views with this code def ConsultationUpdateView(request, pk): consultation = Consultation.objects.filter(id=pk) client = Client.objects.filter(id=consultation.clientid) return render(request, 'client_consultationupdate.html', {'client':client, 'consultation':consultation}) First one is, as per checking with the retrieve "consultation" values it had this <QuerySet [<Consultation: Chad Milky Sugar | will | 1 | will>]> and there's no "concern" field in this queryset, is this why "concern" field value not appearing in my HTML page? If so how can I pass the concern field value to the page? (BTW, I'm working now with editing part that's why I need to pass the "concern" field value to the page) {% extends 'base.html' %} {% block title %}Update Concern{% endblock %} {% block content %} … -
Sending email with HTML support from user input with Django
I am creating a form where users can input HTML and a email address and it will send a email. Right now I am just using a TextArea to let users put in any text. This doesn't support HTML but now I want to support HTML. I have looked at some solutions and they all involve reading in a template file. If I did that then I would need a way for the user to edit the template file. Is it possible to just take a string that contains HTML and send like that? I tried throwing in some HTML tags and it just prints it as plain text in the email that I receive. -
Stuck at Integrating Multiple Django databases
I'm new to Django but can't seem to find my way around this challenge. Scene: I have a new Django project I want to use as an API I have my default database setup and works perfectly when I try to view the tables in my admin panel (Only table present is the user's table) So I have another database that I want to integrate into the project. It's populated already and I won't be writing data into it just reading data from it. I have been able to add the database to my database list in settings.py, I have also run inspectdb and my models have been generated i have done my migrations and i can view the model objects from shell command. Challenge So i have the models registered in my admin.py file and I can find the two generated tables in the admin panel when i login but when i try to click on it to view it gives me an error that the table doesn't exist. I was able to deduce the problem to be that when i try to open any of those two generated tables in the admin panel, Django searches for those tables … -
Django: Exception Type: IntegrityError UNIQUE constraint failed: auth_user.username
I am new to Django, and trying to create a registration app where account is activated upon email verification. I read previous posts, but there seems to be unique reasons for this error. I cannot figure out what is causing this error in my case. Can someone troubleshoot this for me, or point me in the right direction? from django.shortcuts import render, redirect from django.urls import reverse_lazy from django.views.generic import View, UpdateView from .forms import SignUpForm from django.contrib import messages from django.contrib.auth import login from django.contrib.sites.shortcuts import get_current_site from django.utils.encoding import force_bytes, force_text from django.utils.http import urlsafe_base64_decode, urlsafe_base64_encode from django.template.loader import render_to_string from .tokens import account_activation_token from django.contrib.auth.models import User from django.core.mail import EmailMessage class SignUpView(View): form_class = SignUpForm template_name = 'signup.html' def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False #Deactivate account until confirmed user.save() current_site = get_current_site(request) subject = 'Activate Your New Account' message = render_to_string('activateUserEmail.html', {'user': user, 'domain':current_site.domain, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) messages.success(request, ('Please confirm your email to complete registration:')) return redirect('login') return render(request, self.template_name, {'form': form}) class ActivateAccount(View): def get(self, request, uidb64, token, *args, … -
Django How do I filter querysets to insersect common results
I want to filter a queryset that depends on another queryset My models.py class Escola(models.Model): id = models.AutoField(db_column='ID', primary_key=True) nome = models.CharField(db_column='Nome', max_length=255, blank=True, null=True) class Inscrio(models.Model): id = models.AutoField(db_column='ID', primary_key=True) escolaid = models.ForeignKey(Escola, models.DO_NOTHING, db_column='EscolaID', blank=True, null=True) This is my views.py def view_forms(request): return render(request, "main/view_forms.html", {"escolas": Escola.objects.all, }) I have an .html template where I run a for loop to write all the objects of Escola and those objects are connected with the Model Inscrio (by 'escolaid' foreign key). I want a queryset to find Inscrio objects that have the same 'escolaid' as Escola's 'id' For example, say the for loop returned the 'id' = 1 for the model Escola, now I want to get (in a for loop) all Inscrio objects with 'escolaid' = 1 and I want this until the Escola loop has no more values How can I do that? Thanks in advance -
verbose_name_plural not working as in django admin
I am trying to change display for Model name in my django admin using verbose_name_plural in class Meta. here is my code : class Country(models.Model): country_name = models.CharField(max_length=30) is_active = models.BooleanField(default=True) date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) def __str__(self): return self.country_name class Meta: verbose_name = "Country" verbose_name_plural = "Countries" But it is not working, the display name is not changed in django admin list. django-admin list models I also tried to : place the "Meta" class in admin.py -> not working already makemigrations & migrate -> still same result stop and start server Thank you for any comment/advice. -
how i solve Class 'Like' has no 'objects' memberpylint(no-member)
**In My models classes occure error Class '' has no 'objects' memberpylint(no-member) in al; models classes so how i solve this error can you tell me below example like class in cls is occured above error ............................................................................................................................................................................. ** models.py class Like(models.Model): user = models.ManyToManyField(User,related_name="linkingUser") post = models.OneToOneField(Post,on_delete=models.CASCADE) @classmethod def like(cls,post,liking_user): obj,create= cls.objects.get_or_create(post=post) obj.user.add(liking_user) @classmethod def dislike(cls,post,disliking_user): obj,create= cls.objects.get_or_create(post=post) obj.user.remove(disliking_user) -
Get value from dropdown and use it for post method within view
Hi there another Django newbie here, So, I'm trying to make a simple Quote web application. So, I have 2 models: 1 for an Author and another 1 for Quotes. So there is a many to one relationship: Author model: ```class AuthorInfo(models.Model): author_firstName = models.CharField(max_length=100) author_lastName = models.CharField(max_length=100) def __str__(self): return self.author_firstName``` Quote model: ```class Quote(models.Model): author = models.ForeignKey(AuthorInfo, on_delete=models.CASCADE) quote_text = models.CharField(max_length=255) def __str__(self): return self.author.author_firstName``` What I'm trying to do right now is, I have a form and inside that form, I have a dropdown that is filled up with the author's first names. Form inside Home.html: ```<form method="POST" action="/addQuote/"> {% csrf_token %} <div class="container mt-3 d-flex justify-content-center"> <div class="card w-100"> <div class="card-header navbar-dark bg-primary"> <h1 style="color: white;">Add quote</h1> </div> <div class="card-body"> Quote text <div class="input-group input-group-sm mb-1"> <div class="input-group-prepend"> <span class="input-group-text bg-primary" style="color: white;" id="inputGroup-sizing-sm" >Enter Quote</span > </div> <input name="quote_text" type="text" class="form-control" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-sm" /> </div> <br /> <div class="mb-3"> <div class=""> Select author <select name="dropdown_author"> {% for author in authors %} <option value="{{author.author_firstName}}" >{{author.author_firstName}}</option > {% endfor %} </select> </div> </div> <button type="submit" class="btn btn-primary align-items-center d-flex justify-content-center" > Submit quote </button> </div> </div> </div> </form>``` I want to make it possible for … -
Storing multiple images per each entity object in Django with SQLite
I am currently building myself a website that I could store info of recently release hardware parts (e.g. Motherboard, CPU, etc.) I am super newb on Web Development and here is my code snippet of current database model. class Manufacturer(models.Model): name = models.CharField(max_length=264, unique=True) class Hardware(models.Model): manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE) name = models.CharField(max_length=264, unique=True) price = models.DecimalField(max_digits=6, decimal_places=2) release_date = models.DateField(default=datetime.date.today) image = models.ImageField(null=True, blank=True) class Meta: abstract = True So, this way I could have stored zero or one image per each entity, but ain't sure how I could make it to store 0 to more images per each. It seems like PostgreSQL does support an ArrayField, but since I am using SQLite, I can't really think of the best way to achieve this. -
I am trying to make a JS function inside of a button within a Django app that deletes a related database (SQLite3) entry
I have a Django localhost webserver that I've been experimenting with, and I'm doing the infamous "todo app" as my intro to a few topics. Conceptually, the user puts their "todo item" into a text input field (which is a Django form that's inside of the django html template). This action takes the text and puts it in a SQLite3 database and at the same time, the action creates a div container that has a paragraph tag and a button inside of that div. The P tag gets filled with the contents of the text given in the input. The button is meant to do two things; firstly, it deletes the parent div, which removes that button and the todo item. So, it's like a "this item is done" button, which deletes that item. That is working properly. The SECOND function of the button, though, has got me stumped. The idea is to delete that item from the database as well, as that's where I store and retrieve the todo items from when the page is generated. I have attempted to do this by passing the {item} variable (which is a Django Template Language variable made inside of the Django … -
Gcloud deleted instance without removing ssl-certificates now my PSQL port 5432 is locked
I was trying to post a site on gcloud, we set everything up on Django SSL and all but, the File was over 10000 so it did not work. I wanted to migrate to AWS and use elastic beanstalk the issue is. I'm locked out of PSQL/port can not even run my site on local port 5432. psql: error: could not connect to server: could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? could not connect to server: Connection refused (0x0074D/100) Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? {gcloud compute ssl-certificates delete} `ERROR: (gcloud.compute.ssl-certificates.delete) Could not fetch resource: - The resource 'projects/firstsitempc/global/sslCertificates/firstsitempc' was not found ` -
Is there a simple way to provide code coverage for django/django rest framework views?
When rendering DRF views using coverage on a Django system, I'm not seeing hits on the internals of my functions. I am seeing hits on the definition of my class/function as those are imported into the tests (which is expected). Is there a general strategy to use in order to achieve coverage reports for Django or DRF views? So far I've been struggling to find any answers here. The code I"m using is similar to the example I'm providing below # API File referenced as afile below. from rest_framework.views import APIView from rest_framework.request import Request from rest_framework.response import Response class MyView(APIView): def post(self, request: Request) -> Response: return Response(resp, status=200) # Test file referenced below. from afile import MyView from django.test import TestCase from rest_framework.test import APIRequestFactory class TestView(TestCase): def test_thing(self): factory = APIRequestFactory() request = factory.post("/fakeurl", {}) response = MyView.as_view()(request) self.assertEqual(response, 200) I understand that most black box testing strategies shouldn't render code coverage. But, since I am calling a Django view via the functionas_view() I am curious as to whether I should expect hits on my code. -
turn each django table row into link
I have a django table2 table and I need to make each row of one column to be a link toward others urls. Django tables 2: Hyperlinking items in a column is the closest thing that I found but it does not work for me. my table looks like this: Class revenue nb_items classAA 10 3 classA 8 4 classB 6 7 classC 4 11 classD 2 17 but I cannot find a way to make the classes a clickable link to a corresponding page that I have. From what I found online, I have tried something like this: class ClassificationTable(tables.Table): Class = tables.LinkColumn('classAA1page.html', args=[class_aa1('pk')]) but this solution does not work because it only let me code one link and not one for EACH row of the table. I am hoping that someone could provide me with some guidance on the matter. Thank you! -
enabling a django download button for pdf download
I am trying to set up a django button so I can download a file. I tried following along a tutorial but I think i'm missing something. The urls.py code below is the urls.py file that i generated in the app section of my project. I am not sure if that is the correct one to be using. The code below is not working, local host doesn't load the page. however when i comment out url('download_my_pdf', download_pdf), in my urls.py the site loads as we dont have that link back to the code in the views. INDEX.HTML: <input type="button" value="Download" onclick="window.open('download_my_pdf')"> VIEWS.PY: from django.shortcuts import render from django.http import HttpResponse from wsgiref.util import FileWrapper def index(request): return render(request, "index.html", {}) def home(request): return render(request, "home.html", {}) def download_pdf(request): filename = 'faults.pdf' content = FileWrapper(filename) response = HttpResponse(content, content_type='application/pdf') response['Content-Length'] = os.path.getsize(filename) response['Content-Disposition'] = 'attachment; filename=%s' % 'faults.pdf' return response URLS.PY from django.urls import url from django.urls import path from . import views urlpatterns = [ path('', views.index, name="index"), path('home', views.home, name="home"), url('download_my_pdf', download_pdf), ] -
how do i add number and string to my django
hey someone should kindly help me out with my code,how can i add number and text randomly to my model.py ,actually i have website with a user profile which when the user subscribe it will generate a random text and number to the user profile that will serve the user like an id till the subscription is over,here is my code models.py def plan_id(): plan_id=[] for i in range(5): alpha=random.choice(string.ascii_letters) num=random.choice(string.digits) plan_id.append(alpha) plan_id.append(num) y = "".join(str(x)for x in plan_id) return str(random.choice(string.y)) class Patient(models.Model): STATE_CHOICES=( (True, u'Yes'), (False, u'No'), ) user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, null=True, related_name="patient") subscribe = models.BooleanField(default=True, choices=STATE_CHOICES) plan_id = models.CharField(max_length=10, null=False, default=plan_id) views.py @login_required def patient(request): context = { 'patient': Patient.objects.all() } return render(request, 'pages/patient.html', context) -
Adding img tags into a Django template using Javascript
Hi so I am trying to make a website in django. For one page on the website I want to have a catalog so I need to load in a big table using javascript. The console.log is the correct img tag syntax but no images load. This is my javascript code : catolog.js function makeList() { listData = Array.from(Array(43).keys()); // Add it to the page content1 = document.querySelectorAll(".tg-0lax"); var count = 0; var td; for (td of content1){ console.log(td); text = 'images'+ '/'+ 'image_' + count + '.jpg'; console.log(text); img = " src= \"{ % static '" + text + "' % }\""; str = '<img ' + img + '>'; console.log(str); td.innerHTML = str; count = count + 1; } } makeList(); This is my html file {% extends "storeApp/base.html" %} {% block content %} {%load static%} <style> article{ text-align: center; } </style> <div class="content1" id="data-point-1"> <style type="text/css"> .tg {border-collapse:collapse;border-spacing:0;} .tg td{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px; overflow:hidden;padding:10px 5px;word-break:normal;} .tg th{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px; font-weight:normal;overflow:hidden;padding:10px 5px;word-break:normal;} .tg .tg-0lax{text-align:left;vertical-align:top} </style> <table class="tg" onload="makeList()"> <thead> <tr> <th class="tg-0lax"></th> <th class="tg-0lax"></th> <th class="tg-0lax"></th> </tr> </thead> <tbody> <tr> . . . </tr> </tbody> </table> <script src={% static 'js/catolog.js'%}> </script> </div> {% endblock %} -
TypeError: expected string or bytes-like object with django Q query
I'm trying to filter Event objects to only show events where the event.day is greater than or equal to today. However, I get the following error when I run it: TypeError: expected string or bytes-like object views.py today = datetime.now().day availability = Event.objects.filter(Q(day__gte=today)).order_by('-day') the day field in the Event model is a DateField. Any help would be greatly appreciated. Thanks! -
Django + PostgreSQL backup and restore on an EC2 instance
I have a simple monolithic architecture: A Django project hosted on an EC2 instance, talks to a PostgreSQL DB running on the same instance. I chose this architecture considering the traffic and cost. So, don't bash me on this one. :) For disaster recovery, I regularly dump my DB (a full dump pg_dump -U postgres fishercoder_db > fishercoder_dump.sql). At restoring, I cannot get Django and the restoring DB to talk nicely with each other: If I launch Django and run ./manage.py migrate first, and then restore the DB from the dump, it fails because Django has already created a bunch of internal tables after running ./manage.py migrate which have exactly the same name of in my dump; If I restore the DB from the dump first, then my Django app cannot stand up because of insufficientprivilege to run ./manage.py migrate, details asked here. My question is: Is my DR strategy reasonable? Any other more optimal ways? How can I get this approach to work: restore my site on a new EC2 instance with DB restored from a .sql dump. -
Displaying PPT in HTML web page
Currently creating an website using Python django framework using HTML and one of the features is file upload & view. It works fine with PDF documents, but when I try to view uploaded PPT documents, it always goes to download in chrome browser Few things I tried and didn't prefer are, 1) Using Embed PPT from Onedrive which supports already available documents. 2) Changing the PPT file into some other document format like PDF and viewing it directly from browser Please let me know how to view/display PPT file in HTML webpage without going through above complications. -
Django model history with foreign keys history tracking using django-simple-history
I have three models with historical records: class WifiUser(models.Model): .... wifiDevice = models.OneToOneField(WifiDevice, on_delete=models.CASCADE, default=None) wifiSim = models.OneToOneField(WifiSim, on_delete=models.CASCADE, default=None) history = HistoricalRecords() class WifiDevice(models.Model): .... history = HistoricalRecords() class WifiSim(models.Model): .... history = HistoricalRecords() I want to keep track of history with corresponding foreign key history records. But when accessing the history of Wifiuser I get the latest values of WifiDevice and WifiSim. I want the historical record of WifiDevice and WifiSim to point to that record of their one. Whats the best method to follow for this ? -
Sort db alphabetically with header in django
Writing website on django: i've got 1500 rows in DB Need to give those rows to frontend like: A Alice Andrew Ann B Bill Boris Brendan ... now in my views.py the for cycle goes around names and if the first letter of name is in the alphabet, that letter is added to my new alphabet: for name in names: if name[0] in alphabet: my_alphabet.append(name[0]) my_alphabet = sorted(list(set(my_alphabet))) Then I transfer my new alphabet and names to the html template: {% for letter in my_alphabet %} <span>{{ letter }}</span> {% for name in names %} {% if name.0 == letter %} <span>{{ name }}</span> {% endif %} {% endfor %} {% endfor %} That pages loads up to 10 seconds Maybe anyone's got a faster variant? Thanks for helping noob, sorry for wasting time! -
Django: Referencing inherited attributes from mixin
I have a long list of tuples used as model choices. They are currently class attributes in a model definition. I would like to move them into a mixin without affecting existing references across a legacy codebase. Here is what currently exists: class MyModel(models.Model): COLD = 1 WARM = 2 HOT = 3 FIRE = 4 STATUSES = ( (COLD, 'Cold'), (WARM, 'Warm'), (HOT, 'Hot'), (FIRE, 'Fire'), ) status = models.IntegerField(choices=STATUSES) Here is what I would like to do: class StatusMixin: COLD = 1 WARM = 2 HOT = 3 FIRE = 4 STATUSES = ( (COLD, 'Cold'), (WARM, 'Warm'), (HOT, 'Hot'), (FIRE, 'Fire'), ) class MyModel(StatusMixin, models.Model): status = models.IntegerField(choices=STATUSES) I'm trying to reference them: As part of the model inheriting them: my_model_instance = MyModel.objects.get(id=1) if my_model_instance.status == MyModel.FIRE: return As part of a model NOT inheriting them, but referencing the model that does: class OtherModel(models.Model): my_model_status = models.IntegerField(choices=MyModel.STATUSES) I am unable to satisfy both conditions. I'm sure there is a better way -- perhaps not a mixin? -
Implement python-social-auth with Django and Steam backend
not sure how to start this thread but i implemented the Python-Social-Auth to work with Github, i followed this tutorial and i got it working: https://simpleisbetterthancomplex.com/tutorial/2016/10/24/how-to-add-social-login-to-django.html So i decided ok why we don't make it with Steam and i found this: Proper way to implement python-social-auth with Django and Steam backend Bad news about it is that, i make everything i guess not sure if i have to do anything else, when i click login into Steam and i go to the https://steamcommunity.com/openid/login but when i get back to the website i get this at console: [19/Jun/2020 17:25:10] "GET /oauth/login/steam/ HTTP/1.1" 200 1230 [19/Jun/2020 17:25:52] "GET /oauth/complete/steam/?janrain_nonce=2020-06-19T21%3A25%3A10ZdgR4aL&openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&openid.mode=id_res&openid.op_endpoint=https%3A%2F%2Fsteamcommunity.com%2Fopenid%2Flogin&openid.claimed_id=https%3A%2F%2Fsteamcommunity.com%2Fopenid%2Fid%2F76561198999680480&openid.identity=https%3A%2F%2Fsteamcommunity.com%2Fopenid%2Fid%2F76561198999680480&openid.return_to=http%3A%2F%2F127.0.0.1%3A8000%2Foauth%2Fcomplete%2Fsteam%2F%3Fjanrain_nonce%3D2020-06-19T21%253A25%253A10ZdgR4aL&openid.response_nonce=2020-06-19T21%3A25%3A50ZQ9%2F%2BHcdLB5lfPjbsYvmGpLCgSe0%3D&openid.assoc_handle=1234567890&openid.signed=signed%2Cop_endpoint%2Cclaimed_id%2Cidentity%2Creturn_to%2Cresponse_nonce%2Cassoc_handle&openid.sig=SLkLPpwAJyW8q9Ftp9bKlp8m%2Bys%3D HTTP/1.1" 302 0 [19/Jun/2020 17:25:52] "GET / HTTP/1.1" 302 0 [19/Jun/2020 17:25:52] "GET /login/?next=/ HTTP/1.1" 200 193 And never login, i go back and still says Login with steam or Github so i decided to check the database and i found that the entries are even added to it... Database Picture Any place where i can find help about this? Or anything that i might be missing? Thanks in advance! =) -
Django ListView filter objects
I have a simple structure Shop_list --> Product_list --> Product_detail I want to filter Product class object by slug field, but I see zero products. I think that the problem in get_queryset() views.py class HomePageView(ListView): model = Shop template_name = 'blog/shop_list.html' page_kwarg = 'shop' context_object_name = 'shops' class ProductListView(ListView): model = Product template_name = 'blog/product_list.html' page_kwarg = 'product' context_object_name = 'products' def get_queryset(self): pattern = str(self.request) pattern = pattern[1:] slug = self.model.shop return Product.objects.filter(shop__slug=pattern) def produt_detail(request, **kwargs): print(request) product = get_object_or_404(Product, pk=kwargs["pk"]) return render(request, 'blog/product_detail.html', {'product': product}) models.py class Shop(models.Model): title = models.CharField(max_length=200) image = models.ImageField(blank=True) slug = models.SlugField(null=False, default="Shop") def get_absolute_url(self): return reverse('product_list', kwargs={'slug': self.slug}) class Product(models.Model): shop = models.ForeignKey(Shop, on_delete=models.CASCADE, related_name="shop") title = models.CharField(max_length=200) price = models.CharField(max_length=200) period_start = models.DateTimeField(blank=True, null=True) period_end = models.DateTimeField(blank=True, null=True) def get_absolute_url(self): return reverse('product_detail', kwargs={'slug': self.shop.slug, 'pk': self.pk}) urls.py urlpatterns = [ path('', HomePageView.as_view(), name='shop_list'), path('<slug:slug>', ProductListView.as_view(), name='product_list'), path('<slug:slug>/<int:pk>/', views.produt_detail, name='product_detail'), ] product_list.html {% for product in products %} <a href="{% url 'product_detail' product.shop.slug product.shop.pk %}"> ... -
filter blogs by tags in Django
I'd like to render a view in Django with objects that have certain tags. Here's my model: class Tag(models.Model): """Model representing a tag.""" name = models.CharField(max_length=200) class Post(models.Model): """Model representing a post.""" title = models.CharField(max_length=200) # ManyToManyField used because tag can contain many posts. Posts can cover many tags. tag = models.ManyToManyField(Tag, related_name='tags', blank=True, default='', help_text='Select a tag for this post') after running migrations, I see three tables generated in my DB: blog_tag, blog_post and blog_post_tag blog_post table doesn't contain a column called tag, instead, this blog_post_tag holds all the mapping. What I'd like to achieve is to find all posts that have certain tags. I tried to use post_list = Post.objects.filter(tag__in=['AWS']), but this one throws Field 'id' expected a number but got 'AWS'. Any help on working this out would be greatly appreciated!