Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Hi there, how to i listen in django channels for the data/sms from different chats even if I m not inside of any specific room
Im trying to build a chat app with multiple rooms and i want to be able to listen for any data even if am not in any room, like whatsapp web, you can receive data of any user even if you are not inside that chat from where you are receiving data. -
Django form tools switch forms
I would like to make a conditional if is_doctor is checked else. So currently it will display the form if the form is checked now I would like to add another form if it isn't checked how would I attempt to do so? urls.py from django.urls import path from pages.views import index, ContactWizard, show_message_form_condition from pages.forms import PickUserType, SignUpForm contact_forms = [PickUserType, SignUpForm] urlpatterns = [ path('', index, name='home'), path('signup/', ContactWizard.as_view(contact_forms, condition_dict={'1': show_message_form_condition} ),name='signup'), ] forms.py from django import forms from pages.models import Profile from django.contrib.auth.forms import UserCreationForm from datetime import date, timedelta class PickUserType(forms.Form): is_doctor = forms.BooleanField(required=False) # verified = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'doctor')) # from django.core.files.storage import FileSystemStorage class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') class Meta: model = Profile fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', ) views.py from django.shortcuts import redirect, render from .forms import SignUpForm, UserProfileForm from django.contrib.auth import login, authenticate from formtools.wizard.views import SessionWizardView def show_message_form_condition(wizard): # try to get the cleaned data of step 1 cleaned_data = wizard.get_cleaned_data_for_step('0') or {} # check if the field isDoctor was checked. return cleaned_data.get('is_doctor', True) class ContactWizard(SessionWizardView): def done(self, form_list,form_dict, **kwargs): print(form_list) print(form_dict) print(kwargs) … -
Two Django apps, two different nginx servers, cannot load static files on 2nd server from 1st server
I have two servers, test1.com and test2.com. Test1 is internet-facing public server. Test2 is intranet only server. Both servers have nginx docker running. Test1 runs a Django app1 which has static files under /app/public/static. App1 can load the static files and run correctly from URL https://test1.com/app1. Test2 has a Django app2 which has static files under /app/public/static on server test2 from URL https://test2.com/app2. Everything works including static files. The issue is I need to configure nginx1 to allow people to access app2 from the public internet. With the configuration nginx1 below I can load app2 but not the app2 static files. The error is: "GET /static/img/logo.jpg HTTP/1.1", host: "test1.com", referrer: https://test1.com/app2/ . The nginx is looking for app2 static file under test1 which obviously ‘file not found’. How can I configure nginx1 to look for app2 static files under test2.com, with a url of https://test2.com/app2/? : user nginx; worker_processes 1; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; client_max_body_size 50m; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; error_log /var/log/nginx/error.log; sendfile on; keepalive_timeout 65; map $http_upgrade $connection_upgrade { default upgrade; '' close; } … -
how to upload a csv file with pandas to a Database created by Django and set the Graph with matplotlib
i created a data base useing Django, so far I made the path for the File to models.FileField the plan is when someone upload a csv file it will generate a graph and display it as .png in the html post detail template. models.py: class Post(models.Model): files_Modulus = models.FileField(null=True,upload_to="chapters/%Y/%m/%D",default='no_data.html) Each uploaded file have the path:\media\chapters\2021\12\12\31\21\test.csv How can I tell pandas to read every file will the user upload to that path in the models.py as upload_to="chapters/%Y/%m/%D"and make a graph useing matplotlib and save it as PNG file and place it in the HTML template. -
Overriding Django model save method with image resizing
The below code successfully override the save method class News(models.Model): ........... photo=models.ImageField() def save(self,*args, **kwargs): super().save(*args, **kwargs) img1 = Image.open(self.image1.path) if img1.height > 400 or img1.width > 400: output_size = (400,400) img1.thumbnail(output_size) img1.save(self.image1.path) But after super().save() code, image is being opened and saved. Is it an efficient method? how its possible to reopen image after saving . -
Standard superuser creation in Django admin give unrecognizable error
python manage.py createsuperuser --username='donfox' After password is entered this is returned raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.name, kwarg)) TypeError: User() got an unexpected keyword argument 'email' The User is extended from an "AbstractUser". class User(AbstractUser): email = None first_name = None last_name = None REQUIRED_FIELDS = [] def __str__(self): return self.email class Meta: db_table = 'User' Column | Type | Collation | Nullable | Default --------------+--------------------------+-----------+----------+------------------------------------ id | integer | | not null | nextval('"User_id_seq"'::regclass) password | character varying(128) | | not null | last_login | timestamp with time zone | | | is_superuser | boolean | | not null | username | character varying(150) | | not null | is_staff | boolean | | not null | is_active | boolean | | not null | date_joined | timestamp with time zone | | not null | -
How to merge list of dictionaries by unique key value [duplicate]
I want to merge list of dictionary provided below with unique channel and zrepcode. sample input: [ { "channel": 1, "zrepcode": "123456", "turn": 7833.9 }, { "channel": 1, "zrepcode": "123456", "pipeline": 324 }, { "channel": 1, "zrepcode": "123456", "inv_bal": 941.16 }, { "channel": 1, "zrepcode": "123456", "display": 341 }, { "channel": 3, "zrepcode": "123456", "display": 941.16 }, { "channel": 3, "zrepcode": "123456", "turn": 7935.01 }, { "channel": 3, "zrepcode": "123456", "pipeline": 0 }, { "channel": 3, "zrepcode": "123456", "inv_bal": 341 }, { "channel": 3, "zrepcode": "789789", "display": 941.16 }, { "channel": 3, "zrepcode": "789789", "turn": 7935.01 }, { "channel": 3, "zrepcode": "789789", "pipeline": 0 }, { "channel": 3, "zrepcode": "789789", "inv_bal": 341 } ] Sample output: [ {'channel': 1, 'zrepcode': '123456', 'turn': 7833.9, 'pipeline': 324.0,'display': 341,'inv_bal': 941.16}, {'channel': 3, 'zrepcode': '123456', 'turn': 7935.01, 'pipeline': 0.0, 'display': 941.16, 'inv_bal': 341.0}, {'channel': 3, 'zrepcode': '789789', 'turn': 7935.01, 'pipeline': 0.0, 'display': 941.16, 'inv_bal': 341.0} ] -
How do you implement Django namespaces
I have started my journey with Django and I am thoroughly loving it. I do have a question about namespaces which I hope someone will be able to help me with and explain why it works like that. I understand namespaces are used to make sure that if you have two pages with the same name that the url and reverse function points to the right page. I have been trying to implement namespaces in a test app I am writing but have not been able to do it. Here is what I have so far (This is without namespaces as I haven't been able to get it to work. Extract from app urls.py from django.urls import path, re_path from . import views urlpatterns = [ path('', views.index, name = "index"), ] project urls.py from django.contrib import admin from django.urls import path, include, re_path import gallery urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('django.contrib.auth.urls')), path('index/', include('gallery.urls')), ] And lastly, this is my view.py file in my app folder from django.shortcuts import render from django.urls import reverse # Create your views here. def index(request): return render(request,"gallery/index.html") Any help will be appreciated -
Simple WYSIWYG image uploading
Currently I am using ckeditor to allow users to write blog posts. It does everything I want except the image uploading is awful. Users have to jump through two screen to upload an image and specify dimensions. The images don't auto scale to mobile and overall its a very poor experience. Is there a simple way to allow users to upload images or another WYSIWYG that can handle this. -
Acessing SQLite tables with Django on Ubuntu
I am following the Django official documentation tutorial on how to setup the database, provided here : https://docs.djangoproject.com/en/4.0/intro/tutorial02/ After running the code below I should have any necessary database tables according to the database settings in my mysite/settings.py. $ python manage.py migrate Now I want to check those tables through the terminal (this is my problem -> I can't). The documentation says : If you’re interested, run the command-line client for your database and type \dt (PostgreSQL), SHOW TABLES; (MariaDB, MySQL), .tables (SQLite), or SELECT TABLE_NAME FROM USER_TABLES; (Oracle) to display the tables Django created. None of those commands works on my terminal, my project is setup to be on SQlite, which is just a file on my project folder and SQLite is included in Python, so I shouldn't need to install anything else to support your database My questions is if I can ONLY run that command (.tables) on sqlite special command line and I need to install it or is there any way I can acess it with the terminal Iam using on Django. Any help will be HIGHLY appreciated. -
Django Tutorial - Testing vote(request, question_id)
I am working my way through the django tutorial and I reached part 5 - Introducing automated testing. I want to go beyond and write test for the vote method in views.py, but can't realise how to simulate the behaviour. Is there a way to do this? models.py: class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text views.py def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html', { 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) I've tried multiple stuff in tests.py. This is the latest version - i know choice_vote is currently not what i want, still needs to be filtered: class QuestionVoteTests(TestCase): def test_vote(self): """ Placeholder for vote method test. """ question = create_question(question_text="Question.", days=-5) … -
URL error in Django, being asked to add semicolon in the url link object
I have an HTML link, upon clicking it will direct me to the respective link <div onclick="location.href='{% url 'newscountry' 'Kuwait' %}'"> Kuwait </div> But I am being warned to add ; in the above link (as {% url 'newscountry'; 'Kuwait' %}')as per the attached image. Also, I am getting inconsistent links results too. urls.py as below, path('country/<str:country>/',NewsCountryView.as_view(),name='newscountry'), views.py class NewsCountryView(ListView): model = News template_name = 'newsfront/index.html' # <app>/<model>_<viewtype>.html context_object_name = 'news' ordering = ['-date_posted'] paginate_by = 16 def get_queryset(self): country=self.kwargs.get('country') return News.objects.filter(country=country) -
Failed to exec Python script file '/myproject/myproject/myproject/wsgi.py'
When I deployed my project, got these errors: [Fri Dec 31 18:27:56.319749 2021] [wsgi:error] [pid 4064:tid 140323912808192] [remote 5.238.148.231:53389] mod_wsgi (pid=4064): Failed to exec Python script file '/myproject/myproject/myproject/wsgi.py'. [Fri Dec 31 18:27:56.319901 2021] [wsgi:error] [pid 4064:tid 140323912808192] [remote 5.238.148.231:53389] mod_wsgi (pid=4064): Exception occurred processing WSGI script '/myproject/myproject/myproject/wsgi.py'. [Fri Dec 31 18:27:56.320220 2021] [wsgi:error] [pid 4064:tid 140323912808192] [remote 5.238.148.231:53389] Traceback (most recent call last): [Fri Dec 31 18:27:56.320306 2021] [wsgi:error] [pid 4064:tid 140323912808192] [remote 5.238.148.231:53389] File "/myproject/myproject/myproject/wsgi.py", line 16, in <module> [Fri Dec 31 18:27:56.320322 2021] [wsgi:error] [pid 4064:tid 140323912808192] [remote 5.238.148.231:53389] application = get_wsgi_application() [Fri Dec 31 18:27:56.320346 2021] [wsgi:error] [pid 4064:tid 140323912808192] [remote 5.238.148.231:53389] File "/myproject/virtualenv/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application [Fri Dec 31 18:27:56.320359 2021] [wsgi:error] [pid 4064:tid 140323912808192] [remote 5.238.148.231:53389] django.setup(set_prefix=False) [Fri Dec 31 18:27:56.320381 2021] [wsgi:error] [pid 4064:tid 140323912808192] [remote 5.238.148.231:53389] File "/myproject/virtualenv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup [Fri Dec 31 18:27:56.320393 2021] [wsgi:error] [pid 4064:tid 140323912808192] [remote 5.238.148.231:53389] apps.populate(settings.INSTALLED_APPS) [Fri Dec 31 18:27:56.320415 2021] [wsgi:error] [pid 4064:tid 140323912808192] [remote 5.238.148.231:53389] File "/myproject/virtualenv/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate [Fri Dec 31 18:27:56.320427 2021] [wsgi:error] [pid 4064:tid 140323912808192] [remote 5.238.148.231:53389] app_config = AppConfig.create(entry) [Fri Dec 31 18:27:56.320448 2021] [wsgi:error] [pid 4064:tid 140323912808192] [remote 5.238.148.231:53389] File "/myproject/virtualenv/lib/python3.8/site-packages/django/apps/config.py", line 224, in create … -
Can't measure the performance of serializer using cProfile
I'm trying to use cProfile to compare between serializers.ModelSerializer and serializers.Serializer according to this tutorial. Please, check out the tutorial before continuing the reading, it will be useful for you! Serializers: from django.contrib.auth.models import User from rest_framework import serializer class UserModelSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ 'id', 'username', ] class UserSerializer(serializers.Serializer): id = serializers.IntegerField() username = serializers.CharField() Views: from . serializers import UserModelSerializer, UserSerializer from rest_framework.response import Response from rest_framework.views import APIView import cProfile class TestApi(APIView): def get(self, request): u = User.objects.get(username='hamza') assert u.username == 'hamza' # just to ensure it fetches the user data = UserModelSerializer(u).data cProfile.run('for _ in range(5000): data') return Response(data) In views I just create GET endpoint and try to run cProfile but this gives me an error: NameError: name 'data' is not defined but if I comment the line cProfile.run('for _ in range(5000): data') in views and try to access data and send it to the Response without using cProfile it will work fine! So the question is, Why cProfile can't see UserModelSerializer? -
How to make the search-bar return "the post you searched doesn't exist" instead of displaying nothing https://github.com/Ayman-Isam/Class-of-2024-Blog
Here the searched function looks for the title of a post and searches it using the icontains functionality {% extends "blog/base.html" %} {% block content %} <div class="search-results"> {% if searched %} <h1>Results for - {{ searched }} </h1> <br> {% for post in posts %} <a href="{% url 'post-detail' post.id %}">{{ post }} - {{ post.description }}<br></a> {% endfor %} {% else %} <h1 class="find">You forgot to search for a post</h1> {% endif %} </div> {% endblock %} -
Issue with django json response
I have issue with json response. messages.values() gives me user_id instead of username. How to get username? Here is my code: class LivechatMessage(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE, null=True) def getMessages(request): messages =LivechatMessage.objects.all() return JsonResponse({"messages":list(messages.values())}) -
when going to admin giving error site url does not exist
When i am trying to go admin path in the it is giving me error that saying that site matching query does not exist this never happens to me before -
Django complex query with ForeignKey relations
I am using Django 3.1.4 and I have these models: from django.db import models from django.utils.translation import gettext_lazy as _ from django.utils.timezone import now class CrowdfundingOffering(models.Model): class PlatformChoices(models.TextChoices): buytheblock = "buytheblock", _("buytheblock") flashfunders = "flashfunders", _("flashfunders") mainvest = "mainvest", _("mainvest") netcapital = "netcapital", _("netcapital") republicco = "republicco", _("republicco") seedinvest = "seedinvest", _("seedinvest") smallchange = "smallchange", _("smallchange") startengine = "startengine", _("startengine") trucrowd = "trucrowd", _("trucrowd") wefunder = "wefunder", _("wefunder") platform = models.CharField( max_length=255, choices=PlatformChoices.choices, ) company_name = models.CharField(max_length=255) description = models.TextField(max_length=3000) url = models.URLField() funding_goal = models.FloatField(default=0) start_date = models.DateField() end_date = models.DateField() class Investment(models.Model): offering = models.ForeignKey( CrowdfundingOffering, on_delete=models.CASCADE, related_name="investments" ) timestamp = models.DateTimeField(default=now) number_of_investors = models.PositiveIntegerField(default=0) amount_invested = models.FloatField(default=0) Problem statement We need to make our data available to our data science team. For now, let’s give them something basic. A simple table like this will do: | Platform Name | Number of offerings | Amount raised total | Success ratio | -------- | -------------- | -------------- | -------------- | |startengine | 34 | 60093134 | 0.45 |wefunder | 56 | 3246765 | 0.4 We can create such a table from our database and save it as a CSV file. You need to implement a function that queries our … -
Creating Gin index for Postgres stored generated column in Django
I want to setup a Postgres "stored generated columns" with indexing to have full text search on two fields of a model. I created the generated column getting help from this tutorial, but when setting gin index on the column, I get this: django.core.exceptions.FieldDoesNotExist: Article has no field named 'vector_column'. The app cache isn't ready yet, so if this is an auto-created related field, it won't be available yet. And my Article model: class Article(models.Model): title = models.CharField(...) content = models.TextField(...) class Meta: indexes = [GinIndex(fields=['vector_column'])] and my custom sql in migration file: operations = [ migrations.RunSQL( sql=''' ALTER TABLE articles_article ADD COLUMN vector_column tsvector GENERATED ALWAYS AS ( setweight(to_tsvector('english', coalesce(title, '')), 'A') || setweight(to_tsvector('english', coalesce(content,'')), 'B') ) STORED; ''', reverse_sql=''' ALTER TABLE articles_article DROP COLUMN vector_column; ''' ), ] Is it possible to set index from Django? Seems Django needs the field to be defined on the model but that's not how generated column works. If not, what's the correct way of setting the proper index (mentioned in this Postgres doc, the on at the end) in migration files? -
Django application with Docker compose, not able to run cron job. Getting "crontab: can't open 'appname': No such file or directory"
This runs fine for me using docker-compose up locally. But when I run it on my EC2 (or locally) instance with docker-compose -f docker-compose.yml up, and then run docker-compose run --rm appname sh -c "python manage.py crontab show" I get crontab: can't open 'appname': No such file or directory, followed by Currently active jobs in crontab: Any ideas? -
FilePathField for Image Path not working with Django Admin Panel
New to Django and web development in general. But I have followed a tutorial for creating my first site. Everything worked fine, until I finished it and wanted to edit the info using the Django admin panel. The main issue is that I have a model shown below that uses FilePathField to describe the image locations. The tutorial had me place the images in /home/pi/mysite/projects/static/img. from django.db import models class Project(models.Model): title = models.CharField(max_length=100) description = models.TextField() technology = models.CharField(max_length=20) image = models.FilePathField('/img') def __str__(self): return self.title #or self.title for blog posts This worked fine at first for displaying the images on the website, but once I tried to navigate to the /change/ url from the admin panel, I would get FileNotFoundError at /admin/projects/project/1/change/ [Errno 2] No such file or directory: '/img' So I looked around and found that FilePathField is an absolute path, so tried defining it absolutely with /home/pi/mysite/projects/static/img/. This stopped the error from occurring which let me at least access the /change/ url from the admin panel. The panel now showed the image field with a dropdown that I could use to choose between the different images I had up there, which were located at /home/pi/mysite/projects/static/img/. But … -
Django ManyToOne reference multiple tables
Right now I have the following model that I'd like to be used in different models (I want to store the day of the week and time in different models): class DayTime(models.Model): # Side note: I saw that there is a DurationField and # was considering using that instead of the CharField below day = models.CharField(max_length=9, choices=DaysOfWeekTypeEnum.choices) time = models.TimeField() From the docs, I'd have to create a ForeignKey field in the above model to accommodate the ManyToOne reference. Example: class DayTime(models.Model): day = models.CharField(max_length=9, choices=DaysOfWeekTypeEnum.choices) time = models.TimeField() modelA = models.ForeignKey(ModelA, on_delete=models.SET_NULL) modelB = models.ForeignKey(ModelB, on_delete=models.SET_NULL) This doesn't sound right to me. Should I create different DayTime model instead? Thanks in advance. -
How to auto-refresh data and politely chart Plotly in Django
Hello how to auto refresh and auto updates so I can get realtime data in plotly chart in Django (whithout clicking on refresh button on the browser) Here is my code: in (views.py) from plotly.offline import plot import plotly.graph_objs as go import yfinance as yf def result(request): stock_ticker = request.GET['num1'] period = request.GET['num2'] interval = request.GET['num3'] data = yf.download(tickers=stock_ticker, period = period, interval = interval, auto_adjust = True, threads = True, proxy = None) data['Date'] = data.index def candlestick(): figure = go.FigureWidget(data = [go.Candlestick(x=data['Date'],high=data['High'],low=data['Low'],open=data['Open'],close=data['Close'],)]) figure.update_layout(width=1400, height=800, title=f'{stock_ticker} Historical price', plot_bgcolor="white") figure.update_yaxes(showline=True, linecolor='lightgray', showgrid=True, gridwidth=0.5, gridcolor='lightgray', mirror=True) figure.update_xaxes(showline=True, linecolor='lightgray', mirror=True, rangebreaks=[dict(bounds=["sat", "mon"]), dict(bounds=[16, 9.5], pattern="hour"),]) figure.update_traces(visible=True, selector=dict(type='candlestick')) candlestick_div = plot(figure, output_type='div', config = {"displaylogo": False}) return candlestick_div return render(request, 'index.html', {'candlestick':candlestick()}) also in (index.html) {% block content %} <center> {{ candlestick | safe}} </center> {% endblock %} -
Unable to get relation attribute in Django, many-to-many relationship
models.py: class Author(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Book(models.Model): title = models.CharField(max_length=100) author = models.ManyToManyField(Author) def __str__(self): return self.title I'm able to filter books by the author relation: >>> Book.objects.filter(author__name__contains="Fyodor") <QuerySet [<Book: Crime and Punishment>, <Book: The Brothers Karamazov>]> However, I'm unable to get the book's author: >>> all_books = Book.objects.all() >>> all_books[0].author <django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager object at 0x7fdf068a2b20> >>> all_books[0].author.name Any suggestions? -
Django - Add entry to ManyToMany field through class based view
I want to add / remove members from a Team model. Members are specified as a ManyToManyField. I use django-rules to specify permissions, so team owners should be able to add/remove members. # models.py from django.db import models from rules.contrib.models import RulesModel from django.conf import settings class Team(RulesModel): name = models.CharField(max_length=80) owner = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, help_text="Owner can view, change or delete this team.", related_name="team_owner", ) members = models.ManyToManyField( settings.AUTH_USER_MODEL, blank=True, related_name="team_members" ) The permissions are specified as following: import rules @rules.predicate def is_team_owner(user, obj): return obj.owner == user rules.add_perm("teamapp.change_team", is_team_owner) I've specified some generic views (CreateView, DetailView, UpdateView and DeleteView) to manage the Team. Now I want two separate views to add and remove members on the same. # views.py from django.views.generic import ( CreateView, DetailView, UpdateView, ListView, DeleteView, ) from rules.contrib.views import PermissionRequiredMixin from django.contrib.auth import get_user_model from .models import Team class TeamMemberAddView(PermissionRequiredMixin, UpdateView): model = Team permission_required = "teamapp.change_team" raise_exception = True fields = ["members"] def form_valid(self, form): user = get_user_model() new_member = user.objects.get(pk=1) self.object.members.add(new_member) return super(TeamMemberAddView, self).form_valid(form) Which generic view can I use to add / remove members? Which approach is recommended here? I wanted 1 dedicated view to select an existing User to be added, …