Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Admin - Show ManyToOne data on a model in admin
I have 2 models Patient and History. I would like to show all History of a Patient inside the Patient model in django admin as table. I was thinking to use ManyToOne field as one patient can have more than 1 history and 1 history is only owned by 1 patient. In the Patient model admin I would like to also be able to add a new history. I have tried to use ManyToMany field but doesn't looks like the solution. Can anyone please help me on how to solve this? Below is the code: class Patient(models.Model): name = models.CharField(max_length=100) class History(models.Model): patient = models.ForeignKey(Patient, on_delete=models.CASCADE) diagnosis = models.TextField() Thanks in advance. -
How to keep some variables of a template after post request in Django
I’ve been using Django for some time and I have a kind of question about how I code after I’ve been on forums. My heaviest page requires generating several objects that I send in the context of my view. I organized my view this way: def myFunction(request): if request.method == 'POST' and "some_Button" in request.POST : #when click on a button #update object_2 elif request.method == 'POST' and "another_Button" in request.POST : #when click on another button #update object_1 else: #part executed at first load myFunction.object_1 = #some code myFunction.object_2 = #some code myFunction.object_3 = #some code context = {'object_1' : myFunction.object_1, 'object_2' : myFunction.object_2, 'object_3' : myFunction.object_3} return render(request, 'index.html', context) I had found the practice of writing my context's variables like MyFunction.myVariable in order not to have to regenerate them all when I just want to change an object. Like here when I click on one of the buttons I don’t have to regenerate the other variables. However, I am aware that this is not a good practice and I would like to change that. Except that all the examples I find need to regenerate all the variables each time. I thought about using the cache to temporarily … -
AWS instance accessible by IP only and but not with domain name in Route53
I really don't know what I am doing wrong and I have searched for solution and all to no avail. My configurations are all okay. Scenario I have deployed my django app on EC2 ubuntu and I am able to access deployed application either http://ip-address/en/ or http://ip-address:8000/en/ but not on http://domain/en/ nor http://domain:8000/en/ I get ERR_CONNECTION_REFUSED error when I access with the domain name. In Route53, an A record exist which was set 3 days ago. When I ping the ip address it returns this PING ip-address (ip-address) 56(84) bytes of data. 64 bytes from ip-address: icmp_seq=1 ttl=63 time=0.434 ms 64 bytes from ip-address: icmp_seq=2 ttl=63 time=0.425 ms 64 bytes from ip-address: icmp_seq=3 ttl=63 time=0.357 ms 64 bytes from ip-address: icmp_seq=4 ttl=63 time=0.464 ms 64 bytes from ip-address: icmp_seq=5 ttl=63 time=0.440 ms 64 bytes from ip-address: icmp_seq=6 ttl=63 time=0.422 ms 64 bytes from ip-address: icmp_seq=7 ttl=63 time=0.420 ms 64 bytes from ip-address: icmp_seq=8 ttl=63 time=0.498 ms When I ping the domain PING domain.com (ip-address) 56(84) bytes of data. 64 bytes from ec2-ip-address.compute-1.amazonaws.com (ip-address): icmp_seq=1 ttl=63 time=4.53 ms 64 bytes from ec2-ip-address.compute-1.amazonaws.com (ip-address): icmp_seq=2 ttl=63 time=0.483 ms 64 bytes from ec2-ip-address.compute-1.amazonaws.com (ip-address): icmp_seq=3 ttl=63 time=0.385 ms 64 bytes from ec2-ip-address.compute-1.amazonaws.com (ip-address): … -
Django select2 modify standard text
I use django select2, the standard text of no results is "no results found", i want to change that. In my template i have: $('.django-select2').djangoSelect2({ language: { noResults: function() {return "Geen resultaten"; } }, }); This is working fine, however i want to do this in django directly in my form This is the important part of my form: person = forms.ModelChoiceField( queryset=User.objects.all(), required=True, widget=PersonWidget())---> this is the custom widget, see below and the custom widget: class PersonWidget(s2forms.ModelSelect2Widget): def build_attrs(self, *args, **kwargs): attrs = super().build_attrs(*args, **kwargs) attrs['data-placeholder'] = "Zoeken" attrs['data-minimum-input-length'] = 0 return attrs search_fields = [ "first_name__icontains", "last_name__icontains", "email__icontains" ] -
How to create new log file for every user by logging Django
I have logger for every user if he`s log in and log out How am i suppose to say logger create every time new file for each user with his nickname. I dont need all info about all users in one log file i want to split it by different files settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'log_in_out_format': { 'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}', 'style': '{', }, }, 'handlers': { 'log_in_out_file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': 'loggers/log_in_out/log.log', 'formatter': 'log_in_out_format', }, }, 'loggers': { 'authentication': { 'handlers': ['log_in_out_file'], 'level': 'INFO', 'propagate': False, } }, } in views.py i have something like that: login(request, user) logger.info(f'{request.user.email} logged in ') logger.warning(f'{request.user.email} logged out') logout(request) -
Django Rest Serializer: How to get hyperlink when read, use id when create or update?
models.py class User(models.Model): name = models.CharField(max_length=300) class Booking(models.Model): time = models.DateTimeField() user_id = models.ForeignKey(User, related_name='booking', on_delete=models.CASCADE) serializers.py class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = '__all__' class BookingSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Booking fields = '__all__' With the above code, I would get an error user_id ":["Incorrect type. Expected URL string, received int."] during creating booking process. I believe this because HyperlinkedModelSerializer expect a URL for the foreign key field. However, passing an ID during creating or updating is way more convenient. How can I edit this so that it can use id when create or update and return hyperlink only when read? -
Nginx and guncorn active and running but the website is not loading
I am new to the nginx and gunicorn setup I am trying to setup my django project in production server with the help of nginx and gunicorn but facing some issues any kind of help will be appreciated. This is my gunicorn status sudo systemctl status gunicorn ● gunicorn.service - gunicorn daemon for EPC Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: active (running) since Mon 2023-03-13 18:09:20 IST; 13min ago TriggeredBy: ● gunicorn.socket Main PID: 797016 (gunicorn) Tasks: 4 (limit: 28757) Memory: 91.8M CGroup: /system.slice/gunicorn.service ├─797016 /usr/bin/python3 /home/web/.local/bin/gunicorn --access-logfile - --workers 3 --bind 0.0.0.0:8001 EPC.wsgi:application ├─797018 /usr/bin/python3 /home/web/.local/bin/gunicorn --access-logfile - --workers 3 --bind 0.0.0.0:8001 EPC.wsgi:application ├─797019 /usr/bin/python3 /home/web/.local/bin/gunicorn --access-logfile - --workers 3 --bind 0.0.0.0:8001 EPC.wsgi:application └─797020 /usr/bin/python3 /home/web/.local/bin/gunicorn --access-logfile - --workers 3 --bind 0.0.0.0:8001 EPC.wsgi:application Mar 13 18:09:20 EHTP-DB-WEB systemd[1]: Started gunicorn daemon for EPC. Mar 13 18:09:20 EHTP-DB-WEB gunicorn[797016]: [2023-03-13 18:09:20 +0530] [797016] [INFO] Starting gunicorn 20.1.0 Mar 13 18:09:20 EHTP-DB-WEB gunicorn[797016]: [2023-03-13 18:09:20 +0530] [797016] [INFO] Listening at: unix:/run/gunicorn.sock (797016) Mar 13 18:09:20 EHTP-DB-WEB gunicorn[797016]: [2023-03-13 18:09:20 +0530] [797016] [INFO] Using worker: sync Mar 13 18:09:20 EHTP-DB-WEB gunicorn[797018]: [2023-03-13 18:09:20 +0530] [797018] [INFO] Booting worker with pid: 797018 Mar 13 18:09:20 EHTP-DB-WEB gunicorn[797019]: [2023-03-13 18:09:20 +0530] [797019] … -
Getting django model entries with a more complex query (joining with no direct relationship)
I am trying to get the model entry for a certain query where I'm joining with columns that are not the ForeignKey of the table. My tables (models) look like this (simplified with necessary columns): class PE(models.Model): # table p_e p_e_id = models.AutoField(primary_key=True) p_o = models.ForeignKey('PO', models.DO_NOTHING) p_r = models.ForeignKey('PR', models.DO_NOTHING) s_o = models.ForeignKey('SO', models.DO_NOTHING) item = models.ForeignKey(Items, models.DO_NOTHING, related_name='pe_item') p_e_is_possible = models.BooleanField() class EIH(models.Model): # table e_i_h e_i_h_id = models.AutoField(primary_key=True) target_item = models.ForeignKey('Items', models.DO_NOTHING,related_name='target_item') component_item = models.ForeignKey('Items', models.DO_NOTHING,related_name='component_item') p_o = models.ForeignKey('PO', models.DO_NOTHING) p_r = models.ForeignKey('PR', models.DO_NOTHING) class Items(models.Model): item_id = models.AutoField(primary_key=True) The Query I am currently using without models looks like this: SELECT * FROM p_e INNER JOIN e_i_h ON e_i_h.target_item_id = p_e.item_id AND e_i_h.component_item_id = -1 AND (e_i_h.p_o_id = p_e.p_o_id OR (p_e.p_e_is_possible = True AND p_e.s_o_id != -1) ) Is it possible to get the same queryset result as the Query only using models? The result is one entry from the table EIH with the query. I tried to filter the EIH objects with joining over the items table: pe_queryset = PE.objects.filter(item_id=15) for pe in pe_queryset: erp = EIH.objects.get(Q(p_o_id= pe.p_o.p_o_id) | Q(pe.p_e_is_possible=True), item_id=pe.item.item_id, component_item_id=-1) I also tried lookup: erp = EIH.objects.get(Q(p_o_id= pe.p_o.p_o_id) | Q(target_item__p_e__p_e_is_possible=True), item_id=pe.item.item_id, component_item_id=-1) The problem … -
Meta.ordering is deprecated option, what is the alternativeoption
I have updated my Django project from version 2 on version 3.2, and I have found in documentation that Meta.ordering option is deprecated. Actually this is in documentation: 'Meta.ordering will be ignored in such queries staring in Django 3.2'. I would like to if there is some another attribute in Meta class or in my main class in order to have same order impact. Project is really big, so I can not use order_by() with every filter. Database is PostgreSQL. Thanks in advance... -
Django channels, UserWarning: async_to_sync was passed a non-async-marked callable
I am using Django channels for the notification system,i want to send a notification to the associated store when an order is created, i create Notification model to save all previous notifications and in my post_save order signal i create notification instance. I'm using WebsocketConsumer customer type, without any authentication 'for know'. notification_models.py from django.db import models class Notification(models.Model): user = models.ForeignKey('connect.User', on_delete=models.CASCADE) store = models.ForeignKey('stores.Store', on_delete=models.CASCADE) message = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created_at'] indexes = [ models.Index(fields=['user']), models.Index(fields=['store']), ] def __str__(self): return f'{self.store.name}: {self.message}' url.py from rest_framework.urlpatterns import format_suffix_patterns from .consumers import StoreConsumer from django.urls import path websocket_urlpatterns = [ # wscat -c ws://localhost:8083/ws/store/yani/notifications path('ws/store/<store_slug>/notifications/', StoreConsumer.as_asgi()), ] consumers.py from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync class StoreConsumer(WebsocketConsumer): def connect(self): self.store_slug = self.scope['url_route']['kwargs']['store_slug'] self.store_group_name = f'store_{self.store_slug}' async_to_sync(self.channel_layer.group_add)( self.store_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): pass def send_notification(self, event): message = event['message'] self.send(text_data=message) notification_signals.py from django.dispatch import receiver from channels.layers import get_channel_layer from asgiref.sync import async_to_sync from stores.models import Notification from django.db.models.signals import post_save @receiver(post_save, sender=Notification) def send_notification(sender, instance, **kwargs): channel_layer = get_channel_layer() print('channel_layer > > ',channel_layer) async_to_sync(channel_layer.group_send)( f'store_{instance.store.id}', { 'type': 'store_notification', 'message': instance.message } ) asgi.py import os from django.core.asgi import get_asgi_application from channels.routing import … -
Django project guidance required
This is a small project given to me. I need help. If possible, give me the code files in Django: Create a REST api to be consumed by a mobile app which tell you if a number is spam, or allow you to find a person’s name by searching for their phone number. Each registered user of the app can have zero or more personal “contacts”. The “global database” is basically the combination of all the registered users and their personal contacts (who may or may not be registered users). The UI will be built by someone else - you are simply making the REST API endpoints to be consumed by the front end. Data to be stored for each user: Name, Phone Number, Email Address. Registration and Profile: A user has to register with at least name and phone number, along with a password, before using. He can optionally add an email address. Only one user can register on the app with a particular phone number. A user needs to be logged in to do anything; there is no public access to anything. You can assume that the user’s phone contacts will be automatically imported into the app’s database … -
Cutting stock problem methods and techniques
I have taken an interest in creating a web app using React based on cutting stock problem. I have some questions about the topic: Should i pair React with Django or is there better alternative? I'm gonna implement two algorithms each for 1 Dimensional and 2 Dimensional (So 4 in total). What algorithms should i implement? Is there any recommended resources online that will aid me in my work? -
No module named 'debug_toolbar.urls' : version 3.1.1 installed
settings.py INSTALLED_APPS = ( 'debug_toolbar', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', ) urls.py if DEBUG: import debug_toolbar urlpatterns += url('__debug__/', include('debug_toolbar.urls')) requirements.txt Django django-debug-toolbar==3.1.1 its showing No module named 'debug_toolbar.urls' when testing on the server. -
django pass id in HttpResponseRedirect
I have page that shows a usecase details with edit button that redirects to editing the usecase. my views.py: def edit_usecase(request, ucid): try: usecase_details = Usecase.objects.filter(usecase_id=ucid) if request.method == "POST": usecase_name = request.POST['usecase_name'] usecase_description = request.POST['usecase_description'] usecase_details = Usecase.objects.get(usecase_id=ucid) usecase_details.user_name = usecase_name usecase_details.user_email = usecase_description usecase_details.save() if usecase_details: messages.success(request, "Usecase Data was updated successfully!") return HttpResponseRedirect('/usecase-details/usecase_details.usecase_id') else: messages.error(request, "Some Error was occurred!") return HttpResponseRedirect('/usecase-details/uecase_details.usecase_id') return render(request, 'UpdateUsecase.html', {'usecase_details':usecase_details[0]}) except: messages.error(request, "Some Error was occurred!") return HttpResponseRedirect('/usecase-details/usecase_details.usecase_id') my url: path('update-usecase/<str:ucid>', av.edit_usecase), my template: <div class="row d-flex"> <div class="col-12 mb-4"> <div class="card border-light shadow-sm components-section d-flex "> <div class="card-body d-flex "> <div class="row mb-4"> <div class="card-body"> <div class="row col-12"> <div class="mb-4"> <h3 class="h3">Edit usecase details:</h3> </div> <!-- <li role="separator" class="dropdown-divider border-black mb-3 ml-3"></li> --> <form action="/update-usecase/{{usecase_details.usecase_id}}" method="POST"> {% csrf_token %} <div class="form-row mb-4"> <div class="col-lg-8 mr-f"> <label class="h6" for="exampleFormControlTextarea1">Usecase name:</label> <input value="{{usecase_details.usecase_name}}" type="text" name="usecase_name" class="form-control" placeholder="Name of Employee" required> </div> <div class="col-lg-8 mr-f"> <label class="h6" for="exampleFormControlTextarea1">User Name:</label> <input value="{{usecase_details.usecase_description}}" type="text" name="usecase_description" class="form-control" placeholder="Name of Employee" required> </div> </div> <input type="submit" class="btn btn-primary" value="Submit Changes"> </form> </div> </div> </div> </div> </div> </div> </div> How can I pass the usecase id in HttpResponseRedirect to redirect me to the same page after updating the data> -
How can I allow user to log in with email and to be created with additional fields
I want users to be able to log in using their email address and password. For the registration form, I need to include the following fields: Username, Email, Phone Number, Password, Repeat Password, and Address. All users should be created using these fields. How can I do this please? -
Increase number of Postgres pool connections for each Uvicorn Worker of a Django Application
I am running an asynchronous Django server with django-postgrespool2 as its Database Engine on my local machine. No matter how I configure the pooling parameters, it creates only a certain amount of pool connections. This number seems to be directly proportional to the number of Uvicorn Workers I run for my application. The following parameters are configured in the settings.py DATABASE_POOL_CLASS = 'sqlalchemy.pool.QueuePool' DATABASE_POOL_ARGS = {"max_overflow": 500, "pool_size": 1000, "recycle": 300} I am using the QueuePool class of SQLAlchemy for queueing as mentioned in the official documentation of Django-Postgrespool2. Also, I have significantly incremented the pool size to 1000 and max_overflow to 500. After concurrently hitting requests with a load testing tool, what I have observed is, that the number of database connections in the pool only increase with the number of Uvicorn workers I have running. Even if I increment the pool size to 1000, the number of pool connections created are limited. My inferences, based on the number of Uvicorn workers I ran and the number of pool connections created are stated as follows: Number of Uvicorn Workers Pool Connections Created 5 80 6 96 7 112 8 128 9 144 10 160 50 773 The pool_size and … -
How to remove an annotate attribute from a Django query set?
I have a situation where I am annotating some values and I do not want those to be the output. qs = A.objects.annotate(data=...) I want to remove data before the serialization in my Django projects -
ImportError: Couldn't import Django?
when run with command python manage.py runserver crashes with the error The virtual environment is active, for some reason it does not see the packages that they are all installed.Virtual environment active packages all installed when run with command python manage.py runserver crashes with the error The virtual environment is active, for some reason it does not see the packages that they are all installed.Virtual environment active packages all installed -
There is an error when trying to order in python-django
Whenever I try to order something, I keep getting this error. Here is my views.py: if not request.user.is_authenticated: session = request.session cart = session.get(settings.CART_SESSION_ID) if cart: del session[settings.CART_SESSION_ID] else: customer = request.user.customer order, created = Order.objects.get_or_create( customer=customer, complete=False) order_products = OrderProduct.objects.filter(order=order) if order_products: order_product = order_products[0] else: order_product = OrderProduct.objects.create(order=order) order.save() messages.success(request, 'Заказ успешно оформлен. Проверьте свою электронную почту!!!') session = request.session del session[settings.CART_SESSION_ID] return redirect('product_list') Please can anyone help me to fix it? -
Remove "%...% in urls
My urls in django have %.... How can I change that? At first this was ok but suddenly changed at some point in my day. My views, models and urls are as follow: class Rant(UUIDModel, TitleSlugDescriptionModel, TimeStampedModel, models.Model): categories = models.ManyToManyField(Category) def slugify_function(self, content): return content.replace("_", "-").lower() def get_absolute_url(self): return reverse("rants:rant-detail", kwargs={"title": self.title}) def __str__(self): return self.title class RantDetailView(DetailView): model = Rant slug_field = "slug" slug_url_kwarg = "slug" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context path("<str:slug>/", RantDetailView.as_view(), name="rant-detail"), path("category/<slug:category>/", rant_category, name="rant-categories"),``` I have no Idea why the link on my localhost is `localhost:8000/first%20rant%20on%20rantr/` Does anyone know where I made a mistake? I'm expecting the urls to have `hyphens` in it like `http://localhost:8000/first-rant-on-rantr/` where did I make a mistake? -
Connecting to LND Node through a server-running Django Rest API
@swagger_auto_schema(tags=['Payment']) def get(self, request): url = ( "<instance address>" ) macaroon = connect.encoded_hex TLS_PATH ='tls.cert' headers = {"Grpc-Metadata-macaroon": macaroon} r = requests.get(url, headers=headers, verify=TLS_PATH) # disable SSL verification return Response(json.loads(r.text)) So I can connect and get the Info when sending a request from my local machine but it fails when sending request from my EC2 running on Elastic Beanstalk env with load balancer. I'm running a t3a.large instance type and Using Django as a framework. Can anyone help as by now I've tried many different solutions. This is the error I get : HTTPSConnectionPool(host='<host>', port=8080): Max retries exceeded with url: /v1/getinfo (Caused by SSLError(SSLError(1, '[SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl.c:1131)'))) THANK YOU -
Django rest_framework quantity is not incrementing in ecommerce project
models.py class Cartlist(models. user = models.ForeignKey(User, on_delete=models. created_at = models.DateField(auto_now_add=True) class Meta: ordering = ['id'] def __str__(self): return self.user.username class Items(models.Model): cart = models.ForeignKey(Cartlist, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) order = models.BooleanField(default=False) created_at = models.DateField(auto_now_add=True) class Meta: ordering = ['id'] def __str__(self): return '{}'.format(self.product) Views.py class AddCartView(generics.CreateAPIView): permission_classes = [IsAuthenticated] queryset = Items.objects.all() serializer_class = AddCartSerializer Serializer.py class AddCartSerializer(serializers.ModelSerializer): class Meta: model = Items fields = ['product'] def create(self, validated_data): user = self.context['request'].user product = self.validated_data['product'] if Cartlist.objects.filter(user=user): item = Items.objects.filter(cart__user=user,product=product) if item: item.quantity += 1 item.save() return item else: item = Items.objects.create(cart=Cartlist.objects.get(user=user),**validated_data) item.save() return item else: cart = Cartlist.objects.create(user=user) cart.save() item = Items.objects.create(cart=cart,**validated_data) item.save() return item Exception Value:'QuerySet' object has no attribute 'quantity' if the product is already exists, then increment the quantity field by 1. Default value is 1 if the user add same product into their cart list the product quantity must be increment by 1 -
Reverse for 'edituser' with arguments '('',)' not found
I have this function in Django function editFunc(id) { $.ajax({ type: "POST", url: "{% url 'edituser' id %}", data: { id: id }, dataType: 'json', success: function(res) { $('#ProductModal').html("Modifica dati"); $('#product-modal').modal('show'); $('#id').val(res.id); $('#username').val(res.username); $('#first_name').val(res.first_name); $('#last_name').val(res.last_name); $('#email').val(res.email); $('#is_staff').val(res.is_staff); $('#password').val(""); $("#password").attr("required", false); $("#passl").html('Password (lasciare il campo in bianco per non modificare la password).'); } }); } I checked the value of id and is ok But i have the error: Reverse for 'edituser' with arguments '('',)' not found To better explain: id="1"; url: "{% url 'edituser' id %}", doesn't work url: "{% url 'edituser' "1" %}", works What is wrong and howto solve ? -
Django - Display 2 Datefields for a Course. When it starts and when it ends
class Kurs(models.Model): # Kursleiter = # Thema name = models.CharField(max_length=200) beschreibung = models.TextField(null=True, blank=True) # teilnehmer = # auto_now macht immer, wenn wir was ändern einen Timestamp updated = models.DateTimeField(auto_now=True) # auto_now_add macht nur einen Timestamp created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name This is my Models.py Class. I want to create 2, in the Admin Panel visible Fields where I can enter the Start Date and End Date for my Courses. When I tried it this way: start_date = models.DateField(default=timezone.now) end_date = models.DateField(default=timezone.now) start_time = models.TimeField() end_time = models.TimeField() My Commandline Displays this Error: It is impossible to add a non-nullable field 'end_date' to kurs without specifying a default. This is because the database needs something to populate existing rows. I hoped to get 2 Date Fields in my Admin Panel in the View, showed in the ImageAdmin Panel, where I wish to display -
How to add different ranges for a model fields in django admin page
I need sample data like below , i mean if a entry created 1,10 a new row should automatically populated with new values 11 to 100, if i edit the next row i.e making 100 to 40 new row should be created with 41 to 100, i should not able to edit start value. Can anyone suggest if their is any package or any in build approcah? start_value end_value 1 10 11 40 41 100 Models.py class A(Model): start_value = IntegerRangeField(min_value=-100, max_value=100, default=0) end_value = IntegerRangeField(min_value=-100, max_value=100, default=100) class B(Model): ranges=ManytoManyField(A) forms.py class Aform(ModelForm): class Meta: model = A admin.py class AAdmin(TabularInline): model = A form = Aform class RangeAdmin(ModelAdmin): inlines=(AAdmin) site.register(B,RangeAdmin)