Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how not to do an action when condition met in Django
I have a couple of models named User, Book, Issue. Model Book has a field named remaining which holds the value of the number of available books. what I want: When there is zero book available, Issuing a book is closed. models.py from django.db import models from datetime import date, timedelta, datetime class Book(models.Model): name = models.CharField(max_length=30) author_name = models.CharField(max_length=30) category = models.CharField(max_length=30) remaining = models.IntegerField() def __str__(self): return self.name class Issue(models.Model): issue_id = models.CharField(max_length=10) roll = models.ForeignKey(User, on_delete=models.CASCADE) book_name = models.ForeignKey(Book, on_delete=models.CASCADE) issue_date = models.DateField(auto_now=False, auto_now_add=True) def save(self, *args, **kwargs): if not self.pk: super().save(*args, **kwargs) if self.book_name.remaining > 0: self.book_name.remaining -= 1 self.book_name.save() elif self.book_name.remaining == 0: print('hi') else: super().save(*args, **kwargs) admin.py from django.contrib import admin from django.contrib.auth.models import Group from .models import User, Book, Issue class BookAdmin(admin.ModelAdmin): list_display = ('name', 'author_name', 'remaining', 'category') list_filter = ('category', 'author_name') search_fields = ('name', 'author_name') class IssueAdmin(admin.ModelAdmin): list_display = ('issue_id', 'issue_date', 'return_date', 'fine',) list_filter = ('issue_date',) search_fields = ('issue_id',) admin.site.register(Book, BookAdmin) admin.site.register(Issue, IssueAdmin) I want to Implement this in Admin Dashboard Regards -
Docker Redis Django connection refused
I'm writing the project using Django REST Framework, Django, Postgres as database and Redis as caching. I want to dockerize my project. But Redis doesn't want to access connection. Django settings: CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://127.0.0.1:6379/', 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', } } } docker-compose.yml: services: postgres: image: postgres:latest env_file: - ./src/main/.env volumes: - ./scripts/postgres:/docker-entrypoint-initdb.d polls: build: . volumes: - .:/code env_file: - ./src/main/.env ports: - "8000:8000" depends_on: - postgres - redis command: ./scripts/wait_for_it.sh redis: restart: always image: redis:3.2.0 expose: - "6379" When I run command to up containers there are follow warnings: polls_cache | 1:M 15 Aug 10:47:36.719 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128. polls_cache | 1:M 15 Aug 10:47:36.720 # Server started, Redis version 3.2.0 polls_cache | 1:M 15 Aug 10:47:36.720 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect. polls_cache | 1:M 15 Aug 10:47:36.720 # WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This … -
Проблемы при установки extdirect на django проект
I installed the django project in python 3.6 and I want to use extjs 6 for server and client interaction. As a basis, I took an article written by the user "k0smita" - https://www.sencha.com/forum/showthread.php?130149-Samples-Examples-for-ExtJS-4-0-and-Django. After creating and configuring the django project, I added the extdirect.django package using pycharm. In the settings.py file, INSTALLED_APPS added 'extdirect.django', and when the application is launched, an error is produced first:module is not installed 'decorators'. To fix this, I installed the decorators package and now I get an error: ImportError: can not import name 'remoting'. In the requirements.txt file I have the following: decorators == 0.1.1 Django == 1.11.15 extdirect == 0.4 extdirect.django == 0.3 pytz == 2018.5 Why can an error "ImportError: can not import name 'remoting'" occur while the decorators package is installed on my project? -
gitlab runner hard reset
I am using gitlab-runner with shell executor. Every time I deploy with new source media files will be wiped out because runner will do hard-reset on my directory. I have check the documents, but it does not mention about this mechanics Question: How do I let runner just ignore whatever in the media directory rather than do hard-reset and my files all are gone? -
Best way to make a multiplayer turn-by-turn online game with python back end
As a project for a friend's birthday I am trying to create an online multiplayer game which is based on this derivative of poker we play. I only really know how to code python so started with that and have managed to create the game basics and I guess it could be a good back end for the game but don't know how to get it online or as an app so my friend could actually play it with me. Is there a way to use python code as a back end for an online game? I've read about Django and other frameworks but can't seem to get my head around how that would actually work. The UI for the game really doesn't matter too much as long as theres some way to take multiple user inputs. Appreciate any help and apologies if I use any wrong terminology Im self taught for the most part -
dns could not translate host name in docker
here is my docker file : FROM ubuntu:18.04 MAINTAINER bussiere "bussiere@toto.fr" EXPOSE 8000 RUN echo "nameserver 8.8.8.8" >> /etc/resolv.conf RUN echo "nameserver 80.67.169.12" >> /etc/resolv.conf RUN echo "nameserver 208.67.222.222" >> /etc/resolv.conf #RUN echo "dns-nameservers 8.8.8.8 8.8.4.4 80.67.169.12 208.67.222.222" >> /etc/network/interfaces ENV LANG C.UTF-8 ENV TZ=Europe/Paris RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone RUN apt-get update -y RUN apt-get install -y --no-install-recommends apt-utils RUN apt-get install -y python3 python3-pip python3-dev build-essential libpq-dev RUN python3 -m pip install pip --upgrade RUN python3 -m pip install pipenv RUN export LC_ALL=C.UTF-8 RUN export LANG=C.UTF-8 COPY app /app WORKDIR /app RUN pipenv --python 3.6 RUN pipenv install -r requirements.txt ENTRYPOINT ["pipenv"] CMD ["run","python", "manage.py", "collectstatic", "--noinput"] CMD ["run","python", "manage.py", "runserver", "0.0.0.0:8000"] Here is the error : psycopg2.OperationalError: could not translate host name "toto.postgres.database.azure.com" to address: Temporary failure in name resolution with the command : docker run --rm -it -p 8000:8000 admin_marque When i try to open localhost:8000 in a browser. The main goal is to deploy it on azure It's a django app, i know i don't have to user django runserver in prod but i'am ine the process of debugging. And i'am sure that the url of the database is good. -
Django migrate when model was previously deleted
When I do python manage.py migrate the desired model doesn't appear in my postgres database. I previously deleted all the tables and then migrated it again and it worked but I don't want that because I have loaded many data in the tables that I will have to load again. How to migrate only a certain model. -
Django - List Filter field in related model as parameter_name
I made a custom filter based on SimpleListFilter. I need to do a query on a related many-to-many model, but the endpoint URL needs to contain an __in for the results to actually show. Say, like this: http://localhost:8000/admin/mymodel/relatedmodel/?field=1234 to .../?field_in=1234 Since I made a custom filter, I cannot simply use a relation in the simple list declaration, like this: list_filter = ('relatedmodel__field'), because it is a custom filter, it needs to be declared list_filter = (CustomFilter,) So I really need to pass that __in parameter. I thought of using the parameter_name in the parameter_name declaration of the ListFilter, but that doesn't work because it doesn't recognize it as a field in my model. What can I do? Here is a snippet of what I'm trying to achieve, it's not the complete filter code. class CustomFilter(SimpleListFilter): title = 'custom' parameter_name = ->>> needs to be field__in! def queryset(self, request, queryset): if self.value(): return queryset.filter(relatedmodel__field=self.value()) Any help is greatly appreciated! -
Django ForeignKey relationship is not working
There should be a table like 'book_book_author' due to the Foreign Key relationships. Otherwise I cannot access the Author.book_set. But I tried on other models, the foreign key field worked perfectly. It only doesn't work for the Author model and the Book model. class Author(models.Model): name=models.CharField(max_length=255) def __str__(self): return self.name class Book(models.Model): title = models.CharField(max_length=255) pub_date = models.DateField() publisher = models.CharField(max_length=255) language = models.CharField(max_length=255) print_length = models.DecimalField(max_digits=6, decimal_places=0) price = models.DecimalField(max_digits=10, decimal_places=2) authors=models.ForeignKey(Author, on_delete=models.CASCADE) def __str__(self): return self.title The database: mysql> show tables; +-------------------------------+ | Tables_in_eshop | +-------------------------------+ | account_user | | account_user_groups | | account_user_user_permissions | | auth_group | | auth_group_permissions | | auth_permission | | book_author | | book_book | | django_admin_log | | django_content_type | | django_migrations | | django_session | +-------------------------------+ 12 rows in set (0.00 sec) How can I fix this issue? -
Failed to establish a new connection: [Errno 10061] No connection could be made because the target machine actively refused it
I am keep getting this error: ConnectionError at /entities/pull-ipam-types/ HTTPConnectionPool(host='10.30.0.10', port=7777): Max retries exceeded with url: /devices/resources/IPamTypes/ (Caused by NewConnectionError(': Failed to establish a new connection: [Errno 10061] No connection could be made because the target machine actively refused it',)) at this function: `def pull_ipam_types(request): #ftp_host = FTPConfiguration.objects.all()[0].FTP_HOST #url = 'http://' + ftp_host + ':7777/devices/resources/IPamTypes/' # resp = requests.get(url, headers={'User-Agent': 'Definitely-Not-Requests'}, auth = ('user', '123456')) resp = requests.get('http://' + FTPConfiguration.objects.all()[0].FTP_HOST + ':7777/devices/resources/IPamTypes/', auth=('user', '123456')) #olivera auth=('user', '123456')) ret_message = 'Pulled successfully. ' # 1) get old types old_ipam_types = [] for one_type in IpamType.objects.all(): old_ipam_types.append(one_type.type) # 2) get new types new_ipam_types = [] if resp.status_code != 200: # This means something went wrong. messages.error(request, 'Error ' + resp.status_code + ' during REST request, review your FTP configuration.') return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/')) else: for one_type in resp.json(): new_ipam_types.append(one_type) # 3) create list of added and removed. added_ipams = [] for new_ipam in new_ipam_types: is_found = False # current old still exists for old_ipam in old_ipam_types: if old_ipam == new_ipam: is_found = True # new_ipam added if not is_found: added_ipams.append(new_ipam) removed_ipams = [] for old_ipam in old_ipam_types: is_found = False # current old still exists for new_ipam in new_ipam_types: if old_ipam == new_ipam: … -
How to get option for select tag in forms.py from my model?
Please help me to solve this problem! I have form for job application and I have this in my models.py: class Vacancy(models.Model): vacancy_title = models.CharField(max_length=100) vacancy_description = models.TextField() data = models.DateTimeField(default=timezone.now) contact_person = models.CharField(max_length=50) phone_number = models.CharField(max_length=30) mail = models.EmailField(); def __str__(self): return self.vacancy_title A user must choose one of the vacancies <select name="job_field" id="job_field"> {% for vacancy in vacancies %} <option value="">{{ vacancy.vacancy_title }}</option> {% endfor %} </select> Now in the forms.py I cannot connect vacancy_title to the choice of the select group(Choice Field). How to do it? -
Django form field customizing
I have simple ModelForm and Im using django-bootstrap4 to render my form. this is my html code: <div class="form-step-0" role="form" data-toggle="validator"> {% for field in itemForm %} {% bootstrap_field field %} <div class="help-text with-errors"> {% endfor %} </div> The code works fine by displaying forms but I need to put my div behind of every input fields like this: <div> <label></label> <input> <div class="help-text with-errors"></div> <label></label> <input> <div class="help-text with-errors"></div> </div> my code is displaying like this: <div> <label></label> <input> <label></label> <input> <div class="help-text with-errors"></div> </div> -
What is the point of not using class-based views?
Here, you can find things like def index(request): return HttpResponse("Hello, world. You're at the polls index.") and then on tutorial 03, you get def detail(request, question_id): return HttpResponse("You're looking at question %s." % question_id) and later on: def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] template = loader.get_template('polls/index.html') context = { 'latest_question_list': latest_question_list, } return HttpResponse(template.render(context, request)) Why this? Why not talk immediately about class-based and generic views? What is the point of this code? Why not do: class IndexView(View): def get(self, request): return HttpResponse("Hello, world. You're at the polls index.") ? Or for the last one: class IndexView(request): template_name = 'polls/index.html' def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context['latest_question_list'] = Question.objects.order_by('-pub_date')[:5] return context It's exactly the same number of code lines. Here all the people I've met (and my students) start with the samples in the documentation and the code end up in an horrible mess. When you start with this code, all the project is less easy to read thus less easy to maintain and thus... you like less Django in the best case, in the worse case if it's used by the company it's less maintanable hence it costs more. IMHO Even for a brand new project or to learn … -
django database emptied when I create a new git branch on my project
Whilst I am working on my django project (which has a single app), I wanted to create a new git branch so I can test a new design feature, however when I am on the new branch I cannot seem to find any of my previously populated data in my database (I am using sqlite3)....why could that be the case an how can I fix this? -
Django database query: How to filter objects by date to warn user if >= 8 hours?
I've got a field in one model like class Project(models.Model): date = fields.DateField(auto_now=False) user = models.ManyToManyField(User, related_name="projects", blank=True) work_times = models.FloatField(default=1, verbose_name="work times(hours)") Now, I would like to filter a user's work_times(different value) by a date(same date), the purpose is to warn or remind users when they create new project, because user can't have new project if his projects' work_times >= 8 hours on a day, I already got values as below [{'work_times': 1.0, 'date': datetime.date(2018, 6, 25)}, {'work_times': 1.0, 'date': datetime.date(2018, 6, 28)}, {'work_times': 1.0, 'date': datetime.date(2018, 6, 28)}, {'work_times': 1.0, 'date': datetime.date(2018, 6, 28)}, {'work_times': 1.0, 'date': datetime.date(2018, 6, 28)}, {'work_times': 1.0, 'date': datetime.date(2018, 6, 28)}, {'work_times': 1.0, 'date': datetime.date(2018, 6, 28)}, {'work_times': 1.0, 'date': datetime.date(2018, 6, 28)}, {'work_times': 1.0, 'date': datetime.date(2018, 6, 28)}, {'work_times': 1.0, 'date': datetime.date(2018, 6, 28)}, {'work_times': 1.0, 'date': datetime.date(2018, 6, 28)}, {'work_times': 1.0, 'date': datetime.date(2018, 6, 28)}, {'work_times': 1.0, 'date': datetime.date(2018, 6, 28)}] one user has several projects with different work_times on a date, how to filter user A's total work_times on a date in his all projects? Thanks for your help! -
Django_Rest_Framework Serializer Field "source" attribute is not working
I am trying to build a DRF Serializer that uses different names for the fields than the underlying Django Model. I thought that this is what the "source" attribute was for. Here is some code: models.py: class MyModel(models.Model): my_snake_case_field = models.DateTimeField() serializers.py: class MySerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = ('id', 'myCamelCaseField', ) myCamelCaseField = serializers.DateTimeField(source='my_snake_case_field') But when I try to view that I get the following error: ImproperlyConfigured at /api/mymodel/1/ Field name myCamelCaseField is not valid for model MyModel. Any ideas where I'm going wrong? -
has_add_permission not working in Django 2.1
I have a TabularInline inherited class, where I removed the possibility to add new objects. class ItemInline(admin.TabularInline): model = Item fields = ('name', 'is_active', 'updated_at', 'updated_by') readonly_fields = ('updated_at', 'updated_by') view_on_site = False def has_add_permission(self, request): return False This is working in Django 2.08. I moved to Django 2.1 converted the method to: def has_add_permission(self, request, object): return False as is implemented now, and trows me a key error in the template to the fields (it get the first one 'name') I don't understand, why? I want to use 2.1 for other features. -
Hello Django renames the model of my app
After having a typo and mistyped pricing as prising I've removed the app, deleted the tables in the database then made the new app copied the models.py from the old app, I did a backup, then the error persist here is the img and code from the models here is the models.py class PriceList(models.Model): class Meta: verbose_name = _("ценоразпис") verbose_name_plural = _("ценоразписи") name = models.CharField(blank=False, null=False, max_length=300, verbose_name="наименование") description = models.CharField(blank=False, null=False, max_length=300, verbose_name="Описание") def show_name(self): return '{}'.format(self.name) def show_description(self): return '{}'.format(self.description) def __str__(self): return '{}'.format(self.name) class PriceListItem(models.Model): class Meta: verbose_name = _("елемент от ценоразпис") verbose_name_plural = _("елементи от ценоразпис") ordering = ['id'] price_list = models.ForeignKey(PriceList, blank=False, null=False, verbose_name="ценоразпис", on_delete=models.CASCADE) title_bg = models.CharField(blank=False, null=False, max_length=200, verbose_name="наименование BG") description_bg = models.CharField(blank=False, null=False, max_length=200, verbose_name="Описание BG") title_en = models.CharField(blank=False, null=False, max_length=200, verbose_name="наименование EN") description_en = models.CharField(blank=False, null=False, max_length=200, verbose_name="Описание EN") price_bg = models.DecimalField(blank=False, null=False, decimal_places=PRICE_DECIMAL_PLACES, max_digits=PRICE_DECIMAL_DIGITS, verbose_name="BGN") price_en = models.DecimalField(blank=False, null=False, decimal_places=PRICE_DECIMAL_PLACES, max_digits=PRICE_DECIMAL_DIGITS, verbose_name="EUR") def __str__(self): return '{}'.format(self.id) and the admin.py from django.contrib import admin from pricing.models import PriceList, PriceListItem class PriceListItemInline(admin.TabularInline): model = PriceListItem class PriceListAdmin(admin.ModelAdmin): model = PriceList inlines = [PriceListItemInline, ] list_display = ('name', 'description') admin.site.register(PriceList , PriceListAdmin) -
Django ORM DateTimeField ExpressionWrapper QuerySet annotation
According to the Django documentation here: https://docs.djangoproject.com/en/2.1/ref/models/expressions/#using-f-with-annotations I can do date calculations using ExpressionWrapper. I tried to use it like this: sprints = Sprint.objects.annotate( duration=models.Case( models.When( Q(started__isnull=False) & Q(done__isnull=False), then=models.Value( models.ExpressionWrapper( (models.F('done') - models.F('started')), output_field=models.DateTimeField() )) ), models.When( Q(started__isnull=False) & Q(done__isnull=True), then=models.Value( models.ExpressionWrapper( (Now() - models.F('started')), output_field=models.DateTimeField(), )) ), output_field=models.DateTimeField() )).values_list('name', 'planned', 'started', 'done', 'duration') But I get an error from pytz trying to do auto-localisation on the ExpressionWrapper: Traceback (most recent call last): File "/home/phirt/local/venv/core3/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/home/phirt/local/venv/core3/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/phirt/local/venv/core3/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/phirt/local/venv/core3/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/phirt/local/venv/core3/lib/python3.6/site-packages/rest_framework/viewsets.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "/home/phirt/local/venv/core3/lib/python3.6/site-packages/rest_framework/views.py", line 483, in dispatch response = self.handle_exception(exc) File "/home/phirt/local/venv/core3/lib/python3.6/site-packages/rest_framework/views.py", line 443, in handle_exception self.raise_uncaught_exception(exc) File "/home/phirt/local/venv/core3/lib/python3.6/site-packages/rest_framework/views.py", line 480, in dispatch response = handler(request, *args, **kwargs) File "/home/phirt/src/core3/src/backend/portal/views/api/transformation.py", line 766, in get_sprint_data_csv for sprint in sprints: File "/home/phirt/local/venv/core3/lib/python3.6/site-packages/django/db/models/query.py", line 272, in __iter__ self._fetch_all() File "/home/phirt/local/venv/core3/lib/python3.6/site-packages/django/db/models/query.py", line 1179, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/home/phirt/local/venv/core3/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1011, in apply_converters value = converter(value, expression, connection) File "/home/phirt/local/venv/core3/lib/python3.6/site-packages/django/db/backends/mysql/operations.py", line 247, in convert_datetimefield_value value = timezone.make_aware(value, self.connection.timezone) File "/home/phirt/local/venv/core3/lib/python3.6/site-packages/django/utils/timezone.py", line … -
Django microservices within Docker
I have the following docker-compose.yml: version: '3.6' services: db: image: postgres:10.4 volumes: - postgres_data:/var/lib/postgresql/data/ cache: image: redis:4.0.10 volumes: - redis_data:/data web: build: . image: dockerdjangoexample command: bash -c "gunicorn demosite.wsgi:application -b 0.0.0.0:8000" volumes: - .:/code depends_on: - db - cache nginx: image: nginx:1.15.2-alpine ports: - "8000:8000" volumes: - ./docker-config/nginx:/etc/nginx/conf.d depends_on: - web volumes: postgres_data: redis_data: The Dockerfile is: FROM python:3.6.5 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /code COPY . /code/ RUN pip install --upgrade pip RUN pip install pipenv RUN pipenv install --deploy --system --skip-lock --dev The Nginx config file is: upstream web { ip_hash; server web:8000; } server { location / { proxy_pass http://web/; } listen 8000; server_name localhost; } This all works perfectly. What im trying to figure out now is how I can add a second Django app into the mix so I can create a microservice environment. For example, the existing web app from above would be an API that handles user registration / sign in etc. I would like to add another Django API into the mix that would do something else and would also use its own database. The first API would be used through urls starting with /api/users and the second API … -
how to create temporary tokens django
I have found that we can make temporary tokens with this in Django : pip install Django-rest-framework-temporary-tokens but I don't know how to use this method. does anybody know how to use this or any other way to make temporary tokens in Django ?? -
UploadFileForm(request.POST, request.FILES) return null
I'm trying to upload files using django and I wrote the following codes: from django import forms class UploadFileForm(forms.Form): title = forms.CharField(max_length=50) file = forms.FileField() def uploadexcel(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) print(form) print(form.is_valid()) print(form.errors) if form.is_valid(): print("success") else: form = UploadFileForm() return render(request,'index.html', {'form': form}) I can get the value of request.POST and request.FILES. I use form = UploadFileForm(request.POST, request.FILES) to build form but the value of form is null -
Reset Password in django?
I am following a bolg to reset the password in django. First it say to add : EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' # During development only in settings.py file. But I want to deploy my web application in production. So what steps should I take care about? Will this tutorial is safe for the production too? The bolg link is given below: https://simpleisbetterthancomplex.com/tutorial/2016/09/19/how-to-create-password-reset-view.html -
Update the attributes of the Children(FK) Model when the Parent Model attributes changes - Django Admin
I have multiple connected to FK Models, each one of them having a state -is_active attribute. class Parent(models.Model): name = models.CharField(max_length=255) # state is_active = models.BooleanField(choices=BOOL_TYPE_CHOICES, default=BOOL_TYPE_NO) class Child1(models.Model): name = models.CharField(max_length=255) # state is_active = models.BooleanField(choices=BOOL_TYPE_CHOICES, default=BOOL_TYPE_NO) class Child2(models.Model): name = models.CharField(max_length=255) # state is_active = models.BooleanField(choices=BOOL_TYPE_CHOICES, default=BOOL_TYPE_NO) What I need (for Django Admin): When the is_active value becomes False for the Parent, I want the Child1, Child2 is_active to become also False if is True. If the Child try to make is_active True, but the Parent is_active=False, to not be allowed. I tried to do it at the Model level overriding save, but the Admin save is kind of passing over, Model save -
Access data saved in ModelForm in views form_valid function
Suppose I have two models: Payment and User models.py class Payment(models.Model): user = models.ManyToManyField(A, blank=True) class User(models.Model): name = models.CharField(...) has_paid = models.BooleanField(...) forms.py CreatePayment(forms.ModelForm): class Meta: fields = '__all__' Now, when I submit the CreatePayment form, I can select multiple users for each payment (and vice versa, because multiple users can be paid for in a single payment and each user can make multiple payments). Is there a way I can edit the form_valid method in views.py so that I can make the has_paid field True only for the users selected in the CreatePayment form? Thanks in advance.