Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create Affiliate system for my e-commerce website in Django
As, I am building a Django based e-commerce website and now I want to add the affiliate system setup to my website, like as the users or any influencers can generate affiliate links for any products on my website and if someone purchase through that URL then the commission is added to that influencer affiliate account. Can anyone help me out in this situation? -
File upload in Django rest
I have created an api for uploading 'profilepicture' for an existing user. Models.py class ProfilePicture(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile_picture') profile_pic_path = models.FileField( upload_to=path_and_rename, max_length=254, blank=True, null=True ) class Meta: db_table = "profile_picture" Serializer.py class ProfilePictureSerializer(serializers.ModelSerializer): class Meta: model = ProfilePicture fields = '__all__' Views.py class ProfilePictureViewSet(viewsets.ModelViewSet): queryset = ProfilePicture.objects.all() serializer_class = ProfilePictureSerializer def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) if serializer.is_valid(): serializer.save() custom_data = { "status": True, "message": 'Successfully uploaded your profile picture.', "data": serializer.data } return Response(custom_data, status=status.HTTP_201_CREATED) else: custom_data = { "status": False, "message": serializer.errors, } return Response(custom_data, status=status.HTTP_200_OK) The api is working fine using 'Django REST framework' UI. While using postman i'm getting this error. How can i solve this? -
Count within Django Template how many times a word appears
We have an app which has three tables for bookings (asp, bfbw, tours) and a table for athletes who can be assigned to each booking. What we are looking at achieving is obtaining a count of all bookings that have a status of confirmed against each athlete within the athlete table. For example Athlete1 has 2 bookings set to 'Confirmed' and Athlete2 has 2 bookings set to 'Confirmed'. Rather than 2 being displayed against each athlete record, we get the total 4. We have tried doing this in a view with the below code, but it is not counting the number confirmed cases for each athlete. Instead it is calculating all confirmed cases across the three booking tables. x = 0 y = 0 z = 0 for booking in asp_data: if booking.status == 'Confirmed': for athlete in ath_data: if booking.athlete_id == athlete.id: x = x+1 for booking in bfbw_data: if booking.status == 'Confirmed': for athlete in ath_data: if booking.athlete_id == athlete.id: y = y+1 for booking in tour_data: if booking.status == 'Confirmed': for athlete in ath_data: if booking.athlete_id == athlete.id: z = z+1 active_count = x+y+z print(x+y+z) We have also tried doing this within the Django template but no … -
Django and Sortable.js only one for iteration can drag objects
i got a for iteration that iterate 3 columns with sorteable.js objects. The first iteration works well, i can drag objects perfectly, the problem is in the other 2 iterations were i cant drag any object, they have basically the same objects so i dont know what its the problem. board.html <div class="container"> <div class="row"> {% for co in columnas %} <div class="col-4" id="columnas"> <div class="row align-items-start"> <p><strong>COLUMN Name: </strong>{{ co.nombre }}</p> <div class="list-group" id="tareas"> <div class="list-group-item"> <h5>Task 1</h5> </div> <div class="list-group-item"> <h5>Tarea task2</h5> </div> <div class="list-group" id="tareas"> <div class="list-group-item"> <h5>Tarea task3</h5> </div> </div> </div> </div> </div> {% endfor %} </div> </div> Option.JS const tareas = document.getElementById('tareas'); const columnas = document.getElementById('columnas'); new Sortable(tareas, { group: 'shared', animation: 150, ghostClass: 'blue-background-class' }); new Sortable(columnas, { group: 'shared', animation: 150, ghostClass: 'blue-background-class' }); -
Django help me ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine
i have a really trange problem, when i run my django server, even the simplest one it calls this error once every like 1 minute. ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine. The thing is, nothing is breaking. Server is running fine. I have newest version of python and django installed. Does anybody know how to fix this? This is the screenshot of this error -
download youtube video in user computer not on the server in Django
I make youtube video downloader in django with pytube library. all things work fine. i mean when i run application on localhost its download youtube videos. But when i deployed this application on AWS(amazon web service) videos not download in user computer. videos downloading on aws remote computer. So my question is how to download videos in local computer(user computer) not on the server. please anyone help me. many many Thanks in advance. my downloading function is here:- def downloading(request): homedir = os.path.expanduser("~") dirs = homedir + '/Downloads' if request.method == 'POST': formatRadio = request.POST['formatRadio'] if formatRadio != "audio": qualityRadio = request.POST['qualityRadio'] video_url_d = request.POST['video_url_d'] print(formatRadio) yt = YouTube(video_url_d) print(yt) print("Downloading start ....") if formatRadio == "audio": yt.streams.filter(type = formatRadio).last().download(dirs) else: yt.streams.first().download(dirs) print("Downloding completed") res = render(request,'ydownloader/home.html',{"msg":"Downloading completed Thanks for try our service"}) return res -
How to count the number of unique values on query's related model in Django?
Say I have these three models: class User(models.Model): .... class Tweet(models.Model): created_at = models.DateTimeField(blank=True, null=True) user = models.ForeignKey( "core.User", related_name="tweets", on_delete=models.SET_NULL, null=True ) class Tag(models.Model): tag = models.CharField(max_length=100, blank=False, unique=True) tweets = models.ManyToManyField(Tweet, related_name="calls") The query I want to build is 'Tags, ordered by the number of unique tweet users which made tweets in a particular time period'. I had built a custom counting query to achieve this, it worked, but it was slow. I've now arranged the DB as above, with the tags as a separate model related to Tweets. tags = Tag.objects.filter(tweets__created_at__week=date.isocalendar()[1]).annotate(count=Count('tweets__user')).filter(count__gt=1).order_by('-count', 'asset').distinct() The issue is, the Count('tweets__user') part of the query effectively counts the number of tweets associated with the tag. The tweets can (and are) often from the same account, I want the number of unique twitter user accounts. Is there a way to build this query, with the data modelled in this way, using Django only? -
matching query does not exist What Do I make?
I wrote this code in my view I am using windows 10 and django package I have 6 products def product_detail(request , id): prodcut_detail = Product.objects.get(id=id) context = {'prodcut_detail' : prodcut_detail} return render(request , 'Product/product_detail.html' , context) But he said Product matching query does not exist. And also i added this in my urls.py urlpatterns = [ path( '<int:id>', views.product_detail) ] What Do i make? -
Django Channels Daphne uvicorn
I wrote Django Channels for practice. Use Daphne daphne project.asgi:application Everything works well. Use uvicorn uvicorn project.asgi:application Error on the page (index):16 WebSocket connection to'ws://127.0.0.1:8000/ws/chat/123/' failed: Error during WebSocket handshake: Unexpected response code: 400 I don't know where I went wrong. I follow the official use python -m pip install uvicorn gunicorn gunicorn project.asgi:application -k uvicorn.workers.UvicornWorker Error on the page (index):16 WebSocket connection to'ws://127.0.0.1:8000/ws/chat/123/' failed: Error during WebSocket handshake: Unexpected response code: 400 Please help me where I need to improve, thank you. -
Django tables2. Render link for empty cells
I needed render link for empty cells with some default text. By default, django-tables2 for null values render "—", without any link attached to it. I managed to do this using TemplateColumn like this: import django_tables2 as tables # template TEMPLATE = """ {% if record.some_field %}{{ record.some_field }}{% else %}<default text>{% endif %} """ # column definition link_column = tables.TemplateColumn(linkify=True, template_code=TEMPLATE) I just wanted to ask if there is more convenient way to achieve this, cause it sure seems like this. -
no module named mysite.wsgi django Heroku Deployment
i am trying to deploy my django project on heroku backed by postgreSQL it runs fine on local however while deploying deployment is successful when i run the url like myapp.herokuapp.com, it throughs error my Procfile code: web: gunicorn mysite.wsgi --log-file - wsgi.py import os from django.core.wsgi import get_wsgi_application import sys BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(BASE_DIR) os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") application = get_wsgi_application() settings.py """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 3.2.3. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ import os from pathlib import Path import dj_database_url # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-!j&awpwhyus30$je(5de%5w5b%e-nu_alq!2g)rwfn3-wia94=' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['0.0.0.0', 'localhost', '127.0.0.1','dmhc.herokuapp.com'] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' # Application definition INSTALLED_APPS = [ 'admin_interface', 'colorfield', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mysite', 'tinymce', 'captcha', 'whitenoise.runserver_nostatic', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] ROOT_URLCONF = 'mysite.urls' … -
why coverage report differs according to how I execute it
I am writing a django app. I am trying unittest and pytest with coverage. And depending on how I run tests, I get different coverage report. Relevant Code I have this in settings_test.py , a runner for pytest: class PytestTestRunner(UnManagedModelTestRunner): def __init__(self, verbosity=1, failfast=False, keepdb=False, **kwargs): self.verbosity = verbosity self.failfast = failfast self.keepdb = keepdb def run_tests(self, test_labels): """Run pytest and return the exitcode. It translates some of Django's test command option to pytest's. """ import pytest argv = [] if self.verbosity == 0: argv.append('--quiet') if self.verbosity == 2: argv.append('--verbose') if self.verbosity == 3: argv.append('-vv') if self.failfast: argv.append('--exitfirst') if self.keepdb: argv.append('--reuse-db') argv.extend(test_labels) return pytest.main(argv) TEST_RUNNER = "settings_test.UnManagedModelTestRunner" And also this script to run tests: runner.py USAGE = """ USAGE: python runner.py (will run unittest suite) python runner.py unittest (will run unittest suite) python runner.py pytest (will run pytest suite + coverage) """ TEST_RUNNERS_MAP = { 'pytest': 'testapp.settings_test.PytestTestRunner', # pytest 'unittest': 'testapp.settings_test.UnManagedModelTestRunner', # unittest } if __name__ == "__main__": os.environ['DJANGO_SETTINGS_MODULE'] = 'testapp.settings_test' django.setup() # Get argument to decide which test suite to run. arguments = sys.argv[1:] arg = arguments[0] if 0 < len(arguments) else "unittest" runner = TEST_RUNNERS_MAP[arg] TestRunner = get_runner(settings, test_runner_class=runner) test_runner = TestRunner() failures = test_runner.run_tests(["unit_tests"]) sys.exit(bool(failures)) Test runs … -
how do I get rid of the 404 error when clicking on the detail button using ajax
I am getting 404 page not found error when placing a get request using ajax call for the following URL. http://10.1.2.5:8000/13/data I know this is a simple path problem - resource not found error but not able to fix this issue. The folder structure for static and templates is under the app post I have templates and static folder and then a directory with posts and static files in static folder like js files and html files under templates with posts directory and all html files. I have verified the path in html files for javascript. I can even see the hello world detail message logged in the console in detail.js file. Once the ajax call is started it throws an error as I cannot print anything in the console.log after the ajax get method. Thanks in advance. detail.js =========== console.log('hello world detail') const postBox = document.getElementById('post-box') const alertBox = document.getElementById('alert-box') const backBtn = document.getElementById('back-btn') const updateBtn = document.getElementById('update-btn') const deleteBtn = document.getElementById('delete-btn') const url = window.location.href + "data/" const updateUrl = window.location.href + "update/" const deleteUrl = window.location.href + "delete/" const updateForm = document.getElementById('update-form') const deleteForm = document.getElementById('delete-form') const spinnerBox = document.getElementById('spinner-box') const titleInput = document.getElementById('id_title') const bodyInput = … -
Django: Query to check whether the request.user is group's admin
class Group(models.Model): group_name = models.CharField(max_length=256) group_desc = models.CharField(max_length=2000, blank=True) created_by = models.ForeignKey(User, on_delete=models.PROTECT, blank=True, null=True, related_name='created_groups') group_pic = models.ImageField(blank=True) users = models.ManyToManyField(User, through='GroupMember') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class GroupMember(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) is_group_admin = models.BooleanField(default=False) I have these two models and I want to query whether the request.user is part of a particular group and is group_admin or not: I have successfully queried the first part but not able to do the latter part. For the first part, I have written the following query: GroupMember.objects.filter(id=pk, group__users__in=[request.user]) Any kind of help will be appreciated. -
how to use djangos send email module with model forms
I'm trying to figure out how to fill out the send_mail function when using a model form, to send a confirmation email to the user that fills out the form. class DeliveryForm(forms.ModelForm): class Meta: model = Delivery fields = ('full_name','email', 'phone', 'address', 'city', 'postal') # Create your views here. def info_view(request): if request.method == "POST": form = DeliveryForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('thanks')) form = DeliveryForm() return render(request, 'info.html', {"form": form}) -
Django get value from text input
Currently, I have a django page to display a table of OrderHistory objects. It looks like: {% extends 'base.html' %} <script src="https://code.jquery.com/jquery-3.3.1.js"></script> <!-- Import Jquery Here--> {% load static %} {%block content%} <p style="color: white;">There are {{ unread }} pending requests</p> <table class="table" style="color:white;"> <thead> <tr> <th scope="col">Status</th> <th scope="col">Concept</th> <th scope="col">Department</th> <th scope="col">Location</th> <th scope="col">Type</th> <th scope="col">User</th> <th scope="col">Quantity</th> <th scope="col">Order Date</th> <th scope="col"></th> <th scope="col"></th> </tr> </thead> <tbody> {% for e in orders %} {% if not e.order_read %} <tr style="background-color: grey;"> {% else %} <tr> {%endif%} <th> {% if e.order_read %} Read {% else %} Unread {%endif%} </th> <th>{{ e.order_concept }}</th> <th>{{ e.order_department }}</th> <th>{{ e.order_location }}</th> <th>{{ e.order_type }}</th> <th>{{ e.order_user_name }}</th> <th>{{ e.order_quantity }}</th> <th>{{ e.order_date }}</th> <th> <input type='text' id='tracking_number'></th> <th> <a href="/main/update_order/{{ e.id }}"><button type="submit" class="btn btn-primary" onclick="location.">Complete</button></a> </th> </tr> {% endfor %} </tbody> </table> {% endblock %} With the respective view and url's set up as follows: def update_order(request,pk): #save tracking number to this #send email with tracking number to user order = get_object_or_404(OrderHistory, pk=pk) order.order_read = True order.order_fulfillment_date = datetime.now() order.save() response = redirect('order_history') return response urls.py path('update_order/<str:pk>', views.update_order, name='update_order'), However I would like to add in an extra step where … -
Environment Variables in DevOps and Azure App Service
I am currently struggling to persist environment variables through my DevOps deployment pipeline to Azure App Service. I am deploying a Django app on Azure App Service with Docker containers and Azure's Container Registry. The containers are built on Azure DevOps and pushed to the registry via a release pipeline. I need to keep a few environment variables secret since the app will connect to our Azure Cosmos DB, and I'm doing so by using a tokenized .env file. The variables are kept secret and added to my '.env-prod' file with pipeline variables and the Replace Tokens DevOps task during the build. Here is what my '.env-prod' file looks like: PRODUCTION_KEY=#{{PRODUCTION_KEY}}# AZURE_DB=#{{AZURE_DB}}# AZURE_CONNECT=#{{AZURE_CONNECT}}# ... The tokens are getting properly replaced during the build on DevOps, and the build executes without errors to push containers to our Azure container registry. Now the problem arises when I launch the app on App Service via the docker compose script also used to build the containers. Here is the backend-service in my compose file which builds and runs the Django app: backend-service: env_file: backend_folder/.env-prod build: backend_folder # Container registry name in Azure image: **.azurecr.io/**:0.1.1 volumes: - static:/app/static command: gunicorn django_proj.wsgi:application --chdir django_proj --bind 0.0.0.0:8001 … -
heroku templates does not exist
I tried deploying my project on Heroku, and I get a "template does not exist" error... in my setting 2: have iterated between using and [str(BASE_DIR.joinpath('templates'))], it still doesn't work. In my previous deployment(a different app)i used just Templates and it worked perfectly back then. -
Django 'model' object is not iterable error
I have a problem that I would like you to help me. I have a list of users that shows fine, but when I try to edit a user I get the error: Django 'Residente' object is not iterable. This is my code: residente_list.html <div class="card-body"> {% if not obj %} <div class="alert alert-info">No hay Residentes</div> {% else %} <table class="table table-striped table-hover"> <thead> <th>Nombres</th> <th>Genero</th> <th>T.Documento</th> <th>N.Documento</th> <th>Residencia</th> <th>Estado</th> <th class="all">Acciones</th> </thead> <tbody> {% for item in obj %} <tr> <td>{{ item.nombre_completo }}</td> <td>{{ item.genero }}</td> <td>{{ item.t_doc }}</td> <td>{{ item.numero_doc }}</td> <td>{{ item.residencia }}</td> <td>{{ item.estado|yesno:"Activo, Inactivo" }}</td> <td> <a href="{% url 'res:residentes_edit' item.id %}" class="btn btn-warning btn-circle" role="button"><i class="far fa-edit"></i></a> <a href="#" class="btn btn-danger btn-circle" role="button"><i class="far fa-trash-alt"></i></a> </td> </tr> {% endfor %} </tbody> </table> {% endif %} </div> views.py class ResidenteEdit(LoginRequiredMixin, generic.UpdateView): model = Residente template_name = "res/residente_form.html" context_object_name = "obj" form_class = ResidenteForm success_url = reverse_lazy("res:residentes_list") login_url = 'bases:login' success_message = "Residente Editado Satisfactoriamente" urls.py path('residentes/edit/<int:pk>', ResidenteEdit.as_view(), name='residentes_edit'), models.py class Residente(models.Model): nombre_completo = models.CharField( max_length=100, unique=True) genero = models.ForeignKey(Genero, on_delete=models.CASCADE) t_doc = models.ForeignKey(Tdocs, on_delete=models.CASCADE) numero_doc = models.CharField(max_length=100) residencia = models.ForeignKey(Predio, on_delete=models.CASCADE) estado = models.BooleanField(default=True) Thanks for help -
How to convert FileField query object into bytes in Django?
In this Django project "root" is the main project and "crypt" is the app. What I'm trying to do is, take a user input (file) and then encrypt it. User input is submitted through a form. The form is working just fine and also storing the file inputs. Here is models.py FUNCTION_CHOICE = ( ('ENCRYPT', 'Encrypt'), ('DECRYPT', 'Decrypt'), ) class Cryptdb(models.Model): function = CharField(max_length=7, choices=FUNCTION_CHOICE, default='Encrypt') userinputfile = FileField(upload_to='inputs/') key = CharField(max_length=100, null=True) encryptedfile = FileField(upload_to='encrypted/', null=True) forms.py class InputForm(forms.ModelForm): class Meta: model = Cryptdb fields = ('function', 'type', 'userinputfile') views.py def upload_file(request): if request.method == 'POST': save_the_form = InputForm(request.POST, request.FILES) if save_the_form.is_valid(): save_the_form.save() return HttpResponseRedirect('/success/url') else: form = InputForm() return render(request, 'home.html', {'form': form}) class MainpageView(CreateView): model = Cryptdb form_class = InputForm success_url = 'download' template_name = 'home.html' class DownloadpageView(ListView): model = Cryptdb template_name = 'download.html' context_object_name = 'obj' def get(self, request): form = InputForm() thefile = Cryptdb.objects.order_by('-id')[:1].get() foo = thefile.userinputfile keyy = Fernet.generate_key() key_object = Fernet(keyy) enc = key_object.encrypt(foo) foo.encryptedfile = enc args = {'form': form, 'thefile': thefile} return render(request, self.template_name, args) Here, I used queryset get() method to take the object instead of queryset list and I'm using that object to separate the file and store it … -
Add a string before product name
In the following code, I would like to add a string called "ABC" before appending the product name table_po= set() for tr in orders: table_po.add(str(tr.product)) table_data.append(table_po) After execution, it could be like ABC = Cat where Cat is the {tr.product} value -
content security policy blocking inline execution
I am working on a project in Django, where I am using a javascript from an external payment provider. Upon calling their script, they will insert a payment form embedded in my page. The documentation on how to integrate with their service is found here. Specifically I am following step 3 and 4. A snippet of my html is as below. Upon calling my javascript the payment form from checkout.js will be rendered as an iframe in the checkout-container-div element <div id="checkout-container-div"> </div> <script src="https://test.checkout.dibspayment.eu/v1/checkout.js?v=1"></script> In my javascript, I first call my backend to get the paymentId. Then using the obtained paymentId, I am calling the external checkout.js with const checkout = new Dibs.Checkout(checkoutOptions); in order to render the payment form document.getElementById("paymentButton").addEventListener("click", function() { //Collect all the fields value and send it to the server console.log("pay button clicked") $.ajax({ url : "localDeliveryPayment", type : "get", success: function(response) { if (response['paymentIdCreation'] == true) { console.log(response); const checkoutOptions = { checkoutKey: response['checkoutKey'], // Replace! paymentId: response['paymentId'], containerId: "checkout-container-div", }; const checkout = new Dibs.Checkout(checkoutOptions); checkout.on('payment-completed', function (response) { window.location = 'completed.html'; }); } } }) }) From Google Chrome's console I get the following error related to test.checkout.dibspayment.eu/:1 Refused to execute inline … -
What is the user of sentinel method in Django?
I have seen sentinel methods being used while setting foreign relationship to users, what exactly is the use of these methods? -
Django load huge data to drop down list (select) quicker?
I’m new to django, I have a application with search + drop down field where data load from database which contains 5000+ records, to load data it is taking 30-40 sec, this is not I expected. Is there a better way to load data faster? Any idea/thoughts/example appreciated. -
Is there a way to use Next.js API Routes to Authenticate Django Rest Framework backend?
I'm using DRF as a backend to Next.js frontend. I followed this very fine tutorial to set up authentication, but I read I should use Next.js API Routes as proxy to the DRF API Routes and I can do that on any route other than the authentication one because I must send the X-CSRFToken and credentials: "include" in the request headers. Currently I'm getting the CSRF Token on page load with useEffect: useEffect(()=> { fetch("http://localhost:8000/api-auth/csrf",{ credentials: "include" }) .then( res => setCsrf(res.headers.get("X-CSRFToken"))) .catch( err => console.error(err)) },[]) Im using a direct route to DRF API "http://localhost:8000/api-auth/csrf" instead of a Next.js API like "/api-auth/csrf". The same happens with the handleLogin function: const handleLogin = async (event) => { event.preventDefault(); fetch("http://localhost:8000/api-auth/login/", { method: "POST", headers: { "Content-Type": "application/json", "X-CSRFToken": csrf }, credentials: "include", body: JSON.stringify(formValues), }) .then(() => Router.push("/profile")) }; It is working like this, but I can't set credentials using Next.js API Routes. Even using the same pattern it doesn't work. I think I'm missing some fundamental concept here and I looked it up but couldn't find. If anyone can help I'd appreciate :)