Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django redirect does not work
I wanted to have function that every time get the request and check that user is login and then return user object if user is login otherwise redirect to login , so this is what I tried to do def is_login(request): userID = request.session.get('mainSession', 0) next = resolve(request.path_info).url_name print(1) if userID != 0: print(2) user = msignup.objects.filter(id=userID).first() return user print(3) return HttpResponseRedirect(reverse('login') + "?next= {}".format(next)) I tried to test this function with below view when user is loged out and request has no mainSession : def email_activation(request): user = is_login(request) print(4) if req.method == 'GET': print(5) email = user.email return render(request, 'account/emailActivation.html',{'email': email}) return redirect('login') and in response I got this : 'HttpResponseRedirect' object has no attribute 'email' and the response for prints that I had made is : 1 3 4 5 why after 3 redirect does not happens ?what am I doing wrong? -
Permissions don't apply to users in extended group in Django
I have custom user model and extended group model. When I go to admin panel and set permissions in my extended group then it doesn't have any effect on users who are in that group. I checked database and everything looked correct. It works only when I put user to non-extended Group model even tho extended class should share permissions with parent one. settings.py AUTH_USER_MODEL = 'web.TurboM_User' models.py from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import Group class TurboM_Group(Group): TurboM_Users = models.ManyToManyField('TurboM_User', blank=True, verbose_name="Users") is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) class Meta: verbose_name = "Group" verbose_name_plural = "Groups" class TurboM_User(AbstractUser): TurboM_Groups = models.ManyToManyField('TurboM_Group', through=TurboM_Group.TurboM_Users.through, blank=True, verbose_name="Groups") ADgroups = models.TextField(null=True, blank=True) domain = models.ForeignKey(Domain, null=True, blank=True) class Meta: verbose_name = "User" verbose_name_plural = "Users" admin.py class TurboM_GroupAdmin(admin.ModelAdmin): model = TurboM_Group fieldsets = [ (None, {'fields': ['name','is_staff', 'is_active',]}), (_('Permissions'), {'fields': ['TurboM_Users', 'permissions',]}), ] filter_horizontal = ('TurboM_Users', 'permissions',) admin.site.unregister(Group) admin.site.register(TurboM_Group,TurboM_GroupAdmin) -
Django template tags + using fabric.js
I've set up a reasonable Django site to test and play around with, but I'm having an awful time including fabric.js Ultimately I want to use fabric.js to take small images from a database and display them on a canvas, but I digress. The issue I'm having is that I cannot use a local png image within my html using fabric.js - I mean, fabric is included (because I can do very basic tricks with fabric, like create rectangles) However, the tutorial isn't clear on including local images. Here's my awful code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>This is using render</title> {% load staticfiles %} <script scr="{% static "js/fabric.js" %}" type="text/javascript"></script> </head> <body> <script type="text/javascript"> var canvas = new fabric.Canvas('c'); canvas.setHeight(480); canvas.setWidth(640); var imgElement = fabric.Image.fromURL('../static/images/pitch.png', function(oImg) { canvas.add(oImg); }); var imgInstance = new fabric.Image(imgElement, { left: 100, top: 100, angle: 90, opacity: 0.85 }); canvas.add(imgInstance); </script> </body> </html> Probably doing something noobish, so apologies in advance. -
Image Downsizing and Upsizing in React Native like Instagram
Instagram changes image pixels when user posts it. I think Instagram resizes image on the Front-End. When we uploads image, how can we downsize or upsize the image in React Native? For instance (I've done little a bit of research), 1. 192 x 263 image -> 320 x 400 fixed image (upsized by width 320) 2. 250 x 220 image -> 320 x 282 fixed image 3. 183 x 276 image -> 320 x 400 fixed image 4. 2048 x 1152 image -> 1080 x 608 fixed image (downsized by width 1080) 5. 683 x 1024 image -> 683 x 853 fixed image (downsized by width 683) if the width of the image is greater than 1080 or lower than 320, it resizes the image. About my app, I'm using Django REST framework for Backend and React Native for Front-End. I'm sending image using http gzip compression. If I'm not wrong, apps downsize or upsize image from Front-End and send it to Backend. I think this way is the most efficient. -
docker-compose django failed to connect to mysql instance
I'm having a hard-time to make django to communicate with mysql instance which runs on another container. I'm using docker-compose to set the services up. docker-compose.yaml version: '2' services: nginx: build: ./nginx container_name: ng01 ports: - "80:80" depends_on: - api api: build: ./api container_name: dg01 restart: always command: bash -c "python manage.py makemigrations && python manage.py migrate && gunicorn s2s_api.wsgi:application -b localhost:8000" depends_on: - db ports: - "8000:8000" tty: true links: - db:mysql db: image: mysql container_name: db01 command: mysqld --user=root --verbose ports: - "3306:3306" restart: always environment: MYSQL_DATABASE: "demo" MYSQL_USER: "root" MYSQL_PASSWORD: "avi" MYSQL_ROOT_PASSWORD: "avi" MYSQL_ALLOW_EMPTY_PASSWORD: "yes" DB_PORT: 3306 DB_HOST: db When i try to make the services up through docker-compose up command, it shows, it always shows like django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on '127.0.0.1' (111)"). But running ping db, curl db:3306 inside api container works. It properly sends the ack message as well as the mysql version. I have also tried this https://stackoverflow.com/a/42703132/3297613 method. It prints starting daemon ... but failed to execute the next step. -
gunicorn for chat bot
I have a chat bot written in python django and deployed with gunicorn. I started 12 workers on cpu with 2 cores. More than 12 I do not run, because the documentation is not recommended, but my cpu is loaded 7 percent maximum. Why I can not run 20 processes and more? Maybe I need run worker with multiple threads? I tried, but bot send many responce on one request. How can I start using all the resource of the processor? Maybe it's worth deploying the application to a different technology instead of gunicorn? Gunicorn i'm running so: nohup gunicorn --workers=12 --max-requests=5000 --bind 127.0.0.1:8000 exgirlbot.wsgi:application & Maybe i just need to set confugiratio? Thank you. -
Architectural design of an SQL & Document Database based Web Application
I am designing a web application with Django as the backend. Overview of the system is as follows Data is collected from user related to different entities. Example : Plant, Project, Machine, Test, etc. Configuration Blocks (consolidated, fully self contained, dated & versioned JSON files) are created by user by selecting different instances of above entities into a package. The config block is sent to an automated API server, which generates an API for the said block on the fly. I am trying to model the database structure the step 1. Known details Different classes of entities. Ex. Plant, Project, Machine, etc are known before hand and are fixed. Everything else is unknown. I don't know the data in the entities, the links between them, etc. I plan to user Postgres for a searchable relational data and a document database, CouchDB to handle the unknown data schema part. Envisaged Architecture I plan to have template tables for different entities, in a Postgres database, where, the administrator defines a set of templates for data required to be filled by the user. The template is a JSON document, with a protocol for defining different fields the user will fill out. My UI … -
Using For-Variables for Django Model coloumn
Dunno if its possible. Hopefully u guys knows what I try to do. I wanna do the model changes in a FOR loop cause the keys of the values have always the same name as the model coloums. My currently code: sites = DataModel.objects.all() for site in sites: d = self.getDataBySoup(soup) site.title = d['title'] site.text = d['text'] site.facebook = d['facebook'] site.twitter = d['twitter'] site.save() As you can see, the keys are always the same as the django coloumns. So I thought its maybe possible to do it with less code. What I tried (But not working): sites = DataModel.objects.all() for site in sites: d = self.getDataBySoup(soup) for key, value in d.items(): site.key = value site.save() I use Python 3.6 -
Search string in database with django. icontains and iexact lookups not fulfill my requirements
I have products database in Django. A Product name Eg-(ABCD-E34F). If user search 'abcd34'. How will i get the object of ABCD-E34F product. -
save slug for product and company as soon as they are saved
I have a product and company model where slug is included for better detail view in the url. I have used pre_save signal to save the slug as soon as the product and company are saved to the database. The code I have written is not saving the slug so when I post product form I get an error regarding slug Here is my code class Product(models.Model): name = models.CharField(max_length=200, unique=True, blank=False, null=False) company = models.ForeignKey('Company', related_name='products', blank=True, null=True, on_delete=models.SET_NULL) website = models.URLField(unique=True) slug = models.SlugField(unique=True) class Meta: verbose_name= 'Product' verbose_name_plural= 'Products' def __str__(self): return self.name def hits(self): self.hits += 1 self.save(update_fields=['hits']) class Company(models.Model): name = models.CharField(max_length=200, unique=True, blank=False, null=False) slug = models.SlugField(unique=True) description = models.CharField(max_length=400) editor = models.ForeignKey(User, related_name='company') # product = models.ForeignKey(Product, related_name='company') def get_absolute_url(self): return reverse("products:view-company", kwargs={"slug": self.slug}) def create_slug(instance, new_slug=None): slug = slugify(instance.name) if new_slug is not None: slug = new_slug qs = Company.objects.filter(slug=slug).order_by('-id') if qs.exists(): new_slug = "%s-%S" %(slug, qs.first().id) return create_slug(instance, slug=new_slug) return slug def pre_save_slug_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = create_slug(instance) from django.db.models.signals import pre_save pre_save.connect(pre_save_slug_receiver, sender=Company) def create_slug(instance, new_slug=None): slug = slugify(instance.name) if new_slug is not None: slug = new_slug qs = Product.objects.filter(slug=slug).order_by('-id') if qs.exists(): new_slug = "%s-%S" %(slug, … -
How to display comments and it's replies in django templates?
I want to display comment and it's replies in the template. But there is an issue, every reply may have some other replies. The below snippet is my Comment and CommentReply model: class Comment(models.Model): author = models.ForeignKey(Profile, related_name="c_sender", on_delete=models.CASCADE, unique=False) comment = models.CharField(max_length=500, unique=False) created_date = models.DateTimeField(auto_now_add=True) edited_date = models.DateTimeField(blank=True, null=True) def __str__(self): return self.comment @property def replys(self): return CommentReply.objects.filter(comment_id=self) class CommentReply(models.Model): comment_id = models.ForeignKey(Comment, related_name='sender', on_delete=models.CASCADE) reply_id = models.ForeignKey(Comment, related_name='reply', on_delete=models.CASCADE) My question is how to display comments and it's replies under it, and every reply may have some other replyies that I want to display them too. -
How can i call a html template without any view in django
I want to call index.html template to particular URL without calling any view. is it possible in django? -
Error in installing My-SQL Python in my Django Project
I am new to django ,and i having this error installing My-SQL Python in my django environment . I tried most of the answers posted earlier . When i do 'pip install MySQL-python' on cmd i am getting this error error: Microsoft Visual C++ 10.0 is required. Get it with "Microsoft Windows SDK 7.1": www.microsoft.com/download/details.aspx?id=8279 , but i have already installed windows sdk 7.1 and Microsoft Visual C++ x64Redistributable 10.0 from the link , Kindly help me out here . This is what i am getting (env) C:\Users\HP\prj\env\plm>pip install MySQL-python Collecting MySQL-python Using cached MySQL-python-1.2.5.zip Building wheels for collected packages: MySQL-python Running setup.py bdist_wheel for MySQL-python ... error Complete output from command c:\users\hp\prj\env\scripts\python.exe -u -c "im ort setuptools, tokenize;__file__='C:\\Users\\HP\\AppData\\Local\\Temp\\pip-bui d-n_ns79ya\\MySQL-python\\setup.py';f=getattr(tokenize, 'open', open)(__file__) code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exe '))" bdist_wheel -d C:\Users\HP\AppData\Local\Temp\tmpbu_gvnsapip-wheel- --pyth n-tag cp34: running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-3.4 copying _mysql_exceptions.py -> build\lib.win-amd64-3.4 creating build\lib.win-amd64-3.4\MySQLdb copying MySQLdb\__init__.py -> build\lib.win-amd64-3.4\MySQLdb copying MySQLdb\converters.py -> build\lib.win-amd64-3.4\MySQLdb copying MySQLdb\connections.py -> build\lib.win-amd64-3.4\MySQLdb copying MySQLdb\cursors.py -> build\lib.win-amd64-3.4\MySQLdb copying MySQLdb\release.py -> build\lib.win-amd64-3.4\MySQLdb copying MySQLdb\times.py -> build\lib.win-amd64-3.4\MySQLdb creating build\lib.win-amd64-3.4\MySQLdb\constants copying MySQLdb\constants\__init__.py -> build\lib.win-amd64-3.4\MySQLdb\cons ants copying MySQLdb\constants\CR.py -> build\lib.win-amd64-3.4\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win-amd64-3.4\MySQLdb\co stants copying MySQLdb\constants\ER.py -> build\lib.win-amd64-3.4\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win-amd64-3.4\MySQLdb\constant copying MySQLdb\constants\REFRESH.py -> … -
How to access request.FILES in my views?
Trying to upload an image to a model image field with AJAX. Here's my code: js $('input#id_banner_image').on('change', function(e) { $.ajax({ type: 'POST', url: '/change_banner_image/', data: { image: URL.createObjectURL(e.target.files[0]), csrfmiddlewaretoken: $("input[name='csrfmiddlewaretoken']").val() } }) }); views def change_banner_image(request): if request.is_ajax(): print('AJAX') #prints image = request.FILES['id_banner_image'].name #this is wrong profile = get_object_or_404(Profile, user=request.user) profile.image = image profile.save() return HttpResponse() How do I correctly grab the image in my views? I know that's the bit that's wrong. -
Django Status 200 but 'Failed to Load Response Data" On Certain Image Uploads
I'm making an ajax post request to the Python Django view below which always return a success json response. # views.py @csrf_exempt def success_response(request): """ Returns a http response with a JSON success state :param request: :return: """ return JsonResponse({'success': True}) In each ajax post request, i'm attaching an image file in enctype=multipart/form-data format. As you can see, here is an example request payload: ------WebKitFormBoundarymYCuLcqA6kEkqMA7 Content-Disposition: form-data; name="file"; filename="willprobablycrash.png" Content-Type: image/png ------WebKitFormBoundarymYCuLcqA6kEkqMA7-- How is it possible that images below a certain image dimension (below 960px x 1141px) return the intended response {"success": true} while images above the said dimension return Failed to Load Response Data? In both success and error cases, the status_code in the response is 200. -
After parsing JSON with Volley library i don't have any error but result is not displaying
I'm trying to access json data via Android using Volley Library,and for the backend of the webserver i've used python.Here is my server side code: def showAndroid(request): users=User.objects.all() data = serializers.serialize('json', users, fields=('nom', 'prenom', 'postnom', 'adresse','tel','mail')) return HttpResponse(data, content_type='application/json') When i access the URL i obtain the folllowing result: See also my android code: package com.example.lislis.mesexercices; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class UserJson extends AppCompatActivity { EditText nom,prenom,postnom,email; Button ajouter,voir; TextView list; RequestQueue requestQueue; String insertUrl="http://192.168.1.14:8000/webservices/insert-users/"; String showUrl="http://192.168.1.14:8000/webservices/afficher-users/"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.user_json); nom=(EditText)findViewById(R.id.nom); prenom=(EditText)findViewById(R.id.prenom); postnom=(EditText)findViewById(R.id.postnom); email=(EditText)findViewById(R.id.email); ajouter=(Button) findViewById(R.id.ajouter_user); voir=(Button)findViewById(R.id.afficher_users); list=(TextView)findViewById(R.id.list_users); requestQueue= Volley.newRequestQueue(this); voir.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.GET, showUrl, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { JSONArray users=response.getJSONArray("data"); for(int i=0;i<users.length();i++) { JSONObject user=users.getJSONObject(i); String fname=user.getString("prenom"); String lname=user.getString("nom"); String mname=user.getString("postnom"); String mail=user.getString("mail"); list.append(fname+" "+lname+" "+mname+" "+mail+"\n"); System.out.println("Tototo\n"+fname+" "+lname+" "+mname+" "+mail+"\n"); } list.append("===\n="); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }); requestQueue.add(jsonObjectRequest); } }); } } But when … -
deepcopy Django request
What I want to do is to make a copy of the Django request, and change the sensitive information within it, and then log it in a file. So I make a middleware to do that. from django.utils.deprecation import MiddlewareMixin import copy class RecordMiddleware(MiddlewareMixin): """ record the request,but hide the sensitive info """ def process_request(self, request): # in this case, the original request is changed dic = request.__dict__.copy() # in this case, TypeError: can't pickle uwsgi._Input objects # dic = copy.deepcopy(request.__dict__) hide_auth_token(dic) hide_auth_token(dic.get('META', None)) # here you can log it in a file print('middleware, request is {}'.format(dic)) print('original is {}'.format(request.__dict__)) def hide_auth_token(dic): if not isinstance(dic, dict): return if 'HTTP_AUTHORIZATION' in dic: ha = dic['HTTP_AUTHORIZATION'] if len(ha) > 10: dic['HTTP_AUTHORIZATION'] = ha[0:len(ha) - 10] + 'XXX-XXX-XX' The problem is shallow copy will not keep the original request, while deepcopy will raise an error. Does anyone has experience for this problem? -
django static file directory
in Django template file, I can use <link href="/static/css/bootstrap.min.css" rel="stylesheet"> to include my css file in /static/css I have such a javascript which load background img, $.backstretch([ "/static/img/backgrounds/a.jpg" , "/static/img/backgrounds/b.jpg" , "/static/img/backgrounds/c.jpg" ], {duration: 3000, fade: 750}); but this script can not find the img path. So I wonder what is the root path for javascript regarding my web -
Clumsy repeat-myself django permission check
I have a class based view for a Problem object. I only want the author of the Problem to be able to view the Problem cbv. Other logged-in users should be redirected to a forbidden page. I achieve this by checking the ownership in the get_template_name() method. But if I want to pass in context to the forbidden template, I also need to check ownership in the get_context_data() and make the appropriate context. This works, but it seems like way too much semi-repetitive code, and just very non-Pythonic/Djangonic. Can any suggest a nicer way to do this? It's an issue for many ClassBasedViews I created. I have both "Problem" objects and "Board" objects that I want to ensure the logged-in user == the author of the Problem or Board object. Almost seems like I could have some kind of Mixin or something. Anyway, here is an example of my approach: class ProblemStudyView(UpdateView): model = Problem fields = "__all__" def get_template_names(self): problem = self.get_object() if problem.author != self.request.user: # User should not see this entry context = {'original_author': problem.author, 'request_user': self.request.user} template_name = "board/forbidden.html" return template_name else: # This user is OK template_name = "board/study.html" return template_name def get_context_data(self, **kwargs): context … -
Django+Postgres: Table Lock "Allow only 1 http request access the rows"
I want to allow only the first server that selects the first 100 rows to modify from status_log=0 to status_log=2 on the database. And if 10 other servers get the same query wont be able to make updates. Currently I've 10 servers that pull data from a main server but its a whole mess because all of them get the same data and even if I use django: select_for_update() it's worthless. It's like all these servers get the data and don't care if the earliest got it with status = 0 the still make the update and change the status for all the servers. I want to lock the query make the update and prevent others from touching those rows ever again if the status_log != 0 This is my Query. try: logs = sms_log.objects.filter(status_log__in=[1], direction=2, server=0, retry=0)[0:100] if len(logs) != 0: for items in logs: send_sms.apply_async(args=[items.id, items.to_phone, items.body, items.account.auth_token, "4"], queue="high") except sms_log.DoesNotExist: return -
webpack and django on Heroku: bundling before collectstatic
I am building a django+react app on Heroku, using django-npm which automatically installs all modules from package.json to node-modules dir and then copies everything to staticfiles/ during python manage.py collectstatic (which is triggered by Heroku during deploy). However, for this configuration to work I need to pre-bundle my React app before deployment and put it into my static folder along with all the CSS, fonts, etc. to be picked up by collectstatic later. But I don't want to pollute my git diffs with new bundle versions. So, is there a way to make webpack create a bundle during deployment? I know there is a release command on Heroku where I can put my npm run build. But the problem is it only fires AFTER collectstatic, so my bundle will not be picked up by it. -
IndentationError: expected an indented block (Django and Python)
I'm currently working with Django on a proyect, when I'm about to import the models en the file models.py into the database this error shows up: File "/home/hansen/Escritorio/SIDECO/sideco/models.py", line 31 class Empresa(models.Model): ^ IndentationError: expected an indented block* The code is the following: from django.db import models class Sistema(models.Model): def lista_empresa(): pass def lista_desempleado(): pass def dar_de_alta_desempleado(): pass def dar_de_alta_empresa(): pass def enviar_informacion_desempleado(): pass def listado_desempleado(): pass def almacenamiento_historico(): pass class Persona(models.Model): DNI = models.CharField(max_length=10) tipo_de_trabajo = models.TextField() fecha_de_nacimiento = models.TextField() class Empleado('Persona'): empresa = models.ForeignKey('Empresa') class Desempleado('Persona'): class Empresa(models.Model): cuil = models.CharField(max_length=12) razon_social = models.TextField() rubro = models.TextField() def contratar_desempleado(): pass class OfertaLaboral(models.Model): empresa = models.ForeignKey('Empresa') tipo_de_trabajo_solicitado = models.TextField() -
VueJS props are undefined in component
I am trying to integrate VueJS with my frontend for my Django applications. I have the following Vue code in a javascript file: window.onload = function() { Vue.component('discuss-post', { props: ['post'], template: `<div class="card"> <div class="grid-x margin-x"> <div class="cell small-4"> <img class="avatar-img" :src="post.by.profile.img_url"> <p style="font-family: Abel;font-size: 24px">{{ post.by }}</p> </<div> </div> <div class="grid-x margin-x"> <div class="cell small-4"> <p style="font-family: Abel;font-size: 18px">{{ post.content }}</p> </div> </div> </div>` }) var postDiv = new Vue({ el: "#post-div" }) } And the following code in an HTML file: <div class="card-section"> {% for feed in feeds %} {% for post in feed %} <div id="post-div"> <discuss-post post="{{ post }}"></discuss-post> </div> {% endfor %} {% endfor %} </div> However, when I load my page I get these errors in my console: What in my code could be causing these errors to be raised? -
Why does opening the Chrome Console solve long wait issue?
My colleagues & I are building an Angular 4 app with a Django back-end. Periodically we have to wait a long time for a request to go out from the UI to the web-server. Yet if one opens up the Chrome Console then this seems to effect the request to immediately go out and provide the desired response. We're trying to get a handle on what's going on. Any ideas? Robert -
Django/Postgres - No function matches the given name and argument types
I'm trying to create a search system in my Django and Postgresql project but I keep running into an error when I try to make a query. Whenever I try these commands in the shell: vector = SearchVector('title','tags') query = SearchQuery('book') | SearchQuery('harry') My_Library.objects.annotate(similarity=TrigramSimilarity(vector,test),).filter(similarity__gt=0.3).order_by('-similarity') I get the error: "No function matches the given name and argument types. You might need to add explicit type casts." I've been testing other options for a while, and the only way I can successfully pass a search query without an error is by using two strings in the place of query and vector. My_Library.objects.annotate(similarity=TrigramSimilarity('title','my search query'),).filter(similarity__gt=0.3).order_by('-similarity') This will successfully pass my search with no error. Why am I getting this error, and how can I fix it? I've been basing my code off of this Full Text Search documentation