Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Executing two queries in the get_queryset function from Python Django
I am trying for a couple of days to perform an update on a model. I cannot get it right though. I am trying using the ModelViewSet. I know that the function get_queryset must return something, so i cannot return None. Beacause of that first i perform the update to a model and then i try to return the updated result. The problem is that the update query is not performed for some reason i do not know. class UpdateBooks(viewsets.ModelViewSet): serializer_class = BookSerializer def get_queryset(self): variables = open('F:/Facultate/Personal Work/LibraryApi/api/update_file.txt', 'r').read() Book.objects.raw("UPDATE library_book SET subject = " + "'" + variables + "'" + " WHERE title = 'Nopti Albe'") return Book.objects.raw("SELECT * FROM library_book WHERE title = 'Nopti Albe'") So the thing is: first i read a something from a file with which i will update the model and afet that i return the updated model. The problem is as i mentioned before is that the first query does not executes. -
How to ignore 404 exceptions in Rollbar?
I'm using Rollbar in a Django 1.11.9 app (Python 2.7) and I'm trying without success to configure it to ignore 404 exceptions. I've checked Rollbar docs for Python and noticed I'm already using the configuration 'exception_level_filters': [(Http404, 'ignored')] which is not working at all. So first I thought the library I was using was raising a different type of exception (Django REST Framework) and tried to add its NotFound exception in the exception_level_filters, but (1) it didn't work and (2) the 404 exceptions were not being ignored for modules not using this library as well. So I checked my views and found out there was a custom view handling 404 errors, which simply used the Django logging method to log the request path in debug level. I've tried editing the logging settings by removing Rollbar from the logger handlers with level debug and even removed the logging in the custom view, however I still get Rollbars for 404 errors. I've also tried using the Rollbar configuration ignorable_404_urls with the value re.compile('.*') hoping it would ignore for all URLs, but it didn't work as well. Has anyone been able to do it properly in a Django app and/or seen any mistake … -
UnboundLocalError: local variable 'csv_file' referenced before assignment
When I run my code I get these errors: if not csv_file.name.endswith('.csv'): UnboundLocalError: local variable 'csv_file' referenced before assignment views.py import csv, io from django.shortcuts import render from django.contrib import messages from .models import Profile # Create your views here.# one parameter named request def profile_upload(request): # declaring template template = "profile_upload.html" data = Profile.objects.all()# prompt is a context variable that can have different values depending on their context prompt = { 'order': 'Order of the CSV should be product_title, sku, slug, image_path, price', 'profiles': data } # GET request returns the value of the data with the specified key. if request.method == "GET": return render(request, template, prompt) csv_file = request.FILES['file'] # let's check if it is a csv file if not csv_file.name.endswith('.csv'): messages.error(request, 'THIS IS NOT A CSV FILE') data_set = csv_file.read().decode('UTF-8') # setup a stream which is when we loop through each line we are able to handle a data in a stream io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=',', quotechar="|"): _, created = Profile.objects.update_or_create( name=column[0], email=column[1], address=column[2], phone=column[3], profile=column[4] ) context = {} return render(request, template, context) I am not sure why I am getting this error, it would be great if anyone can help … -
Django form: how to have access to variable initialized in __init__?
I have a Modelform that override init method I initialize a variable country in init and would like to have access outside init to set initial value of a form field country (outside of init) I am newbie in python... form.py class ParametrageForm(forms.ModelForm): def __init__(self, request, *args, **kwargs): super(ParametrageForm, self).__init__(*args, **kwargs) self.request = request instance = Parametrage.objects.get(asp_par_cle = kwargs['instance'].asp_par_cle) country = Site.objects.get(sit_abr = instance.asp_par_loc).reg.pay.pay_nom_eng # initial value country = forms.CharField(label = _("Country"),widget=forms.TextInput,initial=country, disabled=True) -
Can't get the celery task of real-time information
I want to get the task of celery information, and then refer to the document(http://docs.celeryproject.org/en/latest/userguide/workers.html?highlight=revoke#inspecting-workers) Here's the code. celery.py app = Celery('tasks', broker='redis://127.0.0.1:6379/0') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) i = app.control.inspect() views.py from myproject.celery import i class AAA(APIView): def get(self,request): print(i.registered()) print(i.active()) print(i.scheduled()) print(i.reserved()) return Response("ok") This is the printed result {'celery@wwl': ['quantum.tasks.pro_execute']} {'celery@wwl': []} {'celery@wwl': []} {'celery@wwl': []} Can't get the last three results? I don't know why, But can see them on flower dashboard Thx a lot . -
Fetching data from csv and displaying it in a website using django
I have a csv file of employee attendance. I want to display the data in the csv file using django. I am new to django. Can anyone please help me with this. -
Django Foreign Key Constraint not represented in PostGres DB Model
I have created a model X, that is assigned to model Y as foreign key object: from appX.models import ModelX class ModelY(models.Model): model_x = models.ForeignKey(to=ModelX, on_delete=models.CASCADE, null=True) As shown above, ModelX stems from a different Django app than ModelY. This works pretty well and migrations also do not cause any problems. Whenever an invalid value is used, integrity errors show up as intended. However, within my PostgreSQL database, no foreign key relation is created for the model_x-field in the table of model Y. This issue DOES NOT OCCUR whenever I establish foreign key relations between apps of models, which are part of the same Django app. Do you have any ideas how to circumvent this behavior? -
How to Insert & Update Multiple Record in Django
I want to know how to deal with this task. here are the details: this is product_feature model class Feature(models.Model): has_value_choice = [ ('y', 'Yes'), ('n', 'No'), ] feature_id = models.AutoField(primary_key=True) feature_name = models.CharField(max_length=255, null = False) product_type = models.ForeignKey(Product_type, on_delete=models.SET_NULL, null=True) feature_has_value = models.CharField(choices=has_value_choice, max_length = 1, null = False) created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) class Product_feature(models.Model): product_feature_id = models.AutoField(primary_key=True) feature = models.ForeignKey(Feature, on_delete=models.SET_NULL, null=True) product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) product_feature_value = models.CharField(max_length=255, null = False) created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) here, I'm passing features data to the template to save features of the specific product in the product_feature model. <form> <table class="table table-bordered"> <thead> <tr> <th>Features</th> <th>Value</th> </tr> </thead> <tbody> {% for data in features_data %} <tr> {% if data.feature_has_value != 'n' %} <td>{{ data.feature_name }}</td> <td><input type="text" name="{{ data.feature_name }}" id="{{ data.feature_name }}" placeholder="Enter {{ data.feature_name }}" class="form-control" required/></td> {% else %} <td>{{ data.feature_name }}</td> <td> <select id="{{ data.feature_name }}" name="{{ data.feature_name }}" class="form-control" required> <option selected id="select" value="yes">Yes</option> <option value="no">No</option> </select> </td> {% endif %} </tr> {% endfor %} </tbody> </table> </form> Now, the thing is how to insert this form data to the product features … -
Conditional LOGIN_URL in settings.py
I need different settings.LOGIN_URL for staff users. How can I make this dynamic? if request.user.is_staff: LOGIN_URL = 'two_factor:login' else: LOGIN_URL = 'account_login' -
How to perform search with django and ajax?
Here I have a bootstrap modal inside the create_user_group.html template.In this modal within the template I want to search users asynchronously so that I implemented ajax search like this but it giving no results.I am very new to ajax things so is there anything I need to learn ? what I might be doing wrong here ? class UserGroupCreate(generic.CreateView): model = Group form_class = CreateUserGroupForm template_name = 'user_groups/create_user_group.html' success_url = reverse_lazy('user_groups:list_groups') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['users'] = get_user_model().objects.filter(is_active=True) return context def search_users(request): # searching users in group page bootstrap modal q = request.GET.get('q') print(q) if q: users = get_user_model().objects.filter(Q(first_name__icontains=q) | Q(last_name__icontains=q)) else: users = [] return render(request,'user_groups/ajax_user_search_results.html', {'users':users}) create_user_group.html <div class="modal-body"> <input name="q" type="text" id="search" /> <ul id="search-results"> {% include 'user_groups/ajax_user_search_results.html' %} </ul> </div> ajax_user_search_results.html template {% for user in users %} <li>{{user.name}}</li> {% endfor %} ajax which is inside create_user_group.html template <script> $('#search').keyup(function() { $.ajax({ type: "GET", url: "{% url 'user_groups:search_users' %}", data: { 'q' : $('#search').val(), }, success: searchSuccess, dataType: 'html' }); }); function searchSuccess(data, textStatus, jqXHR) { $('#search-results').html(data) } </script> -
Python relative import different for Django
I am experiencing an inconsistency between Django and Spyder (or any non-Django framework). I make use of relative imports for my modules by means of the . operator. This works in Spyder (i.e. non-Django) but as soon as I run my Django server I get the errorImportError: attempted relative import with no known parent package. My code: I have a helpers.py file with a few helper functions which I import as follows: from .helpers import get_SQL_TABLE. The helpers.py is in the same directory as the scripts whence it is called but as mentioned, it leads to an error in Django but not in Spyder. -
Django: how to modify form field order of bound form with one unbound field?
I have an update form with 4 fields to display 3 of them are related to a class to which the form is bound the last field (country) is only for information and I would like that field to be display in first position currently, it is displayed at the end of my form... I tryed to use field_order but country field is ignored... form.py class ParametrageForm(forms.ModelForm): def __init__(self, request, *args, **kwargs): super(ParametrageForm, self).__init__(*args, **kwargs) self.request = request self.language = request.session.get('language') self.user = request.user.id # id de l'utilisateur self.user_pays = request.session.get('user_pays') # pays de l'utilisateur self.user_site_type = request.session.get('user_site_type') self.user_site = request.session.get('user_site') instance = Parametrage.objects.get(asp_par_cle = kwargs['instance'].asp_par_cle) SITE_CONCERNE = Site.option_list_sites(self.language) if self.language == 'en': country= Site.objects.get(sit_abr = instance.asp_par_loc).reg.pay.pay_nom_eng elif self.language == 'fr': country= Site.objects.get(sit_abr = instance.asp_par_loc).reg.pay.pay_nom_fra else: country= Site.objects.get(sit_abr = instance.asp_par_loc).reg.pay.pay_nom_eng self.fields["pays"] = forms.CharField(label = _("Country"),widget=forms.TextInput,initial=country, disabled=True) self.fields["asp_par_loc"] = forms.ChoiceField(label = _("Site concerned by settings"), widget=forms.Select, choices=SITE_CONCERNE,) self.fields["asp_par_ale"] = forms.IntegerField(label = _("Stock alert value for this site"), widget=forms.TextInput,) self.fields["asp_par_con"] = forms.IntegerField(label = _("Stock confort value for this site"), widget=forms.TextInput,) class Meta: model = Parametrage fields = ('asp_par_loc','asp_par_ale','asp_par_con',) field_order = ['country','asp_par_loc','asp_par_ale','asp_par_con',] -
Django: Chat app (Don't need to refresh to read the message)
i had created chat app using django, and it works fine and no error (terminal and console browser) but every time the user receive a message from the admin, he need to refresh the page to see the message of the admin, same goes with the admin, the admin need to refresh the page to see the message of the user I use redis server this is my file tree this is my thread.html this is my consumers.py class ChatConsumer(WebsocketConsumer): def websocket_connect(self, event): #print('connected', event) #await asyncio.sleep(10) other_user = self.scope['url_route']['kwargs']['username'] me = self.scope['user'] #print(other_user, me) thread_obj = self.get_thread(me, other_user) chat_room = f"thread_{thread_obj.id}" self.chat_room = chat_room self.channel_layer.group_add( chat_room, self.channel_name ) self.send({ "type": "websocket.accept" }) def websocket_receive(self, event): print('receive', event) front_text = event.get('text', None) if front_text is not None: loaded_dict_data = json.loads(front_text) msg = loaded_dict_data.get('message') #print(msg) user = self.scope['user'] username = 'default' if user.is_authendticated: username = user.username myResponse = { 'message': msg, 'username': username } self.channel_layer.group_send( self.chat_room, { "type": "chat_message", "text": json.dumps(myResponse) } ) def chat_message(self, event): self.send({ "type": "websocket.send", "text": event['text'] }) def websocket_disconnect(self, event): print('disconnected', event) @database_sync_to_async def get_thread(self, user, other_username): return Thread.objects.get_or_new(user, other_username)[0] my admin.py class ChatMessages(admin.TabularInline): model = ChatMessage class ThreadAdmin(admin.ModelAdmin): inlines = [ChatMessages] class Meta: model = … -
Django : How to create , write and attach .ics file to mail with meeting response?
How can i create and attach .ics or .icalender file as an attachment in send_mail() function django 1.11? I have tried below code but failed . : from ics import Calendar, Event def send_mail_to_interviwee(request, round_pk): intv_round = Round.objects.get(pk=str(round_pk)) supporters = list(intv_round.supporting_interviewer.values_list('email', flat=True)) round_taker = intv_round.assignee subject = "Interview Scheduled..Please go through details" htmly = get_template('Evaluator/email_interview.html') d = { 'round_taker': round_taker, 'candidate': intv_round.interview.candidate, 'round_date': intv_round.date, 'round_name': intv_round.name, 'round_time': intv_round.contact_time, 'round_type': intv_round.round_type, 'additional_Comments': intv_round.comments, } cal = Calendar() event = Event() event.name = intv_round.name event.begin = intv_round.date event.time_equals = intv_round.contact_time cal.events.add(event) file_name="interview.ics" with open(file_name,'w') as my_file: my_file.writelines(cal) html_content = htmly.render(d) all_mails = [round_taker.email] + supporters #Format: Subject, Message, from, to msg = EmailMultiAlternatives(subject, "Please find details of Candidate in this mail", request.user.email, all_mails) msg.attach(file_name) msg.attach_alternative(html_content, "text/html") i am getting following error: File "venv\lib\site-packages\ics\__init__.py", line 3, in <module> from .alarm import AudioAlarm, DisplayAlarm File "venv\lib\site-packages\ics\alarm\__init__.py", line 1, in <module> from ics.alarm.audio import AudioAlarm File "venv\lib\site-packages\ics\alarm\audio.py", line 25 trigger: Union[timedelta, datetime] = None, ^ enter code here -
Django pagination dependent on ordering
I have the following model (simplified): class Post(models.Model): title = models.CharField(max_length=20) date_created = models.DateTimeField(auto_now=True) class Meta: ordering = ('-date_created',) # note the "reverse" ordering here , then my custom ListView based on generic.ListView: class PostListView(generic.ListView): queryset = Post.objects.all() paginate_by = 2 and, finally, the following template: <nav class="navigation"> {% if page_obj.has_previous %} <a class="nav-link-prev left" href="?page={{ page_obj.previous_page_number }}">Previous</a> {% endif %} {% if page_obj.has_next %} <a class="nav-link-next right" href="?page={{ page_obj.next_page_number }}">Next</a> {% endif %} </nav> My pagination implemented this way works, but due to the reverse ordering (i.e -date_created) field, its Previous/Next labels are misplaced. In other words my template outputs "Previous" where it should be "Next", and vice versa. If I remove a - sign in ordering = ('-date_created',) it will work fine, but that's not the ordering I would like to have on my website. Is there an easy and idiomatic way of fixing this misbehavior? What am I missing? -
how to update the json data (i.e using Id value) in python django?
I want Update the data to use put request update the data by using Employee Id Value first retrieve the data which we pass id number and update that particular Id data def put(self, request): serializer = employeeSerializer( data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I have this sample code but I didn't get update at particular id number. can anyone help for that ques. -
How to use more than one class modifier in django admin?
i have already wrote a class to customize my model in django admin (extends from admin.ModelAdmin),but now i want to use a rich-text editor for my TextFields in that model(needs to extends from SummernoteModelAdmin), i don't know how to apply both of them. in admin.py admin.site.register(my_model, my_modelA) i've tried this but got error: admin.site.register(my_model, my_modelA, my_modelB) how can i use both of those classes ? Thanks~ -
Django models: use save() show which field failed instead of throwing 500
my code myapp/validators.py from django.conf import settings def UIDValdator(obj_uid): if re.match(settings.UID_REGEX_PATTERN, obj_uid): return True raise ValidationError(f"The uid must follow the pattern: {settings.UID_REGEX_PATTERN}") myapp/models.py from django.conf import settings from .validators import UIDValdator class MyObject(models.Model): uid = models.CharField(validators=[UIDValidator],....) ... ... def save(self, *args, **kwargs): if UIDValidator(self.uid): super(MyObject, self).save(*args, **kwargs) My question I wish I could only use the UIDValidator once, now I use it twice because if I try to create my object using the ORM will not raise the exeption, and if I remove the validation from my field will throw 500 instead of underlining the field with the error message. Discovered it when I started running the tests. -
Change field representation in Django Admin fieldset
I want to change the string representation of a field in Django Admin. The field is a foreign key from Product. I want to delete the __str__ method inside the Product model, I want to find a way to have that representation in the admin. #models.py class Product(models.Model): name = models.CharField() amount = models.IntegerField() description = models.TextField() def __str__(self): # To delete return "{} XL".format(self.name) class Query(models.Model): name = models.CharField() product = models.ForeignKey(Product) ... #admin.py class QueryAdmin(admin.ModelAdmin): ... fieldsets = ( ('Product', { 'fields': ( 'product', ) def product(self): return "{} XL".format(obj.product.name) -
Statistics Table query related:
I created Statistics API in django using MYSQL Connector, IN that API i have 3 table all three tables are same name and same content(s_no,target,achieve,balance),i want add three table(table1.target+table2.target+table3.target) like this how to add like this 3 table as same field...can one have idea kindly guide to me "SELECT SUM(target) as target, SUM(achieve)as achieve, SUM(balance) AS balance FROM develop where date BETWEEN DATE_SUB(NOW(), INTERVAL (365) DAY) AND NOW()") i am using this query for adding single table values but i want to add all the three table as a same time..... -
Django authenticate always returns None no matter what
I have been trying to add registration/login/logout functionality. The user registration appears to be working fine, as the created user shows up in Django admin and appears in the database. However, whenever I try to implement the login functionality, it never works. I think I've narrowed down the problem to authenticate(). I have tried everything, and no matter what I do, the authenticate() function always returns None. The usernames and passwords I give are clearly being stored, and yet it doesn't seem to be getting the password correctly, since printing out raw_password = form.cleaned_data.get('password1') in the login_user view gives None. How can I get the login functionality to work? In urls.py urlpatterns = [ path('register', views.register_user, name='register'), path('login', views.login_user, name='login'), path('logout', views.logout_user, name='logout'), ] In views.py def register_user(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): user = form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') print(f'User is: {user}') login(request, user) return redirect('/') else: form = UserCreationForm(request.POST) context = { 'form': form } return render(request, 'register.html', context) def login_user(request): if request.method == 'POST': form = AuthenticationForm(request=request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) print(f'User is: {user}') print(f'username is: {username}') print(f'password is: {raw_password}') if user … -
Django Celery Beat doesn't execute the tasks old tasks
I had created PeriodicTask objects with IntervalSchedule as hourly and assigned tasks function to them. celery -A appname worker -B --loglevel=debug -c 5 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: appname:0x7f687c231a10 - ** ---------- .> transport: amqp://guest:**@localhost:5672// - ** ---------- .> results: redis://localhost:6379/ - *** --- * --- .> concurrency: 5 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> mainqueue exchange=mainqueue(direct) key=mainqueue ... ... [2020-02-14 01:03:13,627: DEBUG/Beat] DatabaseScheduler: Fetching database scheduleESC[0m [2020-02-14 01:03:13,639: DEBUG/MainProcess] Start from server, version: 0.9, properties: {'capabilities': {'publisher_confirms': True, 'exchange_exchange_bindings': True, 'basic.nack': True, 'consumer_cancel_notify': True, 'connection.blocked': True, 'consumer_priorities': True, 'authentication_failure_close': True, 'per_consumer_qos': True}, 'cluster_name': 'rabbit@kiraakdrop', 'copyright': 'Copyright (C) 2007-2015 Pivotal Software, Inc.', 'information': 'Licensed under the MPL. See http://www.rabbitmq.com/', 'platform': 'Erlang/OTP', 'product': 'RabbitMQ', 'version': '3.5.7'}, mechanisms: [b'AMQPLAIN', b'PLAIN'], locales: ['en_US']ESC[0m [2020-02-14 01:03:13,642: INFO/MainProcess] Connected to amqp://guest:**@127.0.0.1:5672// [2020-02-14 01:03:13,643: DEBUG/MainProcess] ^-- substep okESC[0m .. [2020-02-14 01:03:14,770: DEBUG/MainProcess] basic.qos: prefetch_count->20 [2020-02-14 01:03:14,841: DEBUG/Beat] Current schedule: <ModelEntry: TASK-157-project run_project_task(*[], **{'p_id': 157}) <freq: 1.04 days>> <ModelEntry: TASK-PROJ run_project2_task(*[], **{'pp_id': 4}) <freq: 7.00 hours>> There are around 200+ <ModelEntry: Task scheduled tasks but only a few (40 tasks which are … -
Django - Issue with Dynamic URL Redirect using Reverse in Model
I am attempting to set up dynamic URL redirecting using the method outlined in my tutorial. However, it always mangles the actual URL. For example, it should redirect to http://127.0.0.1:8000/products/3/, but rather redirected to http://127.0.0.1:8000/products/=/products/3/ My redirect function in models is def get_absolute_url(self): return reverse("product-detail", args=[self.id]) Note: My tutorial said I should pass in `kwargs={"id": self.id}, however, that created a whole other list of issues, and other posts I've seen pass in args, instead. My urlpattern is path('products/<int:my_id>/', dynamic_lookup_view, name='product-detail'), I've been puttering around for a while trying to figure this out. Would appreciate any help. -
Connection reset by peer django
I am trying to create a register page.Model and Form has been completed correctly. I can create and save a user in python shell but when I do it in webpage it respond an error it's like: Exception happened during processing of request from ('127.0.0.1', 64590) Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 720, in __init__ self.handle() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 171, in handle self.handle_one_request() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 179, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socket.py", line 589, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 54] Connection reset by peer View.py register function: def register(request,id): form = RegisterForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get("username") name=form.cleaned_data.get("name") password = form.cleaned_data.get("password") email=form.cleaned_data.get["email"] newUser1=user(username=username) newUser1.set_password(password) newUser1.save() print(newUser1) login(request,newUser1) messages.info(request,"Başarıyla Kayıt Oldunuz...") return redirect("PatchPanel") context = { "form" : form, "id":id } return render(request,"SignupLogin.html",context) -
django oscar create bulk offer with quantity
I'm new to the Django Oscar framework. i want to add a bulk offer with item quantity, for example - in basket, product1 x 2 items product2 x 3 items product4 x 1 items when basket has this products with correct quantity. then only, i want to add bulk offer.