Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
An error was reported while closing the websocket connection(...failed: Invalid frame header)
I use django and dwebsocket. There is a warning in my browser console. Also it runs well. There is no problem :). But i wondered. enter image description here enter image description here views.py import threading from django.shortcuts import render_to_response from dwebsocket.decorators import accept_websocket def index(request): return render_to_response('index.html', {}) clients = [] @accept_websocket def echo(request): if request.is_websocket: lock = threading.RLock() try: lock.acquire() clients.append(request.websocket) for message in request.websocket: if not message: break for client in clients: client.send(message) finally: clients.remove(request.websocket) lock.release() -
how to write raw like query in django2?
I was trying to develop a search application where a user can search and I need to avoid ORM query when I try to write this following raw query q = request.POST.get('searchData') if q: titleInfo = Item.objects.raw("""select * from item where title like '%%s%'""", [q]) It gives me this error ValueError at /test unsupported format character ''' (0x27) at index 41 Where my query is working fine in MySQL database -
Trouble Using Django Shell on PythonAnywhere
I am experimenting with Django Shell on PythonAnywhere. I imported a module and run help() on it. The help text is displayed, but I can't find a way to get back to the prompt. It shows (END) at the end of the help text instead of the prompt. Ctrl + Z completely closes the shell, which is not what I want. -
Django App crashes when deployed to Heroku - Worker failed to boot
Sorry for the long post but wanted to provide as much information as possible. Having some serious issues trying to deploy a django app onto heroku.. Been battling for days with this. The build is successful and so is the deployment but for some reason when navigating to the site address there is an application error. wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangoProject.settings") application = get_wsgi_application() settings.py import os import dj_database_url BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) SECRET_KEY = os.environ.get('SECRET_KEY') DEBUG = False ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'users.apps.UsersConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.storage.CompressedManifestStaticFilesStorage' ] ROOT_URLCONF = 'djangoProject.urls' enter code here TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ] WSGI_APPLICATION = 'djangoProject.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL … -
Django: 'SessionStore' object has no attribute 'session'
I'm trying to built an E-commerce following a tutorial on Udemy. I'm on the chapter on how to build the cart functionality (how to add items, see total cost and quantity). However, I'm having troubles adding products to cart. AttributeError at /cart/add/4/ 'SessionStore' object has no attribute 'session' views.py: from django.shortcuts import render, redirect from shop.models import Product from .models import Cart, CartItem from django.core.exceptions import ObjectDoesNotExist # Create your views here. def _card_id(request): cart = request.session.session.key if not cart: cart = request.session.create() return cart def add_cart(request, product_id): product = Product.objects.get(id = product_id) try: cart = Cart.objects.get(cart_id = _card_id(request)) except Cart.DoesNotExist: cart = Cart.objects.create( cart_id = _card_id(request) ) cart.save() try: cart_item = CartItem.objects.get(product = product, cart = cart) cart_item.quantity += 1 cart_item.save() except CartItem.DoesNotExist: cart_item = CartItem.objects.create( product = product, quantity= 1, cart = cart, ) cart_item.save() return redirect('cart:cart_detail') def cart_detail(request, total = 0, counter = 0, cart_items = None): try: cart = Cart.objects.get(cart_id = _card_id(request)) cart_items = CartItem.objects.filter(cart = cart, active=True) for cart_item in cart_items: total += (cart_item.product.price * cart_item.quantity) counter += cart_item.quantity except ObjectDoesNotExist: pass return render(request, 'cart.html', dict(cart_items = cart_items, total = total, counter = counter)) models.py from django.db import models from shop.models import Product # Create … -
Dynamic adding apps to Django
I'm building a backend with some core-functionality app (which means, of course, a single DB for the app). I'm looking for elegant way to create app for every new customer by "copying" some template (basic) app to be able modify every's customer app with specific customer's requirements. For ex., I have some basic StoreApp in Django. It could have some basic features, models etc. Now, when some new customer wants to sign up, I want dynamically (not manually) create additional copy of the existing StoreApp (of course, under different name and its own DB), make initial migration for it, register it in the settings and so on. Lately, I want to customize this new app according to the customer's requirements. I'm just looking for a way to separate code maintenance for every existing app, but, as I mentioned before, not to create every app manually. Any elegant way to do it? Some existing plugin for Django? Thanks in advance, Efi -
django not a callable issue
Coming across the error below, not really sure what is wrong. There was phone field missing in the modal which I did not notice before I ran the python manage.py migrate. Now when I try to run the server, I get the error below. I did make changes to the modal( added the phone field) and tried running python manage.py migrate. I thought it would re-migrate but no luck. Getting the same error as below. contacts - models.py: from django.db import models from datetime import datetime # Create your models here. class Contact(models.Model): listing = models.CharField(max_length=200) listing_id = models.IntegerField() name = models.CharField(max_length=200) email = models.CharField(max_length=200) phone = models.CharField(max_length=200) message = models.TextField(blank=True) contact_date = models.DateField(default = datetime.now, blank = True) user_id = models.IntegerField(blank=True) def __str__(self): return self.name contacts - admin.py - from django.contrib import admin # Register your models here. from .models import Contact class ContactAdmin(admin.ModelAdmin): list_display =('id', 'name', 'listing', 'email' 'contact_date') list_diplay_links=('id','name') search_fields = ('name', 'email', 'listing') list_per_page=25 admin.site.register(Contact, ContactAdmin) Error logs: (venv) User-MBP:btre_project user$ python manage.py runserver Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapperat 0x110c651e0> Traceback (most recent call last): File "/Users/rizwanrenesa/Desktop/btre_project/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Users/rizwanrenesa/Desktop/btre_project/venv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) … -
Django - How to update form values without clicking?
I am trying to figure out how to update a form input value into another division in the same html file, without clicking, I was thinking about running views periodically(in a sense of polling), but I just need to update the values, when they change in the input field. I tryed to simplify the code below as much as possible. Is it possible using the current layout, or will I have to drop everything and switch to a jQuery approach? forms.py class Entry(forms.Form): quantity = forms.CharField(label = '', required = True, widget forms.TextInput( attrs={'placeholder': 'Quantity','class':"form-control mr-sm-2"})) views.py def index(request): form = forms.Entry() if request.method == 'POST': form = forms.Entry(request.POST) if form.is_valid(): print("Validation Successful") quantity = form.cleaned_data['quantity'] return render(request, 'index.html', {'form':form, 'Quantity':quantity * 2}) index.html <form method = "POST" class="form-inline" id = "myForm"> {{ form }} {% csrf_token %} <button class="btn btn-outline-success my-2 my-sm-0" type="submit" id="but" >+</button> </form> <div> {{Quantity}} </div> Thanks Jaime -
Django 2.1 Test Issue
first of all thank you for your time and sorry about my english. Im learning Django, I had several years developing with python and decided to start to check this Framework. And I'm getting an weird responses. Im writting a TestCase, wich works perfectly outside Test. That is the code: class BoardTopicsTests(TestCase): # Hago las acciones necesarias para empezar el test def setUp(self): self.board = Board(name="Django", description="Django board.") # self.board.save() # Compruebo el status_code 200 def test_board_topics_view_status_code(self): # self.board.save() url = reverse("board_topics", kwargs={"pk":1}) response = self.client.get(url) self.assertEqual(response.status_code, 200) # Compruebo el status_code 404 def test_board_topics_view_not_found_status_code(self): url = reverse("board_topics", kwargs={"pk" : 99}) response = self.client.get(url) self.assertEqual(response.status_code, 404) # Compruebo que resuelve bien el board def test_board_topics_url_resolves_board_topics_views(self): view = resolve("/boards/1/") self.assertEqual( view.func.__name__, BoardTopics.as_view().__name__ ) If I save the board in setUp the method test_board_topics_view_status_code returns 404, if I save the board inside the method it returns 200 and pass the test. I think I'm missing something because I think it have to work saving from setUp method! Please, can somebody help with that? It's just for learning purposes because I want to know whats happening there. If I do print(self.board.id) inside test_board_topics_view_status_code it returns 1 as it suposed to be. Thank you … -
How to integrate cyber-ark with a Django application?
I have a django web application that connects to the production database( Oracle 12g ). I have to use Cyberark for storing the user id and password for connecting to database. Till now my database connection password and user id were mentioned in the DATABASE setting of the settings.py file as clear text. In some other applications( not coded in django ) we have modified the connection string in the tomcat server to connect to the cyberark driver and get the user name password to connect to the database. But I am new to django and dont know where to look for, for the connection string to connect to the database. Which django file picks up the database information from the settings.py file and actually connects to the database? How to integrate cyberark with Django? We are using Gunicorn as wsgi server and nginx as reverse proxy server. We have found a python module named PyArk but haven't found anybody who has used it. If anybody has used it or can answer the above questions, it would be very beneficial for me. -
Counting lines of code in a django project
I use this shell script to count the lines of code in a django project, find . -name "*.py" -type f -exec grep . {} \; | wc -l How can I modify this to not count the migration scripts. Essentially that means not count anything inside any subfolder by the name migrations Can someone help me with this. -
django - Type Error __init__ positional argument
I'm creating a blog by django, this is the error that I got recently: init() takes 1 positional argument but 2 were given Exception Location: C:\ProgramData\Miniconda3\envs\myDjanEnv\lib\site-packages\django\core\handlers\base.py in _get_response, line 124 And this is the 124th line of the code from base.py: if response is None: wrapped_callback = self.make_view_atomic(callback) try: <!-- line 124 --> response = wrapped_callback(request, *callback_args, **callback_kwargs) except Exception as e: response = self.process_exception_by_middleware(e, request) VIEWS.PY CODES: from django.shortcuts import render,get_object_or_404,redirect from django.utils import timezone from blog.models import Post,Comment from blog.forms import PostForm,CommentForm from django.urls import reverse,reverse_lazy from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.decorators import login_required from django.views.generic import (TemplateView,ListView, DetailView,CreateView, UpdateView,DeleteView,) # Create your views here. class AboutView(TemplateView): template_name = 'about.html' class PostListView(ListView): model = Post def get_queryset(self): return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date') class PostDetailView(DetailView): model = Post class CreatePostView(LoginRequiredMixin,CreateView): login_url = '/login/' redirect_field_name = 'blog/post_detail.html' # form_class = PostForm model = Post class PostUpdateView(LoginRequiredMixin,UpdateView): login_url = '/login/' redirect_field_name = 'blog/post_detail.html' # form_class = PostForm model = Post class PostDeleteView(LoginRequiredMixin,DeleteView): model = Post success_url = reverse_lazy('post_list') class DraftListView(LoginRequiredMixin,ListView): login_url = '/login/' redirect_field_name = 'blog/post_list.html' model = Post def get_queryset(self): return Post.objects.filter(published_date__isnull=True,).order_by('created_date') ############################################### ############################################### @login_required def post_publish(request,pk): post = get_object_or_404(Post,pk=pk) post.publish return redirect('post_detail',pk=pk) @login_required def add_comment_to_post(request,pk): post = get_object_or_404(Post,pk=pk) if request.method == 'POST': … -
Django: urls in html form not working correctly
I am building e-commerce website, I have a shopping cart model with items, I want the customer to select the quantity of a certain item they want to buy, this is the reason I am placing everything in a form to later grab the quantity in views.py by request.POST.getlist('quantity') and pass the data to 'Sales:checkout'. But in there I also have button to delete an individual item form the shopping cart (Sales:delete_cart_item) and a button for emptying the whole cart (Sales:empty_cart). Now to the problem, when I press any of the latter buttons, be it Sales:delete_cart_item or Sales:empty_cart they all execute Sales:checkout, please help me figure out what I'm doing wrong from shopping_cart.html: <form action="{% url 'Sales:checkout' %}" method="POST"> {% csrf_token %} {% for item in items %} <td>{{ item.item.item_name }}</td> <td> <input type="number" name="quantity" min="1" max="{{ item.item.stock_level }}"> </td> <td>{{ item.item.id }}</td> <td> <a href="{% url 'Sales:delete_cart_item' item.id %}"><button>Delete row</button></a> </td> {% endfor %} <form action="Sales:empty_cart" method="POST"> <button type="submit">Empty Cart</button> </form> <button type="submit">Continue to Secure Checkout</button> </form> please ask if you need additional details -
How to get user feedback from Django 2.x ModelAdmin Action
I have an action in a ModelAdmin class. The action may have already been applied to the object selected, so I want to give the user a yes/no popup asking if he/she wants to run the action again. The action is a longish running celery task, but it may be beneficial to run the action again, or it may not. Is there a way to ask the user and get the feedback to make the action do the right thing? Thanks! Mark -
How to use alias in column name in Django
I tried several examples to rename column names before formatting result into json but none of them work. My latest code look like below def employee(request): entries = Employee.objects.annotate(First Name=F('FirstName')). only('FirstName','Email') print(entries) return render_to_response('employee.html',{'employees': serializers.serialize("json",entries, fields=('First Name','Email'))}) This code give below result [{"model": "client.employee", "pk": 1, "fields": {"Email": "employe1@gmail.com"}}] So either only() nor annotate() is not working. -
Gitlab CI - Django functional tests - splinter
I want to run some automation tests on github on a project of mine with a Django framework. Therefore I am using a Django functional test. While executing the test on my local pc works fine, my pipeline is always failing with those tests. I assumed, that chromedriver wasn't working correctly and after some research on the internet, I found out, that I need to install chrome as browser, so I modified my requirements.txt for pip like this: applescript==2018.11.19 astroid==2.1.0 autopep8==1.4.3 chromedriver==2.24.1 decorator==4.3.0 detect==2018.11.19 Django==2.1.3 flake8==3.6.0 google-chrome==2018.11.19 google-chrome-cli==2018.11.19 isort==4.3.4 lazy-object-proxy==1.3.1 mccabe==0.6.1 only==2018.11.20 psutil==5.4.8 public==2018.11.20 pycodestyle==2.4.0 pyflakes==2.0.0 pylint==2.2.1 pytz==2018.7 runcmd==2018.11.20 selenium==3.141.0 six==1.11.0 splinter==0.10.0 temp==2018.11.20 urllib3==1.24.1 wrapt==1.10.11 .gitlab-ci.yml image: python:latest before_script: - pip install virtualenv - virtualenv --python=python3 venv/ - source venv/bin/activate - pip install -r requirements.txt - cd src/ - python manage.py migrate stages: - quality - tests flake8: stage: quality script: - flake8 ./ test: stage: tests script: - python manage.py test test_functional.py def setUp(self): # LINUX x64 executable_path = {'executable_path': settings.CHROMEDRIVER_PATH_LINUX64} # chrome self.browser_chrome = Browser('chrome', **executable_path) [..] With this, a chrome browser has been installed, but now I get this error: selenium.common.exceptions.WebDriverException: Message: Service /builds/mitfahrzentrale/mitfahrzentrale/venv/chromedriver unexpectedly exited. Status code was: 127 What do I need to modify in … -
Call property or method of related model in Django
Is it possible to call property or instance method of related object in Django model? One of my models need to access 'parent's' field and show it as it's own property. To check this I've added @property to 'child' model, but unfortunately when trying to call this property in Django Admin I'm receiving: ERRORS: <class 'some_app.admin.AnotherModelAdmin'>: (admin.E108) The value of 'list_display[5]' refers to 'some_app_timestampapplied_operational_mode', which is not a callable, an attribute of 'AnotherModelAdmin', or an attribute or method on 'some_app.AnotherModel'. Simple example: class SomeModel(models.Model): strategy = Charfield(max_length=1, choices=SOME_STRATEGIES) ... class AnotherModel(models.Model): related_parent_model = models.ForeignKey('SomeModel', on_delete=models.CASCADE) @property def applied_strategy(self): return self.related_parent_model.strategy -
Heroku Pipelines and/or Travis CI
We are using Heroku to host our Django application. We also use Heroku Pipelines with continuous integration and tests running after each push to our staging. Is there any advantage/difference in using Travis CI instead? I see it in so many projects but haven't used it before. -
None model related field as SlugRelatedField to Serializer
I've added a view to create a new user, this takes a username, password, email and a slug field to link to a permission. { "username" : "TestUsername", "email" : "TestUsername@outlook.com", "password" : "Password01", "group" : "partial-permission" } The view for this request is; class CreateUserSerializer(serializers.ModelSerializer): group = serializers.SlugRelatedField(queryset=CompanyGroup.objects.all(), slug_field='slug_field') class Meta: model = User fields = ['company', 'email', 'username', 'password', 'token', 'group'] read_only_fields = ['token'] write_only_fields = ('password',) def create(self, validated_data): return User.objects.create_user(**validated_data) I'm trying to use the SlugRelatedField to link automatically to the Group passed in the slug field and pass this onto my create_user method in my model. class UserManager(BaseUserManager): def get_queryset(self): return UserQuerySet(self.model, using=self._db).active_and_not_deleted() def create_user(self, username, email, password, group=None, company=None): user = self.model(username=username, email=self.normalize_email(email), company=company) user.set_password(password) return user When doing this I'm getting the exception: AttributeError at /users/ Got AttributeError when attempting to get a value for field `group` on serializer `CreateUserSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `User` instance. Original exception text was: 'User' object has no attribute 'group'. I understand that this exception explains exactly what my problem is, but I'm trying to avoid having it on the User object and manually looking … -
Handle POST and GET Mehtods in the same view with Django and Full Calendar JS
first, sorry for my bad english, i'm very redundant with my explanations because i'm newbie in this programming languaje and this community. So, let's begin, I have mounted all structure for the full calendar itself, models, views, forms, URLs, events as JSON and my HTML templates, I use Bootstrap to show a modal pop-up when I click on a empty space in a date to add a new event and works perfectly adding events to my model and rendering in JSON, the real question is: how I can do to update an existing event when I click on it? my models.py from django.db import models from apps.cusomers.models import Person class EventsCalendar(models.Model): title = models.CharField(max_length=200, null=True, blank=True) ##If the event covers all day time allDay = models.BooleanField(blank=True, null=True, verbose_name='All day event?', default=False) start = models.DateTimeField(blank=True, null=True) end = models.DateTimeField(blank=True, null=True) url = models.URLField(max_length=200, null=True, blank=True) ##colors for the events (using clasName option of full calendar) RED = 'RED' GREEN = 'GREEN' BLUE = 'BLUE' YELLOW = 'YELLOW' CIAN = 'CIAN' COLORS = ( (YELLOW, 'Pending'), (BLUE, 'Not Movable'), (CIAN, 'Movable'), (RED, 'Cancelled'), (GREEN, 'Confirmed')) className = models.CharField(max_length=15, choices=COLORS, default=YELLOW) ##If the event is editable or not editable = models.BooleanField(blank=True, null=True, verbose_name='Editable?', … -
Update the attributes of the Django Models.py from views.py
i am working on a booking system project (Django) and i want to make seats decreasing by 1 every time a user books a ticket i made seats as a variable in the train class in the models file and i made a function which decreases the seats by 1 in the same file but i don't know how or where to call it. -
django-avatar form location issue
I'm new to django/python and I'm using the django-avatar plugin (https://github.com/grantmcconnaughey/django-avatar) so users can upload images as avatars on our website. I've been trying to debug this issue for a day and I'm not sure what I'm missing. The issue I'm running into is that I copied the "change.html" form into our myaccount.html page and I get the following: "You haven't uploaded an avatar yet. Please upload one now." That's incorrect since I already have an image uploaded and all I want is the proper change form with the input field to appear that populates once an avatar is uploaded. The form I want generated appears properly when I navigate to "/avatar/change/" when i want it to be "/myaccount/change/". Does anyone have any ideas how to solve this issue? Thanks! myacccount.html <p>{% trans "Your current avatar: " %}</p> {% avatar user %} {% if not avatars %} <p>{% trans "You haven't uploaded an avatar yet. Please upload one now." %}</p> {% else %} {% endif %} <form enctype="multipart/form-data" method="POST" action="{% url 'avatar_add' %}"> {{ upload_avatar_form.as_p }} <p>{% csrf_token %} <input type="submit" value="{% trans " Upload New Image " %}" /> </p> </form> views.py from django.shortcuts import render from django.http import … -
Why does queryset=Post.objects.all() evaluate to Error when queryset is set to Post.objects.all()?
when i set queryset=Post.objects.all() the Post class show error that is"/d:/Programming/Python/Python_WorkPlace/New_django_project/posts/views.py", **"message": "Class 'Post' has no 'objects' member"** -
Issues in creating a dynamic table in report lab that continue printing its values on a next page
I have a table and i want it to print the values on a new pdf page once it reaches maximum page size, i have used report lab canvas and set the table into the canvas. Why we are using Wrapon an DrawOn? My code: buffer = io.BytesIO() p = canvas.Canvas(buffer) data = [ ['begin', 'begin', 'begin', 'begin', 'begin'], ['30', '31', '32', '33', '34'], ['00', '01', '02', '03', '04'], ['10', '11', '12', '13', '14'], ['20', '21', '22', '23', '24'], ['30', '31', '32', '33', '34'], ['00', '01', '02', '03', '04'], ['10', '11', '12', '13', '14'], ['30', '31', '32', '33', '34'], ['00', '01', '02', '03', '04'], ['10', '11', '12', '13', '14'], ['20', '21', '22', '23', '24'], ['end', 'end', 'end', 'end', 'end'], ] t = Table(data, style=[ # ('GRID', (0, 0), (-1, -1), 0.5, colors.black), ('LINEABOVE', (0, 1), (-1, 1), 1, colors.blue), # ('VALIGN', (3, 0), (3, 0), 'BOTTOM'), # ('ALIGN', (3, 1), (3, 1), 'CENTER'), # ('ALIGN', (3, 2), (3, 2), 'LEFT'), ] ) #What do they mean? t.wrapOn(p, 220, 400) t.drawOn(p, 220, 400) p.save() buffer.seek(0) return buffer -
How to add Tags in place of groups to Django posts
Intro: I have a simple project with User, Post and Group. Users can make posts and they have to choose which group the post will belong to. Members (Users) can join and leave groups. If members join a group they see all new articles in that post on their wall. Members cannot create a new Group. They have to select from Existing groups to which their post will belong example: A post on football will belong to the group Football What I want: I want users to be able to link one post to multiple existing groups example: A post on what to eat before a big game.(This post can belong to 3-5 different groups like Football, Soccer, Rugby, Hockey etc). Similar to the Stackoverflow style where you can choose upto 5 tags for your questions. This way this post will belong to all 5 groups. See image below I want to achieve something exactly like this. My Post and Group Models below: class Post(models.Model): user = models.ForeignKey(User, related_name='posts') group = models.ForeignKey(Group, related_name='posts') title = models.CharField(max_length=250, unique=True) message = models.TextField() class Group(models.Model): name = models.CharField(max_length=250, unique=True) description = models.TextField(default='', blank=True) members = models.ManyToManyField(User, through='GroupMember') class GroupMember(models.Model): user = models.ForeignKey(User, related_name='membership') …