Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to initialize Neo4j driver on Django
I use Neo4j as an external database for additional requests in my Django project. There is an issue that I got stuck on, where should I initialize the Neo4j driver in my Django project? I do not want to recreate and close neo4j driver every time that requests came. So currently, I edited my settings.py file, I imported neo4j GraphDatabase and I initialized Neo4j driver as I mentioned below. ..settings.py from neo4j import GraphDatabase driver = GraphDatabase.driver("neo4j://localhost:7687", auth=("test", "test")) But the problem is that I don't know if settings.py file the proper place to initialize Neo4j driver. Where should I initialize global variables in my Django project? Can you help me about this, please? Thanks. -
Calling function form another function to make code more DRY in Django
I'm not using DRF (yet) so I need to copy my code from view to view if i wanna have same functionality like seeing current items in my cart. I don't like that How can i call funcA that returns 2 variables in funcB, get them into context of funcB and render html with that data. def funcA(request): if request.user.is_authenticated: customer = request.user.customer else: customer = "abcd" customerTotal = 1234 context = { "customerTotal":customerTotal, "customer":customer, } def funcB(request,pk): funcA(request) product = Products.object.get(id=pk) context = { "customerTotal":customerTotal, "customer":customer, "product":product, } return render(request,'cart.html',context) -
Nested mutation Django + GraphQL
I am new to Django/Graphql/Graphene and struggling to write a nested mutation with several foreign keys and a many-to-many relation. I have read several posts on this topic but still struggling. I have highlighted several questions within the below code. It would be great to help me both on the foreign keys (Fare, Year) and on the Many-to-Many field (Parent), which I have not even included yet in the graphical request. It would be good to have help both on how to write the Python graphene code and then the Graphiql request. Many thanks to all Here is the code: Model (extract): class Student(models.Model): first = models.CharField(max_length=64) last = models.CharField(max_length=64) email = models.EmailField() phone = models.CharField(max_length=64) year = models.ForeignKey(Year, on_delete=models.CASCADE, related_name="students", blank=True) fare = models.ForeignKey(Fare, on_delete=models.CASCADE, related_name="at_fare", blank=True) parents = models.ManyToManyField(Parent, related_name="children", blank=True) Schema.py: class StudentType(DjangoObjectType): class Meta: model = Student // is the Student Type necessary???? class FareType(DjangoObjectType): class Meta: model = Fare class YearType(DjangoObjectType): class Meta: model = Year class ParentType(DjangoObjectType): class Meta: model = Parent Input object types: class StudentInput(graphene.InputObjectType): #id = graphene.ID() // is this field necessary?? first = graphene.String() last = graphene.String() email = graphene.String() phone = graphene.String() year = graphene.Field(YearInput) fare = graphene.Field(FareInput) parents … -
Django Forms and bootstrap - adding widgets works but not fully
I have problem with bootstrap in my django forms. In forms I have this code: make = forms.ChoiceField(choices=make_choices) make.widget.attrs.update({'class': 'form-control'}) And in tutorials I saw that it should be enough to render proper bootstrap choice field. But in my case it looks like this: Please notice: missing arrow indicating actual dropdown on the right grey select box is not wide enough, or rather box above is too wide? label "Make:" also doesn't look like proper bootstrap label. I checkout out several tutorials but in all of them adding this "{'class': 'form-control'}" in attrs was enough. I was also experimenting with django crispy forms but they were also not fully correct. What am I missing? What I did wrong? -
How to setup up new field in Django Model Serializer?
I have created a different model serilizers like LocationDetailSerializer, ListingDetialSerializer, ..so on. Each of their models share a OneToOne Relationship with a PropertySerializer's Model. class PropertySerializer(serializers.ModelSerializer): # location_detail = LocationDetailSerializer() # listing_detial = ListingDetialSerializer() . . . . . class Meta: model = Property fields = "__all__" While creating a PropertySerializer I also want fields like : location_detail, listing_details..passed with it. How to achieve that? -
How to set the FK automatically for Model in OneToOneRaltionship in Django?
Start of Property Model class Property(models.Model): # ? Relationships user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) # ? Fields property_unique_hash_id = models.UUIDField( default=uuid.uuid4, editable=False ) . . . . created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) def __str__(self): return "Property " + str(self.pk) Now I have divided subsections of Property Model in different models like: `LocationDetail`, `ListingDetail`... With them Property Model Shares a OneToOne Relationship. Example: ```python class ListingDetial(models.Model): # Relationships property = models.OneToOneField("properties.Property", on_delete=models.CASCADE) # ? Fields listing_property_type = models.PositiveSmallIntegerField( choices=choices.LISTING_PROPERTY_TYPE, default=choices.LISTING_PROPERTY_TYPE.single_family_detached, ) . . . . . def __str__(self): return "Listing Detail" + str(self.pk) # ***************************END*************************** Now I want to set the property id of ListingDetial Model automatically. How to do that? -
I need a couple development advices
First of all sorry for my English, I'm electronics eng. student and also working for a tech company for web development. The manager asks me today hey buddy we need a website and mobile app for tracking our inventory. I developed a couple of sites for the company with JavaScript and PHP. But I want to learn new things like react and Django. If I develop a website with react and Django, can I use their source code for a mobile app? -
Django Two Factor Authentication not working
I am trying to do the two-factor authentication set up for my Django project. Below is the configuration details settings.py 'django_otp', 'django_otp.plugins.otp_static', 'django_otp.plugins.otp_totp', 'two_factor', ... ] MIDDLEWARE = [ 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django_otp.middleware.OTPMiddleware', ... ] LOGIN_URL = 'two_factor:login' LOGIN_REDIRECT_URL = 'two_factor:profile' TWO_FACTOR_PATCH_ADMIN = True TWO_FACTOR_CALL_GATEWAY = 'two_factor.gateways.fake.fake' TWO_FACTOR_SMS_GATEWAY = 'two_factor.gateways.fake.Fake' AUTH_USER_MODEL ='Products.CustomUser' AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', }, }, 'loggers': { 'two_factor': { 'handlers': ['console'], 'level': 'INFO', } } } urls.py urlpatterns = [ path('', include(tf_urls)), # path('admin/', admin.site.urls), ] when I access the url http://127.0.0.1:8001/account/login/ it navigates to the token generation page. when I scan the QR code with google authenticator and then when I enter the token system throws the error **not a valid token **. The application is already running with django default authentication using the custom user model. Now I am trying to incorporate the two factor authentication. Can someone guide me on what is missing in the above configuration?. -
Django Rest Framework Serializer Relations: How to get list of all child-child objects in parent's serializer?
I'm new to DRF and have just started building an API. I have three models, a child model connected to a parent model with a foreign key. Here is the simplified version of the model I have: union models: class Union(core_models.TimeStampedModel): # 공통 name = models.CharField(max_length=50) # 조합명 owner = models.ForeignKey( user_models.User, on_delete=models.CASCADE, related_name="owner" ) # 조합을 만든 계정 user models: class User(AbstractUser): nickname = models.CharField(max_length=20, blank=False) # 닉네임 password = models.CharField(max_length=100, blank=False) # 비밀번호 # 학력사항 education = models.ManyToManyField( education_models.Education, related_name="education", blank=True ) # 경력사항 career = models.ManyToManyField( career_models.Career, related_name="career", blank=True ) career models: class Career(core_models.TimeStampedModel): company = models.CharField(max_length=50) # 회사명 job = models.CharField(choices=JOB_CHOICES, max_length=50) # 직무 status = models.BooleanField() # 재직_상태 (재직상태면 True, 아니면 False) in documentation (https://www.django-rest-framework.org/api-guide/serializers/#writable-nested-representations), there is only parent-child case, but I create/update the career models in union serealizer. I think it's perfectly reasonable, but I couldn't understand what I'm missing here. How can I create/upate children-children in parent's serializer? -
My view doesn't save the instance from Form in Djagno
I'm trying make a comment section for my Q&A project.I made the model for comment , the form part in question_detail.html an , also the QuestionCommentForm() in form.py . model.py class QuestionComment(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) question = models.ForeignKey(Question,on_delete=models.CASCADE) created_date = models.DateTimeField(auto_now_add= True) body = models.CharField(max_length=200, null= True , blank = True, default ='') def __str__(self): return str(self.body) forms.py {%if c_form%} <form method="POST" action = action = "{% url 'blog:question-comment' question.pk %}">{% csrf_token %} {{c_form.media}} {{ c_form.as_p}} <button type = "submit" , name = "question_id", value = "{{question.pk}}", class ="btn btn-secondary btn-sm">submit comment</button> views.py @api_view(['POST','GET']) def question_comment(request, *args, **kwargs): form = QuestionCommentForm() print('finction comment started'*20) if request.method == 'Post': c_form = QuestionCommentForm(request.Post) if c_form.is_valid(): new_comment = c_form.save(commit=False) new_comment.refresh_from_db() new_comment.user = request.user new_comment.question = c_form.cleaned_data.get('question_id') new_comment.bldy =c_form.cleaned_data.get('body') context['c_form'] = c_form return render(request, 'blog/question_detail.html',context) class QuestionDetail(DetailView): template_name = 'blog/question_detail.html' model = Question context_object_name = 'question' count_hit = True def get_queryset(self): return Question.objects.filter(id = self.kwargs['pk']) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) c_form = QuestionCommentForm() context = super(QuestionDetail,self).get_context_data(**kwargs) self.obj= get_object_or_404(Question, id = self.kwargs['pk']) self.object.save() self.object.refresh_from_db() answers = Answer.objects.filter (question_id = self.obj.id).order_by('-created_date') liked =self.obj.like.filter(id =self.request.user.id).exists() print('liked in class question not checked still' *10) comments= QuestionComment.objects.filter(question = self.kwargs['pk']) context['comments']= comments context["answers"]=answers context["liked "] = liked context['c_form'] = … -
Hello All, I'm trying to call the webpage but getting error while calling it. I'm new at learning Django so please suggest
THis is the views.py and getting error when I try to call the sports named function def index(request): ob=Com1.objects.all() return render(request,'index.html',{'ob':ob}) def sports(request,name): cat=Categ.objects.filter(name=name) com=Com1.objects.filter(categ_id=cat[0].id) return render(request,'sports.html',{'com':com}) This is the main URLs.. urlpatterns = [ path('admin/', admin.site.urls), path('index/',views.index,name='index'), path('sports/<str:name>',views.sports,name='sports'), AM I missing something to place or declare in Sports.html <li><a href="{%url 'sports'%}">Sports</a></li> -
Django claiming inconsistent migration history on first migration
I have been working on a project for a while, and I have been having no trouble with migrations. I decided reset the database and migrations, which I do from time to time. I went to delete all migrations, make them again, and after recreating the database, apply the migrations, at which point, I get the error "Migration users.0001_initial is applied before its dependency auth.0012_alter_user_first_name_max_length on database 'default'." Now, auth.0012_alter_user_first_name_max_length is apparently coming from django.contrib.auth, which is part of core django, so I don't see why I need any dependency on its migrations for a new project, yet whenever I make migrations on this project from the beginning, it adds a dependency to my user model of auth.0012_alter_user_first_name_max_length. I don't know why it does that, when it apparently wasn't doing that yesterday, but I am now having to remove that dependency from the user migration manually before it will migrate. What might cause this. Here is my users.models.py file. Maybe someone can figure out what would be so odd about it that it would do this. from django.contrib.auth.models import AbstractUser from django.db.models import CharField, EmailField from django.urls import reverse from django.utils.translation import gettext_lazy as _ from phonenumber_field.modelfields import PhoneNumberField from … -
How to set cookie before setting context?
In Django to set cookies first I need to set render function. But i want to pass data from cookies to my template. How can i set cookies before setting context? Current code: def mainPage(httpRequest): # Set Render renderResponse = render(httpRequest, 'AppMain/index.html') # Get Cookies httpCookies = httpRequest.COOKIES # Get Empty Status isCookiesEmpty = True if len(httpCookies) == 0 else False # Empty State if isCookiesEmpty: # Set Cookies renderResponse.set_cookie('likedData', []) renderResponse.set_cookie('dislikedData', []) renderResponse.set_cookie('lovedData', []) # Return Page return renderResponse -
Creating a nested JSON from a value in Django Rest Framework
I'm very new to Django and the DjangoRest Framework and this is my first question on Stack overflow, please bear with me. I am trying to create a Django Rest API that can that to handle entries for an online raffle. So each entry would have details like name, email, and a string that represents the raffle entry in the form of numbers separated by spaces(Eg: "12,23,34,45,56,67"). So far, I've been able to do the basics and create a simple model, serializer, and views. What I need is to create a JSON similar to { "entry" : "12,23,34,45,56,67", "name" : "SampleName", "email" : "sample@sample.com", "values" : [ "one" : 12, "two" : 23, "three" : 34, "four" : 45, "five" : 56, "six" : 67 ] } models.py class EntryModel(models.Model): entry = models.CharField(null=False, max_length=17) name = models.CharField(null=False, max_length=100) email = models.EmailField(null=False) serializers.py class EntrySerializer(serializers.ModelSerializer): class Meta: model = EntryModel fields = ['entry', 'name', 'email'] views.py class EntryViews(viewsets.ModelViewSet): queryset = EntryModel.objects.all() serializer_class = EntrySerializer -
Using variables in Django template Loop/If Statement
Incoming noob Django question I have a Django template that receives two variables from a view: list_of_strings = ['non_target','target','non_target'] target_string = 'target' I want to make a dropdown menu of list_of_strings, & have the default value be target_string: <select name="list_of_strings" id = "list_of_strings"> {% for string in list_of_strings %} <option {% if string == target_string %} selected {% endif %} value="{{string}}">{{string}}</option> {% endfor %} </select> The above produces a dropdown menu with the first value in list_of_strings selected, i.e. 'non_target', so the if statement to select target_string doesn't appear to have worked. Hardcoding 'target' into the statement as per the below works: {% if string == 'target' %} selected {% endif %} My guess is target_string doesn't refer to the string variable. It works fine elsewhere, e.g. referring to it in an H1 element shows 'target': <h1>{{target_string}}</h1> Am I referencing target_string wrongly in the if statement? I've tried target_string, {target_string}, {{target_string}}, "{{target_string}}", "{target_string}", "target_string" as any good personwhohasnoideawhattheyredoing would do, to no avail. -
Django Error in Command Console AttributeError Models
I am getting the following error when I try and display my fields within the command prompt. Any idea what would be causing this? I've tried to adjust "return self.stakeholder" to a field listed above (e.g. return self.employee) but it presents the same error (still referencing 'stakeholder') models class Stakeholder(models.Model): employee = models.CharField(max_length=200) stakeholder_group = models.CharField(max_length=200) description = models.CharField(max_length=200) stakeholder_quadrant = models.CharField(max_length=200) def __str__(self): return self.stakeholder error Traceback (most recent call last): File "C:\Python38\lib\site-packages\werkzeug\local.py", line 72, in __getattr__ return self.__storage__[self.__ident_func__()][name] KeyError: 27232 During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Python38\lib\site-packages\werkzeug\debug\console.py", line 87, in displayhook stream = _local.stream File "C:\Python38\lib\site-packages\werkzeug\local.py", line 74, in __getattr__ raise AttributeError(name) AttributeError: stream During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Python38\lib\site-packages\werkzeug\debug\console.py", line 89, in displayhook return _displayhook(obj) File "C:\Python38\lib\site-packages\django\db\models\query.py", line 255, in __repr__ return '<%s %r>' % (self.__class__.__name__, data) File "C:\Python38\lib\site-packages\django\db\models\base.py", line 518, in __repr__ return '<%s: %s>' % (self.__class__.__name__, self) File "C:\Users\zzzz\Python\Price Tracking\Django\mysite\polls\models.py", line 38, in __str__ AttributeError: 'Stakeholder' object has no attribute 'stakeholder' -
Django Signals.py
I was wondering if it is possible to code a program such that when a blog post is made, a chatroom is created automatically and the blogpost maker is made admin of the chatroom. then everyone can talk about the blog post. I have studied django channels and django separately so I'm unsure how I can link those 2 together. Is it signals.py, and by any chance does anyone have sample code to show how it can be done? Thank you! -
How can I display data of a table based on common attribute value between two tables?
I am trying to display all data from table 'Class' based on common attribute value with table 'Student_class', where (Student_class.course_id==Class.id).There is an erron.How can I solve this? models.py class Class(models.Model): course_code = models.CharField(max_length=111, default="") course_title = models.CharField(max_length=111, default="") course_credit = models.FloatField(default=0.0) section = models.CharField(max_length=111, default="") teacher = models.ForeignKey(User, on_delete=models.CASCADE) code = models.CharField(max_length=10, default="", unique=True) def __str__(self): return self.course_title class Student_class(models.Model): student = models.ForeignKey(User, on_delete=models.CASCADE) marks = models.FloatField(default=0.0) answered_ques = models.IntegerField(default=0) join_date = models.DateTimeField(default=datetime.now, blank=True) course_id = models.ForeignKey(Class, on_delete=models.CASCADE) views.py @login_required def my_class(request): current_user = request.user joined_class = Student_class.objects.filter(student=current_user).order_by('-id') all_class = Class.objects.filter() created_class = Class.objects.filter(teacher=current_user).order_by('-id') image = Profile.objects.get(user_id = current_user) params = {'created_class': created_class, 'teacher_name': current_user, 'image': image, 'all_class': all_class, 'joined_class': joined_class } return render(request, 'course/my_class.html', params) my_class.html {% for j in created_class%} {% for i in all_class%} {% if j.course_id==i.id %} <div class="service text-center"> <a href="#"><img src='{{image.profile_image}}' alt="Image" onerror="this.src='../../static/course/images/default-avatar.jpg'" style="border-radius: 50%;width: 80px;height: 80px; margin-left: 130px;"class="img-fluid"></a> <div class="px-md-3"> <h3><a href="#">{{i.course_code }} {{i.course_title }}</a></h3> <p>Course credit: {{i.course_credit}}<br> {{i.section}}</p> </div> </div> {% endif %} {% endfor %} {% endfor %} -
Serializing/deserializing a foreign key in django rest framework
I'm using the Django rest framework to create an API. Say I have the following models: class Category(models.Model): name = models.CharField(max_length=100) def __unicode__(self): return self.name class Item(models.Model): name = models.CharField(max_length=100) category = models.ForeignKey(Category, related_name='items') def __unicode__(self): return self.name I want to write a serializer for Item such that it returns "category_name" during serialization (i.e. read) but then also takes "category_name" back and converts it into category during deserialization (i.e. write) [you can assume that category_name is unique in its table] I was able to find this link which solves the problem for reads but doesn't work for writes. class ItemSerializer(serializers.ModelSerializer): category_name = serializers.CharField(source='category.name') class Meta: model = Item fields = ('id', 'name', 'category_name') Is there a way to modify it such that it can be used to populate new items via an API? -
Hello All, I'm new in learning in Django and getting error when I try to call the webpage. Please refer to the below code
def index(request): ob=Com1.objects.all() return render(request,'index.html',{'ob':ob}) def sports(request,name): cat=Categ.objects.filter(name=name) com=Com1.objects.filter(categ_id=cat[0].id) return render(request,'sports.html') -
Django Tenant Schemas "argparse.ArgumentError: argument --skip-checks: conflicting option string: --skip-checks"
I faced the same issue as here but was unable to fix it from the answer provided with the question. I tried adding tenant_schemas to the end of INSTALLED_APPS like this INSTALLED_APPS = SHARED_APPS + TENANT_APPS + INSTALLED_APPS + ['tenant_schemas'] but this didn't worked. I moved INSTALLED_APPS to the bottom of the settings file and this also didn't worked. The only option left for me is to copy the entire tenant_schemas library, fix it using the changes provided in the pull request in the answer, and connect it with the project as an app, which is a terrible way to proceed. If there is an example for the solution provided in the above answer, or a better solution in itself, please let me know. TRACEBACK - Traceback (most recent call last): File "E:\PycharmProjects\uniuno\uniuno\manage.py", line 22, in <module> main() File "E:\PycharmProjects\uniuno\uniuno\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Ishu\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Ishu\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Ishu\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 322, in run_from_argv parser = self.create_parser(argv[0], argv[1]) File "C:\Users\Ishu\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 296, in create_parser self.add_arguments(parser) File "C:\Users\Ishu\AppData\Local\Programs\Python\Python39\lib\site-packages\tenant_schemas\management\commands\migrate_schemas.py", line 20, in add_arguments command.add_arguments(parser) File "C:\Users\Ishu\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\migrate.py", line 26, in add_arguments parser.add_argument( File "C:\Users\Ishu\AppData\Local\Programs\Python\Python39\lib\argparse.py", line 1434, in add_argument return self._add_action(action) File "C:\Users\Ishu\AppData\Local\Programs\Python\Python39\lib\argparse.py", … -
Django smtplib.SMTPRecipientsRefused: Recipient address rejected: User unknown in virtual mailbox table
I have a django app that requires users to create an account before they are able to use the service. Upon registration, the user is sent an email with a link to activate their account. Lately however, I have noticed that when someone creates an account with slightly more unusual email addresses than gmail.com, an error is being thrown that the user is 'unknown in the virtual mailbox table. This used to not be the case, but i dont understand what has changed. Full error below (with email address anonymized): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/smtplib.py", line 881, in sendmail raise SMTPRecipientsRefused(senderrs) smtplib.SMTPRecipientsRefused: {'testing@xxxx.com': (550, b'5.1.1 <testing@xxxx.com>: Recipient address rejected: User unknown in virtual mailbox table')} Do you guys have an idea? Thanks! -
Is there a way of defining variables in HTML files with Django?
I'm working on a Django project that has a "random page" link that leads the user to (you guessed it) a random page of the website. I made a function in views.py that returns randomly the name of a page: def randomPage(request): fileList = util.list_entries() num = random.randint(0,len(fileList)-1) fileName = fileList[num] return fileName And I was wondering if there was a way of passing the result to a variable in the HTML file where the link is, like this: {% random = views.randomPage() %} <div class="row"> <div class="sidebar col-lg-2 col-md-3"> <h2>Wiki</h2> <div> <a href="{{random}}/">Random Page</a> </div> {% block nav %} {% endblock %} </div> </div> What I'm trying to achieve is to lead the user to an url such as "/CSS" or "/HTML" (both are pages of the website) -
How to create model fields in a loop?
I am creating a project in Django where in my 'Myapp' I have two models in models.py. I am trying to achieve the objects of model_1 to be the field of my model_2. The example of my code and what I have tried has been shown below:- Model_1 in models.py class Skills(models.Model): skill_name = models.CharField(max_length=200, blank= False) Model_2 in models.py (What I have tried) class Resources(models.Model): pass for skill in Skills.objects.all(): Resources.add_to_class(skill, models.CharField(max_length=200)) the error that I am getting NameError: name 'Resources' is not defined Can anyone provide a better solution to my problem that can create a model_2(Resources) that will have fields skill_1, skill_2,...,skill_3 from my model_1(Skills) -
Python/Django how to stop duplicate entry in list
I have been struggling with a hard puzzle :), but I can't seem to figure it out. It is probably something easy but I don't see it. Maybe you guys can help me out. The problem is that a product shows a duplicate in the cart, but I want to stop that if 2 products in the cart are a 1+1=1 deal/campaign. The problem: First item of the cart reaches the elif not combi_sets and product.deal_type: and if product.deal_type: statements, it adds the product to the items and also sets it as an entry for a combi product. Thats probably why it is a duplicate? The case: Check before adding the product to the items if the product is already matched in the combi_sets list and skip adding that in the items. Here I loop through the cart items and check if there is a product with deal.type: combi_products = [] combi_sets = [] for i in cart: try: cartitems += cart[i]['quantity'] product = Product.objects.get(product_id=i) total = (product.price * cart[i]['quantity']) order['get_original_price'] += total order['get_cart_items'] += cart[i]['quantity'] if product.deal_type: # deal.type is combi, combi applies when admin creates a deal of 1+1 product for one price product_id = product.product_id combi_products.append(product_id) # …