Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Combining DataTables with Django Ajax Requests
I have a Django project that has a model Analytic that lists analytics. I followed this guide: https://simpleisbetterthancomplex.com/tutorial/2016/11/15/how-to-implement-a-crud-using-ajax-and-json.html to implement Ajax calls, and it worked perfectly. Then, I implemented DataTables to hold the data instead of a regular Bootstrap table. On the surface this worked well, but now the Ajax calls don't work. Instead, saving the create/update forms and deleting a row requires a page refresh for changes to take effect. Here is my JS: $(function () { /* Functions */ var loadForm = function () { var btn = $(this); $.ajax({ url: btn.attr("data-url"), type: 'get', dataType: 'json', beforeSend: function () { $("#modal-analytic").modal("show"); }, success: function (data) { $("#modal-analytic .modal-content").html(data.html_form); } }); }; var saveForm = function () { var form = $(this); $.ajax({ url: form.attr("action"), data: form.serialize(), type: form.attr("method"), dataType: 'json', success: function (data) { if (data.form_is_valid) { $("#analytic-table tbody").html(data.html_analytic_list); $("#modal-analytic").modal("hide"); } else { $("#modal-analytic .modal-content").html(data.html_form); } } }); return false; }; /* Binding */ // Create analytic $(".js-create-analytic").click(loadForm); $("#modal-analytic").on("submit", ".js-analytic-create-form", saveForm); // Update analytic $("#analytic-table").on("click", ".js-update-analytic", loadForm); $("#modal-analytic").on("submit", ".js-analytic-update-form", saveForm); // Delete analytic $("#analytic-table").on("click", ".js-delete-analytic", loadForm); $("#modal-analytic").on("submit", ".js-analytic-delete-form", saveForm); var table = $('#analytic-table').DataTable( { fixedHeader: true, language: { search: "", searchPlaceholder: "Table Search", lengthMenu: "Show _MENU_", }, dom: … -
How do we do signup email confirmation on Google App Engine?
What is the best way to implement signup email confirmation using django-allauth on Google App Engine flexible environment? This seems to be a glaring hole in Google App Engine documentation. Although, there are several links talking about email, none of the documentation gives a complete example that works for us. We've tried sending smtp.gmail.com with our GAE account administrator gmail address without success. This is our Django config: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'our_admin_account@gmail.com' EMAIL_PASSWORD = "'********" EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'our_admin_account@gmail.com' Even though we have 'our_admin_account@gmail.com' as authorized email sender and disabled captcha. However, this didn't do the trick for us. Also, we have purchased G-Suite because we thought that it would be easier to setup on GAE. We tried using a G-Suite email address to send without any success. This has been quite infuriating and a total waste of our time. We are thinking about moving over to Amazon cloud instead -- but would rather not take the time loss in switching if it could be avoided. We don't want to waste another couple of days trying the other third party email options on GAE--like SendGrid, MailChimp--without knowing whether or not … -
UnicodeDecodeError in Django Raw Query using bytes as parameter
For Django (python3) I am writing a unit test to ensure that a custom encryption routine can be decrypted by MySQL's native aes_decrypt function. start_value = 'A Simple starting test value.' enc_value = mysql_aes_encrypt(start_value, cipher=self.cipher) self.cursor.execute('SELECT aes_decrypt(%s, %s) FROM DUAL', (enc_value, self.test_key)) When executed, this raises the following exception: # -- snip -- File "/home/vagrant/virtualenv/members/lib/python3.6/site-packages/MySQLdb/cursors.py", line 187, in _do_get_result self.description = self._result and self._result.describe() or None UnicodeDecodeError: 'utf-8' codec can't decode byte 0x96 in position 13: invalid start byte When examining the source to execute it seems that after the query executes it attempts to describe the results and dies. I thought maybe I could pass in a column alias to the query as it was having trouble with the bytes there but that didn't work. SELECT aes_decrypt(%s, %s) as foo FROM DUAL In the end, I wrote a stub class that extends cursor and set the cursorclass of the default connection to be that stub. class NoDescriptionCursor(Cursor): """ Testing Cursor """ def _do_get_result(self): """ Our version doesn't try to get descriptions """ db = self._get_db() self._result = self._get_result() self.rowcount = db.affected_rows() self.rownumber = 0 self.description = None # Overridden to run the query. self.description_flags = None # Overridden to … -
How to change Django datetime field format in datepicker?
I have a model field called close_date models.py class Project(models.Model): close_date = models.DateTimeField(blank=True, null=True) In my forms, I don't do add any classes to display this because I will do it in my template using django-widget-tweaks. However, my forms look like this: forms.py class NewProjectForm (ModelForm): class Meta: model = Project fields = ['close_date', ...] templates {% load widget_tweaks %} <div class="form-group" id="close_date"> <label>{{project_form.close_date.label}}</label> <div class="input-group date"> <span class="input-group-addon"><i class="fa fa-calendar"></i></span> {% render_field project_form.close_date class="form-control" type="text" %} </div> </div> <script> $('#close_date .input-group.date').datepicker({ todayBtn: "linked", keyboardNavigation: false, forceParse: false, calendarWeeks: true, autoclose: true }); </script> All this works fine, I can display the form, save it to the database and even display data to the user, but when I want to edit the this object and I populate the form from my views, I see this in the datepicker input field: 2018-02-28 00:00:00 How can I change what is displayed there from 2018-02-28 00:00:00 to 02/28/2018? Is that on the django side of things or the JS side? -
How to connect a Docker container to PostgreSQL running on the localhost using a DATABASE_URL?
I'm following the Aptible Django Quickstart Tutorial which described how to create and deploy an app Aptible's PaaS. I would also like to be able to run the Docker container with the Django app locally and connect to a local PostgreSQL database, however, and it is unclear to me how to do this. The Dockerfile for the Django app is: FROM python:3.6 # System prerequisites RUN apt-get update \ && apt-get -y install build-essential libpq-dev \ && rm -rf /var/lib/apt/lists/* # If you require additional OS dependencies, install them here: # RUN apt-get update \ # && apt-get -y install imagemagick nodejs \ # && rm -rf /var/lib/apt/lists/* # Install Gunicorn. If Gunicorn is already present in your requirements.txt, # you don't need that (but if won't hurt). RUN pip install gunicorn ADD requirements.txt /app/ WORKDIR /app RUN pip install -r requirements.txt ADD . /app EXPOSE 8000 CMD ["gunicorn", "--access-logfile=-", "--error-logfile=-", "--bind=0.0.0.0:8000", "--workers=3", "mysite.wsgi"] where mysite is the name of the Django app. Its settings.py uses dj-database-url as follows: import dj_database_url DATABASES = {'default': dj_database_url.config()} In order to connect to a local instance of PostgreSQL, it would seem I should follow the Docker for Mac Solution on Allow docker container … -
Celery task to write file in subprocess
There is a celery task to call subprocess and in the subprocess script, I want to write some text in file (auth_path) each function in script done. The problem is, if I call python3 apt.py from shell, text written in the file. but when i call subprocess in task, progress works correctly, all functions works in apt.py but nothing written in aut_path. Why I cannot write some texts when I call script from subprocess. @task(name="dene") def dene(): cmd = ['timeout', '240', 'python3', "apt.py"] output = check_output(cmd) in apt.py there is a write func and calling it again and again. def write_out_auto(msg): with open(aut_path, 'a') as the_file: the_file.write(msg +'\n') write_out_auto("Finished the section 2") -
how to parse an image into api directly
This is how my program works: I'm parsing an image taken by my camera into an emotion detection API and then getting the result via the following html: {% extends "app/layout.html" %} {% block content %} <form action="{% url 'upload' %}" method="post" enctype="multipart/form-data" id="form1"> {% csrf_token %} <div > {% load staticfiles %} <input id="id_file" name="file" type="file" src="{% static 'app/content/image0000000.jpg' %}" width="100" height="30"/> <!--this DO NOT WORK --> </div> <button type="submit" >Submit</button> </form> {% endblock %} The relevant python files are as follow: from django.shortcuts import render from django.http import HttpRequest from django.template import RequestContext from datetime import datetime from .forms import UploadFileForm from projectoxford.Client import Client from projectoxford.Emotion import Emotion from tempfile import TemporaryFile from django.conf import settings from PIL import ImageDraw from PIL import Image import base64 def home(request): """Renders the home page.""" assert isinstance(request, HttpRequest) form = UploadFileForm() return render( request, 'app/index.html', context_instance = RequestContext(request,{'form':form}) ) def upload(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): file = request.FILES['file'] modified, happyscore = handle_uploaded_file(file) modified.seek(0) image = base64.b64encode(modified.read()) return render(request, 'app/result.html', {'image': image, 'ishappy':happyscore}) else: form = UploadFileForm() return render(request, 'app/index.html',{'form':form}) def handle_uploaded_file(file): client = Client.emotion(settings.OXFORD_KEY) recognizeResult = client.recognize({'stream': file}) im = Image.open(file) draw = ImageDraw.Draw(im) … -
Can't find virtualenv in path even though its there
I'm trying to set up Django. I have Python 3.6 installed, and I installed virtualenvwrapper using pip3. Here is what my bash profile looks like: # Get the aliases and functions if [ -f ~/.bashrc ]; then . ~/.bashrc fi export PATH="$PATH:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Frameworks/Python.framework/Versions/3.6/bin/virtualenv" export WORKON_HOME=$HOME/.virtualenvs export VIRTUALENVWRAPPER_PYTHON=/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 export PROJECT_HOME=$HOME/Devel source /Library/Frameworks/Python.framework/Versions/3.6/bin/virtualenvwrapper.sh Every time I run $ mkvirtualenv my_django_env I get ERROR: virtualenvwrapper could not find virtualenv in your path -
Not able to pass value from view to onclick in template
i'm not able append the callurl sending to template from view to onclick <button class="mdl-button mdl-js-button mdl-button--fab mdl-js-ripple-effect mdl-button--primary" onclick="location.href ='{% url 'home:{{callurl}}'%}'"> <i class="material-icons">add</i> </button> when i am passing the like above i'm getting error like Exception Value: Reverse for '{{callurl}}' not found. '{{callurl}}' is not a valid view function or pattern name. -
Django: trying to link to one model inside of other models ListView
I would like to get the Restaurant Id from the Restaurant model and use it for the href in the Lunchmenu listview. Don´t really know how to move forward from here. I have tried a for loop of the "restaurants_list" in the template but did not really understand how to get only one Id from the list. Is there any way to do this in the template? Should I change the View somehow? Models: class LunchMenu(models.Model): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) class Restaurant(models.Model): manager = models.ForeignKey(User, on_delete=models.CASCADE) restaurant_name = models.CharField(max_length=100) Listview: class LunchMenuListView(ListView): template_name = "lunchmenus/lunchmenu_home.html" model = LunchMenu def get_context_data(self, **kwargs): context = super(LunchMenuListView, self).get_context_data(**kwargs) context["restaurants_list"] = Restaurant.objects.all() return context Template: <div class="row"> {% for lunchmenu in lunchmenu_list %} <div class="col-lg-4 col-sm-6 portfolio-item"> <div class="card h-100"> <a href="/restaurants/{{restaurant.id}}"><img class="card-img-top" src="http://placehold.it/350x200" alt=""></a> <div class="card-body"> <h4 class="card-title"> <a href="#">{{lunchmenu.restaurant}}</a> </h4> <p class="card-text">{{lunchmenu.description | safe}}</p> </div> </div> </div> {% endfor %} </div> {% endblock %} -
Bug Update Django Formsets
I am trying to modify a sale in which I have this view: #Views.py class VentaUpdate(UpdateView): model = Venta template_name = 'venta/venta_form.html' form_class = VentaForm success_url = reverse_lazy('venta:ventas_listar') def get_context_data(self, **kwargs): data = super(VentaUpdate, self).get_context_data(**kwargs) if self.request.POST: data['detalleformset'] = DetalleFormSet(self.request.POST, instance=self.object) else: data['detalleformset'] = DetalleFormSet(instance=self.object) return data def form_valid(self, form): context = self.get_context_data() detalleformset = context['detalleformset'] with transaction.atomic(): self.object = form.save() if detalleformset.is_valid(): detalleformset.instance = self.object detalleformset.save() return super(VentaUpdate, self).form_valid(form) It works correctly in these cases: 1. Edit a product (if it was 1 soda, replace it with 1 water). 2. Add another product. But it does not work to want to eliminate a product from the sale. #forms.py class DetalleForm(forms.ModelForm): class Meta: model = DetalleVenta fields = [ 'producto', 'cantidad', 'subtotal', ] labels = { 'producto':'Producto', 'cantidad':'Cantidad', 'subtotal':'Subtotal', } widgets = { 'producto':forms.Select(attrs={'class':'form-control'}), 'cantidad':forms.NumberInput(attrs={'class':'form-control'}), 'subtotal':forms.NumberInput(attrs={'class':'form-control'}), } DetalleFormSet = inlineformset_factory(Venta, DetalleVenta, form=DetalleForm, extra=1) And so that the formset is dynamic, that is to be able to add more fields which I think the error is from the Javascript but I can not find the error {% extends 'base/base.html' %} {% load static %} {% block titulo%} Registrar venta {%endblock%} {% block contenido %} <form method="post"> {% csrf_token %} <div class="col-md-4 … -
del_user() missing 1 required positional argument: 'username' - Django
I'am looking a solution for my problem. I have a something like a my own admin panel, and I want to create a users managment system. The first I want to create a definition to delete the registered users. But when I try to execute this def, the system responde me a error : del_user() missing 1 required positional argument: 'username' My views.py is : from django.shortcuts import render from django.contrib.auth import authenticate, login from django.contrib.auth.models import User from .forms import LoginForm, UserRegistrationForm from django.http import HttpResponse from django.contrib.auth.decorators import login_required from django.contrib import messages ... def del_user(request, username): try: user = User.objects.get(username=username) user.delete(user) message.succes(request, 'Pomyślnie usunięto') except User.DoesNotExist: message.error(request, 'Użytkownik nie istnieje') return render(request, 'konto/settings.html') And I created a url to del_user.html page **urls.py** from django.urls import path from django.contrib.auth import views as auth_views from .views import dashboard, register,settings, del_user ... path('del_user/', del_user, name='del_user'), ... I don't understand this error why is not working. Anybody help? -
Django session dictionary KeyError when attempting to replace
I am dealing with a third-party authorization issue on the backend and encountering strange session store behavior. When I detect that the third part session authorization has become invalid, I re-authenticate and I am attempting to update the data in the session, which is not working. The problem is that after I delete the key from the session, I get a KeyError when I try to replace it once I have the updated information. def my_session_thing(invalidate=False): if invalidate: del self.request.session['my_session_dict'] self.request.session.modified = True my_session_dict = self.request.session.get('my_session_dict') if my_session_dict is not None: self.current_session_dict = my_session_dict return my_new_session_dict = { 'foo': 'bar' } # ** Why does this raise a KeyError when invalidate is True? ** self.request.session['my_session_dict'] = my_new_session_dict I am currently exploring alternatives to this strategy, but I found this behavior contradicts the dictionary-like behavior that the "How to use sessions" documentation describes, so it would be worth posting. -
Django Test: Model not updating
I am writing a test in django using django.test.TestCase. In setupTestData(cls), I create a User instance. test_user1 = User(username='testuser',email="a@b.com") test_user1.set_password('12345') test_user1._category = 'Male' test_user1.save() I have also set up a class in myapp.models where I have a post_save signal to add an object to a model MyModel. @receiver(post_save,sender=User) def update_mymodel(sender,instance,created,**kwargs): MyModel.objects.create(user=instance,category=category) The thing is, the receiver is called and the MyModel object should be created. But when I do MyModel.objects.all() in my test file, it shows empty. Why is the user instance not in the model? -
Django carts Error
Hi i have a problem in (add to cart button and remove from cart ) the default for me when i click add to cart the item should stores in carts object and redirect me to the cart_(home)page but it doesnot work it stay me in the existing page and dont add or remove product Here is my: carts/models.py class cart(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL , null=True, blank=True) products = models.ManyToManyField(product, blank=True) total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) subtotal = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) objects=CartManager() def __str__(self): return str(self.id) def __unicode__(self): return str(self.id) def m2m_changed_cart_receiver(sender, instance, action, *args, **kwargs): if action == 'post_add' or action == 'post_remove' or action == 'post_clear': products = instance.products.all() total = 0 for x in products: total += x.price if instance.subtotal != total: instance.subtotal = total instance.save() m2m_changed.connect(m2m_changed_cart_receiver, sender=cart.products.through) def pre_save_cart_receiver(sender, instance, *args, **kwargs): if instance.total>0: instance.total = instance.subtotal else: instance.total=0.00 pre_save.connect(pre_save_cart_receiver, sender=cart) and my carts/views.py def cart_home(request): cart_obj,new_obj=cart.objects.new_or_get(request) return render(request,"carts/home.html",{"cart":cart_obj}) def cart_update(request): product_id = request.POST.get('product_id') if product_id is not None: try: product_obj = product.objects.get(id=product_id) except Product.DoesNotExist: print("Show message to user, product is gone?") return redirect('cart:home') cart_obj, new_obj = Cart.objects.new_or_get(request) if product_obj in cart_obj.products.all(): cart_obj.products.remove(product_obj) else: cart_obj.products.add(product_obj) # cart_obj.products.add(product_id) return redirect('cart:home') -
Can't load static files in Django from views.py
I am trying to load static files(image files) in the web page by creating a list in views.py and put it in a list which has html elements and then passing to the jinja to render below home.html {% extends "Home/layout.html" %}. {% load staticfiles %} {% block content %} {% include 'Home/includes/header.html' %} <div class="container"> <div class="row"> {% for x in data %} {{ x|safe }} {% endfor %} </div> </div> {% endblock %} views.py from django.shortcuts import render from django.http import HttpResponse from .models import DB from utils.processDB import ProcessDB import os def index(request): ls = os.listdir() lsf = [] for x in ls: if os.path.isfile(x): lsf.append(x) data = ProcessDB(DB,lsf).dbProcess() #this will return a list of html which will have <img> tags like below #<img src="{% static "Home/img/image.png"%}"/> context = {'data': data} return render(request,'Home/home.html',context) when i inspect the rendered web page i see the image tag like this<img src="{% static "Home/img/image.png" %}" /> not what it should be <img src="Home/img/image.png"/> so y it is not loading static files when i m try the above instead loading this <img> tag If I pass the image list directly to jinja and change the views.py to pass a list of tuple(html,img) … -
Django App Running on Google App Engine Flexible environment cannot send mail
Can anyone tell me how to configure a Django app running on Google App Engine Flexible environment to send out emails? We are trying to send confirmation emails to users (we are using django-allauth) during account/signup. Our attempts to configure App Engine for send mail is not working. We have waisted four whole days on this supposedly simple matter. This is our current Django settings: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'my_email_address@gmail.com' EMAIL_PASSWORD = "'********" EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'my_email_address@gmail.com' The account 'my_email_addres@gmail.com' is actually the email that is used to setup the App Engine instance. On App Engine console, we configured 'my_email_address@gmail.com' as the authorized email sender. We verified that we can successfully log into both App Engine and Gmail with our 'my_email_address' and password we provided in the Django Settings file. However, when users attempt to signup, the sendmail step fails with the following error message (I edited the server url and email address edited below): SMTPSenderRefused at /accounts/signup/ (530, b'5.5.1 Authentication Required. Learn more at\n5.5.1 https://support.google.com/mail/?p=WantAuthError c62sm5621898ioj.28 - gsmtp', 'my_email_address@gmail.com') Request Method: POST Request URL: https://my_server_name.appspot.com/accounts/signup/ Any help? Thanks. -
Can't get request.user sub fields
I'm quite new to Django/Python and I'm having trouble to retrieve the user attributes, such as first_name. What am I missing? class principal(LoginRequiredMixin, TemplateView): template_name = 'appPortal/index.html' def get_context_data(self, **kwargs): usuario = self.request.user context = super().get_context_data(**kwargs) print (usuario) ### OK, returns the logged user print (usuario.first_name) ### Don't work, returns nothing print (usuario.get_short_name()) ### Don't work too ### The code continues, but the last two print() don't work Thanks, -
How to fix the Django-allauth settings.py contrib syntax error?
So following the current Django-allauth documentation, I keep getting this minor syntax error when I thought I followed the documentation to every last detail. Terminal error after running: ./manage.py migrate /settings.py", line 43 'django.contrib.auth', ^ SyntaxError: invalid syntax My settings.py file: Was I not supposed to keep the default apps above the allauth section? ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ... # The following apps are required: 'django.contrib.auth', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', # ... include the providers you want to enable: 'allauth.socialaccount.providers.amazon', 'allauth.socialaccount.providers.angellist', 'allauth.socialaccount.providers.asana', -
NOT NULL constraint failed: alpha_chat.message...i am getting this error. How to correct it?
enter image description here The image is the views.py file of the app. The data is not going into the database. How to correct the problem? -
Django rest framework list by BrowsableAPI and create with custom button
I'm kinda newbie to DRF and need some advice pls. I created some kind of time duration record for each day which is ok with inputing the duration manually, here is a model: from django.db import models from datetime import datetime, date class Record(models.Model): recordDate = models.DateField(blank=True, default=date.today) hourAchieved = models.IntegerField(blank=True, default=0) class Meta: ordering = ["recordDate"] def __str__(self): return "Achieved "+str(self.hourAchieved)+" hour(s)!" and works well with these APIviews: from rest_framework import generics from .models import Record from .serializers import ( recordListSerializer, recordUpdateSerializer ) class recordList(generics.ListCreateAPIView): queryset = Record.objects.all() serializer_class = recordListSerializer class recordUpdate(generics.RetrieveUpdateAPIView): queryset = Record.objects.all() serializer_class = recordUpdateSerializer Then, I want to improve input process by create a button to get 'start_time' and another button to get 'end_time' and calculate the time for me instead of me remember and input duration time(hours) myself. So, I found the 'TemplateHTMLRender' and decided to use it as: class recordList(generics.ListCreateAPIView): queryset = Record.objects.all() serializer_class = recordListSerializer renderer_classes = (TemplateHTMLRenderer,) template_name = 'myTemp.html' def get(self, request): records = self.get_queryset() serializer = recordListSerializer(records,many=True,context={'request': request}) return Response({'serializer': serializer, 'record':records}) and this is myTemp.html: {% load rest_framework %} <html> <body> <h1>Neew Era of REST</h1> <form action="{% url 'record:list' %}" method="POST"> {% csrf_token %} {% render_form serializer … -
django error using pagination and raw queryset
when I try to paginate my page it gives me error python - django error using pagination views: class StudentmessageListView(ListView, LoginRequiredMixin): login_url = '/login/' redirect_field_name = 'redirect_to' template_name = 'student_messagesall.html' context_object_name = 'messages_all' model = Message paginate_by = 3 def get_queryset(self): return Message.objects.raw('SELECT * FROM ertaapp_message where to_prof_id=%s ORDER BY create_date DESC',[self.request.user.id]) def get_context_data(self, **kwargs): context = super(StudentmessageListView, self).get_context_data(**kwargs) context['reps'] = ReplyMessage.objects.raw('SELECT * FROM ertaapp_replymessage') return context how can I solve this? -
Django - Search matches with all objects - even if they don't actually match
This is the model that has to be searched: class BlockQuote(models.Model): debate = models.ForeignKey(Debate, related_name='quotes') speaker = models.ForeignKey(Speaker, related_name='quotes') text = models.TextField() I have around a thousand instances on the database on my laptop (with around 50000 on the production server) I am creating a 'manage.py' function that will search through the database and returns all 'BlockQuote' objects whose textfield contains the keyword. I am doing this with the Django's (1.11) Postgres search options in order to use the 'rank' attribute, which sounds like something that would come in handy. I used the official Django fulltext-search documentation for the code below Yet when I run this code, it matches with all objects, regardless if BlockQuote.text actually contains the queryfield. def handle(self, *args, **options): vector = SearchVector('text') query = options['query'][0] search_query_object = SearchQuery.objects.create(query=query) set = BlockQuote.objects.annotate(rank=SearchRank(vector, query)).order_by('-rank') for result in set: match = QueryMatch.objects.create(quote=result, query=search_query) match.save() Does anyone have an idea of what I am doing wrong? -
How do I redirect errors like 404 or 500 to a custom error page in apache httpd?
I have created a Django project but I am using Apache as the webserver. Can anyone tell me how can I redirect an error code like 404 or 500 or 400 to a custom error html page instead of getting a standard error message on page in case an error was to occur ? -
Getting an error opening a file in Visual Studio 2017
I am trying to access a file in Visual Studio 2017 using the django framework but get the following error: How do I resolve it? Thanks