Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django arrayfield saving a array item containing comma
I have a django model that has a postgres array field ArrayField(blank=True, default=list, base_field=CICharField(max_length=200, blank=True)) There is also a corresponding admin page for this model where I can update field this in the regular case, but If for example I want to save the field as ['foo,bar', 'baz'] this is not possible since django seems to be splitting always by comma. I tried saving with "foo,bar",baz thinking csv rules but that didn't work out either. Is there any workaround to achive this in django admin ? -
Django unable to access with JQuery on generated HTML
sorry for the long post. I generated some HTML code with django template tag. Template tag look like this : @register.simple_tag def api_render() : return mark_safe(Loader().render()) The template look like this : <div id='{{ "demo"|api_register:"/api/demo/demo.json" }}'> </div> {% api_render %} <script src="{% static "/jquery/dist/jquery.min.js" %}"></script> <script src="{% static "/api/js/api.js" %}"></script> Final result look like this : <body> <div id="a28207e8cade58babd2bf80d"> </div> <div id="#api"> <div data-dja-id="a28207e8cade58babd2bf80d" data-dja-slug="/api/demo/demo.json" data-dja-event="click" data-dja-suc="demo_click_success" data-dja-err="demo_click_error"></div> </div> <script src="/static/jquery/dist/jquery.min.js"></script> <script src="/static/api/js/api.js"></script> </body> But when I'am trying to access to the div with the id #api I'm not abble to do it: Does someone know how can I solve this? -
Why i am unable to fetch data on the template
What mistake in my code anybody tell me if you can catch my mistake so please inform me i am unable to fetch data on template ............Please tell me pppppppppppppppppppppppppppppppppppp................................................................. views.py def userprofile(request,username): user=User.objects.filter(username=username) if user: user=user[0] profile=Profile.objects.get(user=user) post=getPost(user) bio=profile.bio conn=profile.connection follower=profile.follower following=profile.following user_img=profile.userImage print(user) print(bio) print(conn) print(follower) print(following) print(user_img) print(user) data={ 'user':user, 'bio':bio, 'conn':conn, 'follower':follower, 'following':following, 'userImg':user_img, 'posts':post } print(data) return render(request,'userview/userProfile.html') else: return HttpResponse(" 404 No Such User exist") My data is show on after run server so can you tell me what mistake in my code if you can help me please tell me what mistake in code please tell me why i am not couldn't fetch............................................................................................. profile.html {% extends 'base.html' %} {% block title %}profile{% endblock title %} <style> .pst{ width: 350px; height: 200px; margin-bottom: 30px; } </style> {% block body %} <div class="container my-4"> <div class="media"> <img src="{{userImg.url}}"class="align-self-start mr-3 userImage" alt="......."> <div class="media-body-info"> <h4 class="mt-4" >{{user.get_username}}</h4> <p>Follower : {{follower}} Following : {{followin}} </p> <p><b>{{bio}}</b></p> </div> </div> <hr> <!-- <h3> Username:{{user.get_username}}</h3> <h3> FirstName:{{user.first_name}}</h3> <h3> lastname:{{user.last_name}}</h3> <h3> Email:{{user.email}}</h3> --> <!-- <h3> country:{{user.country}}</h3> sss --> <div class="row"> {% for i in posts %} {% for j in i %} <div class="col-md--4 "> <img src="{{j.image.url}}" alt="" class="pst"> </div> {% … -
Django aggregate Min on filtered reverse foreign field
class Order(models.Model): ... class OrderApplication(models.Model): created_at = models.DateTimeField(auto_now=True) driver = models.ForeignKey(Driver, on_delete=models.CASCADE) suggested_price = models.DecimalField(..., blank=True, null=True) I have the models as described above. All Orders usually have more than 1 OrderApplication (OA). However, there is only 1 OA for each Order which has a non-null suggested_price field. At some moments I have to serialize a list of Orders and send it to the front-end React app. I want my orders to be placed in a very specific Order: For each order I want to get the OA which relates to it and have a non-null suggested_price field Then when I get this OA I want to check its created_at field Basing on this field the earlier the OA was created the closer to the end should the Order be placed. So, the first Order will be the one which has an OA with specified suggested_price and created as recently as possible What I have already tried is ordering the Orders by the first created OA related to it: .annotate(suggestion_created=Min('orderapplication__created_at')).order_by("-suggestion_created") Here inside Min aggregator I use a reversed foreign relation of the Order which is can be accessed as orderapplication and get the first date of the objects which are … -
Upload image using django-restframework
Pardon if this question has been answered already. I can't find a solution that works - please point me in the right direction if you can. I need to upload an image using django-restframework but my code is not working. I get the following error: Got a `TypeError` when calling `Product.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `Product.objects.create()`. You may need to make the field read-only, or override the ProductSerializer.create() method to handle this correctly. My models.py: class Product(models.Model): store = models.ForeignKey(Store, to_field='store_name', on_delete=models.SET_NULL, null=True) product_name = models.CharField(max_length=71) price = models.PositiveIntegerField(null=True, default=0) total_stock = models.PositiveIntegerField(default=0) image = models.ImageField(upload_to='images', blank=True) created = models.DateTimeField('date added', auto_now_add=True) modified = models.DateTimeField('date modified', auto_now_add=True) My serializers.py: from rest_framework import serializers from inventory.models import Product class ProductSerializer(serializers.ModelSerializer): store = serializers.ReadOnlyField(source='store.store_name') slug = serializers.ReadOnlyField(source='store.slug') store_logo = serializers.ImageField(source='store.logo', read_only = True) class Meta: model = Product exclude = ('created', 'modified',) My views.py from rest_framework.parsers import FileUploadParser from rest_framework import generics from rest_framework.response import Response from rest_framework import status class ProductCreate(generics.CreateAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer parser_class = (FileUploadParser,) def create(self, request, *args, **kwargs): serializer = ProductSerializer(data=request.data) print(serializer) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) … -
Super in Python
I have been working in django CBV but i am stuck and cannot reslove it i also googled that thing but nothing much i get it sometimes in classes we use super class ArticleCounterRedirectView(RedirectView): permanent = False query_string = True pattern_name = 'article-detail' def get_redirect_url(self, *args, **kwargs): article = get_object_or_404(Article, pk=kwargs['pk']) article.update_counter() return super().get_redirect_url(*args, **kwargs) class ArticleCounterRedirectView(RedirectView): permanent = False query_string = True pattern_name = 'article-detail' def get_redirect_url(self, *args, **kwargs): article = get_object_or_404(Article, pk=kwargs['pk']) article.update_counter() return super(ArticleCounterRedirectView,self).get_redirect_url(*args, **kwargs) we use super to to call the parent class then in one example we give no arguments and in another we give it two arguements please can someone help me out in this -
Def - time conversion
Folks, It could help me build Def, via SHELL i was able to extract exactly what i need, which is to calculate the duration of hours, in my example it is related to a maintenance window but i'm not sure how to assemble at DEF. Doubt - The manipulation DEF can be represented in the "duration" object that I created? >>> import datetime >>> time1 = datetime.strptime("03-06-2020 23:00",'%d-%m-%Y %H:%M') >>> time2 = datetime.strptime("04-06-2020 04:00",'%d-%m-%Y %H:%M') >>> difference = time2 - time1 >>> difference datetime.timedelta(seconds=18000) >>> difference.seconds 18000 >>> datetime.timedelta(0, 18000) datetime.timedelta(seconds=18000) >>> >>> format(datetime.timedelta(seconds=difference.seconds)) '5:00:00' class Sishora(models.Model): description = models.CharField(max_length=100) OCUPACTION_CHOICES = ( ( 'AlocTOC','Alocacao_TOC'), ('AloENG','Alocacao_apoio_ENG'), ('ImpJan','Implementacao_Janela') ) ocupaction = models.CharField(max_length=50, choices=OCUPACTION_CHOICES) PROJECT_CHOICES = ( ( 'BR1','BR19062'), ('BR2','BR20009'), ('BR3','BR20009.2') ) project = models.CharField(max_length=50, choices=PROJECT_CHOICES) date_ord_1 = models.DateField(null=True, blank=True, default=None) date_ord_2 = models.DateField(null=True, blank=True, default=None) date_ord_2 = models.DateField(null=True, blank=True, default=None) date_ord_3 = models.DateField(null=True, blank=True, default=None) date_ord_5 = models.DateField(null=True, blank=True, default=None) TIME_ORD_1_CHOICES = [(None, '------')] + [(dt.time(hour=x), '{:02d}:00'.format(x)) for x in range(0, 24)] time_ord_1 = models.TimeField(null=True, blank=True, default=None, choices=TIME_ORD_1_CHOICES) date_exth_start = models.DateField(null=True, blank=True, default=None) date_exth_end = models.DateField(null=True, blank=True, default=None) timehe1start = models.DateTimeField(null=True, blank=True, default=None, auto_now_add=False) timehe1end= models.DateTimeField(null=True, blank=True, default=None, auto_now_add=False) duracao = models.DurationField(null=True, blank=True) #user = models.ForeignKey(User, on_delete=models.CASCADE) active = models.BooleanField(default=True) @property … -
Django session is not being persisted and cookie is not being set when using Django Channels
Django 3.6, Channels 2 I am writing a chat application in which I assign a random username to non-authenticated users. I save this username to self.scope['session'] within the consumer. For authenticated users, the csrftoken cookie and the sessionid cookie are being set correctly in the browser. However, even though I both set and save the scope['session'] variable for non-authenticated users in the consumer's connect method, the session is not being saved in the django_session table and the user_name cookie is therefore not being set in the browser. I am using an async consumer, and I am using the correct database_sync_to_async to save the session as shown at the bottom of the first example code shown here. Relevant code sections: consumers.py: from channels.generic.websocket import AsyncJsonWebsocketConsumer from channels.db import database_sync_to_async from chat.models import * class ChatConsumer(AsyncJsonWebsocketConsumer): DIGITS = string.digits ANON_NUMBER_LENGTH = 7 async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = f'chat_{self.room_name}' if not self.scope["user"].is_authenticated: if 'user_name' not in self.scope['session']: # Create user name session for anonymous user random_number = ''.join(random.choice(ChatConsumer.DIGITS) for i in range(ChatConsumer.ANON_NUMBER_LENGTH)) self.scope['session']['user_name'] = f'Guest_{random_number}' await database_sync_to_async(self.scope["session"].save)() elif 'user_name' in self.scope['session']: # Remove user_name from session if present self.scope['session'].pop('user_name') await database_sync_to_async(self.scope["session"].save)() routing.py: from channels.auth import AuthMiddlewareStack application = ProtocolTypeRouter({ # … -
django all-auth can you switch mid-project
I have implemented my own custom accounts app that require email and password for authentication. Recently, I've heard a lot about all-auth and am considering if I should switch to all-auth. Given that custom authentication should be done right when you start a new project, is it advisable to switch to all-auth when you have an existing authentication? If this is possible, what are the additional steps after going through the normal installation of all-auth? -
When should I create methods in model
I have model Post and i'm making querysets like this in view user = CustomUser.objects.get(username=user) blocked_users = user.blocked.all() posts_except_blocked = Post.objects.exclude(author__in=blocked_users).order_by('-pub_date') and a few similar. But i recognized that I can put this into model class as @staticmethod and now it's looking @staticmethod def get_posts_except_blocked(user): user = CustomUser.objects.get(username=user) blocked_users = user.blocked.all() return Post.objects.exclude(author__in=blocked_users).order_by('-pub_date') Should I put every queries like this to model? I have there in views method def create_notifications(post): for word in post.content_post.split(): if '@' in word: user_to_notificate = CustomUser.objects.get(username=word[1:]) TalkAbout(where=post, _from=post.author, to=user_to_notificate).save() I'm calling it after save post form to create notifications. Can this be in views or maybe I need to put it in Post class too? Is it possible to call this function automaticly after creating post? -
Django - authenticate method error. The view home.views.loginAdmin didn't return an HttpResponse object. It returned None instead
I'm newbie to Django. I'm stuck at one thing that, my login authenticate method return None. I've tried my best to search and try to solve this but i didn't find my problem solution. In first screen shot, I'm getting value of form and using variable in authenticate method but its giving me that error. But in second screen shot if, I used hard coded value in authenticate method that i know saved in database username and password, then it will execute successful. I've debug form username and password They are coming. I tried to elaborate my problem. Please guide me how to solve this. Thank You. Screen Shot 1 Link: Having error in This Screen Shot 2 Link: But No error if Hard Coded Value -
Django generates wrong hostname in links (paginating and HyperlinkedModelSerializer)
My question is: everywhere in the project incorrect links are generated, on pages with pagination and when using HyperlinkedModelSerializer. For example: the link should be: http://1.g.cluster:8001/api/v1/admin/sys_logs/?limit=100&offset=100 And this one is generated: http://web/api/v1/admin/sys_logs/?limit=100&offset=100, where the web is the service name from the docker-compose.yml file, it is also in the settings in the settings.py file: ALLOWED_HOSTS = ['web', 'localhost', '192.168.36.85', '192.168.36.47', '0.0.0.0', '127.0.0.1'] Project with Django (1.11.22) and Django Rest Framework (3.10.2) nginx and docker. I don’t know how to configure the correct links, please help -
View didn't return an HttpResponse object. It returned None instead., when used normal form with FormView , django
urls.py path('shift/<int:pk>/assign/', employee_views.ShiftAssignView.as_view(), name="shift_assign"), models.py class Employee(models.Model): name = models.CharField(max_length=120) phone = models.CharField(null=True, blank=True, max_length=20) salary = models.IntegerField(default=0) shift = models.OneToOneField(Shift, on_delete=SET_NULL, null=True, blank=True, related_name='employee') def __str__(self): return self.name def get_absolute_url(self): return reverse('employee_details', args=[str(self.id)]) class Shift(models.Model): branch = models.ForeignKey(Branch, on_delete=CASCADE) start_time = models.TimeField() end_time = models.TimeField() def __str__(self): return str(self.branch) + ' ( ' + str(self.start_time) + ' / ' + str(self.end_time) + ' )' def get_absolute_url(self): return reverse('branch_details', args=[str(self.branch.id)]) forms.py class AssignEmployeeForm(forms.Form): employee = forms.ModelChoiceField(queryset=Employee.objects.filter(shift__isnull=True), widget=forms.Select()) views.py class ShiftAssignView(SuccessMessageMixin, FormView): form_class = AssignEmployeeForm template_name = 'back_office/assign_employee.html' def get_context_data(self, **kwargs): context = super(ShiftAssignView, self).get_context_data(**kwargs) context['current_shift'] = Shift.objects.get(id=self.kwargs['pk']) return context def get_success_url(self): obj = Shift.objects.get(id=self.kwargs['pk']) return reverse_lazy('branch_details', args=[str(obj.branch_id)]) def form_valid(self, form): employee_instance = form.cleaned_data['employee'] shift_object = Shift.objects.get(id=self.kwargs['pk']) employee_instance.shift = shift_object employee_instance.save() super(ShiftAssignView, self).form_valid(form) NOTE The object is already being saved , but it shows this http error ! -
How to read django variable radio button name in jQuery?
TOP PS:To summarize my problem I don't put every thing here. This question is about making a quiz page in django where user answers the questions and get the result. Okay so I have a dictionary in django views which is soru_cevaplar that includes soru(question) and cevap(answers). Also cevap includes answers for their (Foreign key) question. I have read many questions like this but couldn't get it. So in my template I have this: {%for soru, cevap in soru_cevaplar.items%} <p>{{soru.soru_soru|safe}}</p> {% for c in cevap%} <label> <input name="{{c.cevap_soru}}" type="radio" value="{{c.cevap_content}}"/><span>{{c.cevap_content|safe}}</span> </label> {% endfor %} {% endfor %} <input id="test" class="btn btn-outline-info" type="submit" value="End Test"></input> <script type="text/javascript"> var cevap = "{{soru_cevaplar}}"; </script> Cevap is string in JS so can't use it like in python dictionary. My answers are radio buttons and in my jQuery I know I need to do something like this: $("#test").on("click", function(){ var radioValue = $("input[name='{{c.cevap_soru}}']:checked").val(); console.log(radioValue); }); which returns nothing because input name isn't right. So what I want to do get the all answer values for each question control them in JS file and after user submit the button tell them the results. And the problem is like to pass cevap or sorular_cevap to the JS … -
Django ORM Query to find all records with second largest value of age | Django Interview Question
I was recently asked the below question in a Django interview. I want to know how I could improve this query. Question:- Given an Employee table, with fields name, age. Find all the rows with the second maximum age. Consider the below table id name age 1 a 10 2 b 11 3 c 12 4 d 10 5 e 11 In this case query should return all records with age 11 My Solution :- First I will order all age values in Descending order with out repeating them. Employee.objects.order_by().values('age').distinct().order_by('-age') Then since we want the second largest value it will be at 1 index, if you want second then use 2 and so on... Employee.objects.filter(age=Employee.objects.order_by().values('age').distinct().order_by('-age')[1] This will give us a dictionary with the key as age, {'age': 13} TO access the age, we will use Employee.objects.order_by().values('age').distinct().order_by('-age')[1]['age'] Then to Get all the records with the age, I used filter, below is the final query Employee.objects.filter(age=Employee.objects.order_by().values('age').distinct().order_by('-age')[1]['age']) How can I do it with fewer hits to the database? -
Django unique constraint not working properly
I have a model with a custom _id that has to be unique, and soft delete, deleted objects don't have to have a unique _id, so I did it as follows: class MyModel(models.Model): _id = models.CharField(max_length=255, db_index=True) event_code = models.CharField(max_length=1, blank=True, default='I') deleted = models.BooleanField(default=False) deleted_id = models.IntegerField(blank=True, null=True) objects = MyModelManager() # manager that filters out deleted objects all_objects = MyModelBaseManager() # manager that returns every object, including deleted ones class Meta: constraints = [ UniqueConstraint(fields=['_id', 'event_code', 'deleted', 'deleted_id'], name='unique_id') ] def delete(self, *args, **kwargs): self.deleted = True self.deleted_id = self.max_related_deleted_id() + 1 self.save() def undelete(self, *args, **kwargs): self.deleted = False self.deleted_id = None self.save() def max_related_deleted_id(self): # Get max deleted_id of deleted objects with the same _id max_deleted_id = MyModel.all_objects.filter(Q(_id=self._id) & ~Q(pk=self.pk) & Q(deleted=True)).aggregate(Max('deleted_id'))['deleted_id__max'] return max_deleted_id if max_deleted_id is not None else 0 The whole logic of the deleted_id is working, I tested it out, the problem is, the UniqueConstraint is not working, for example: $ MyModel.objects.create(_id='A', event_code='A') $ MyModel.objects.create(_id='A', event_code='A') $ MyModel.objects.create(_id='A', event_code='A') $ MyModel.objects.filter(_id='A').values('pk', '_id', 'event_code', 'deleted', 'deleted_id') [{'_id': 'A', 'deleted': False, 'deleted_id': None, 'event_code': 'A', 'pk': 1}, {'_id': 'A', 'deleted': False, 'deleted_id': None, 'event_code': 'A', 'pk': 2}, {'_id': 'A', 'deleted': False, 'deleted_id': None, 'event_code': 'A', … -
How to use CSRF security for a backend django?
I'm developing a backend for a mobile app with Django where for user registration the user data are sent with the POST method. Since Django provide CSRF security as a middleware. Here my problem is if I have a front end I can enable CSRF token by jinja code as {% csrf_token %} but since it's a backend and how to resolve this problem -
BeautifulSoup - find img with different extensions
I'm working on a project in django and I have to find photos in the provided .csv file in Text column. The problem is that at this point I'm downloading only those with the .jpg extension. How to download e.g. those with the extension .png in one line, as follows: I am using to this task BeautifulSoup. soup = BeautifulSoup(row['Text'], features="html5lib") images = soup.findAll('img', src=re.compile('.jpg')) -
Django Queryset: join two querysets with one as a list or set
I have two separate querysets (A and B), with one having a foreign key relationship to the other (1 to many, where B is many). Is it possible to join the two querysets somehow, creating an object which looks something like this: A: { some_field: ..., list_of_B: [...], } I have already found a relatively slow solution by just iterating over A's values and adding the field: for i in range(len(A.values())): result[i] = A[i] result[i]['list_of_B'] = list(images.filter(fk_in_B=A[i]['id'])) For performance reasons I would like to do this within the querysets if possible. Is it even possible to have lists/sets in fields/columns of a queryset? If so, what would be a possible approach? -
I am getting AttributeError: module 'app' has no attribute 'helpers' when running Djanog runserver on Linux VM
I am getting AttributeError: module "app" has no attributes 'helpers' when I am trying to import as follow in HlperConnector.py: import app.Helpers.SubHelper as shelpr Same setup works perfectly on my VSCode but when deploying on Digital Ocen Linux VM (Ubantu 18.04.3 version). Here is my directory structure: ├───app │ │ admin.py │ │ apps.py │ │ forms.py │ │ tests.py │ │ urls.py │ │ __init__.py │ │ │ ├───Helpers │ │ │ helper1.py │ │ │ HelperConnector.py │ │ │ helper2.py │ │ │ __init__.py │ │ ├───SubHelper │ │ │ │ subhelpers1.py │ │ │ │ subhelpers2.py │ │ │ │ __init__.py └───Project │ asgi.py │ dosettings.py │ settings.py │ urls.py │ wsgi.py │ __init__.py │ Can someone please help me to resolve the above issue? I check the Django version which i use for my development (windows PC) is 3.0.6 and Production environment (Ubantu 18.04) is 3.0.7. But my guess is that this should not be an issue. Thank You. -
Long-term and Versatile Saved Searches?
I have an articles table that might change in the future built into a Django web app. That's to say, a row name might change, a row might get added or deleted, etc... I have to develop a data model for saving advanced searches made on this table that is as future-proof as possible and I'd like you opinions on the solution I came up with. For some background on how searches are made, a user fills out a standard advanced search form (keywords, date ranges, checkboxes...) and the form data is turned into a query string in the form .../?field_1=arg_1&...&field_n=arg_n and sent to the API. Currently searches are saved by simply saving the query string. However, if the article field name changes or gets removed, that user's saved search breaks. This is my proposed saved search model (I made a typo in that the operations field in the Saved Search table is meant to be a many-to-many relationship to the Saved Search Operations table): Essentially, when a user clicks a "Save Search" button, it will create the necessary rows and when it comes time to reactivate that search, it will join the necessary tables and create a valid query … -
sms sent but not received - Twilio
I am developing a Django application where I am using the Twilio free trial account. I have $11 as a trial balance in Twilio. But the fact is, SMS sent from Twilio but it does not reach my phone. Can anyone help me out plz? -
pytz AmbiguousTimeError related to a specific datetime
This is coming up in the context of a django project. All datetime objects are tz aware. One day the production server crashed with the follow error: pytz.exceptions.AmbiguousTimeError: 2020-11-01 01:00:00 The strange thing is that if I change this date manually in the database to almost anything else, the error goes away. Also, if I copy the problematic date into any other datetime field in the database, the same exception is thrown. I have also tried to add this datetime to other records, and the same problem occurs with those records. Same applied to test and dev databases. Any ideas? I am using a mysql database. -
Celery - Chaining groups of tasks
Im having trouble creating a chain of tasks in a group. I'll show a snippet of what I have tasks.py @shared_task def fast_task_1(arg1, arg2): return @shared_task def fast_task_2(arg1,arg2): return @shared_task def slow_task_1(arg1, arg2): return @shared_task def finished_both(): # Do something return And the following groups fast_job = group([fast_task_1.s(arg1, arg2), fast_task_2(arg1,arg2)]) fast_result = fast_job.apply_async(queue='fast_queue') slow_job = group([slow_task_1.s(arg1, arg2)]) slow_result= fast_job.apply_async(queue='slow_task') Is it there a way to make a group in which all the fast and slow tasks are ran in their respective queues and, when both of them finish, call the finished_both task? Another option I thought was to send the result of each group to finished_both and check there if each group had finished, but I still cant figure out how to create chain of tasks after reading the docs. -
How to render a ManyToMany Extra Field in my form? (E.g. quantity of each topping on my pizza)
I wish to build an offer generator for my colleagues and I am a bit stuck. In an offer, we have 1 main product that can have many different accessories in different quantities. E.g. a Pizza with several toppings where you may have 1 x cheese, 2 x pepperoni, etc. #models.py class Accessory(models.Model): name = models.CharField(max_length=200, null=True, blank=True) price = models.PositiveIntegerField(null=True, blank=True) class Offer(models.Model): customer = models.CharField(max_length=200) product = models.ForeignKey(Product, null=True) accessories = models.ManyToManyField(Accessory, through='Addons') class Addons(models.Model): offer = models.ForeignKey(Offer, on_delete=models.CASCADE) accessory = models.ForeignKey(Accessory, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) #forms.py class Offerform(ModelForm): accessories = forms.ModelMultipleChoiceField( widget=forms.CheckboxSelectMultiple(), queryset=Accessory.objects.all()) class Meta: model = Offer fields = '__all__' I have linked my offer accessories through a custom table (Addons) where I have specified the quantity. Nonetheless, how do I manage to get "quantity" as a field in my form so that I can select an accessory and specify the quantity?