Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
After SSL Conf. returning "welcome to nginx!"
Nginx noob here, I did look through all previous posts but couldn't find anything specific to my situation. I'm trying to install a commercial SSL certificate on nginx. After configuring etc/nginx/sites-available/myapp with the following: server { listen 80; server_name example.come www.example.com; rewrite ^/(.*) https://example.com/$1 permanent; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/user/example.com; } location / { include proxy_params; proxy_pass http://unix:/home/djangodeploy/example.com/rex.sock; } } server { listen 443 ssl; server_name example.com www.example.come; ssl_certificate /home/user/example.com.chained.crt; ssl_certificate_key /home/user/example.com.key; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-GC$ ssl_prefer_server_ciphers on; } After checking syntax everything is fine. The https works well, however instead of serving the actual website it just returns "Welcome to nginx!" I've also configured the http directive in /etc/nginx/nginx.conf to include: http { ssl_certificate /home/user/example.com.chained.crt; ssl_certificate_key /home/user/example.com.key; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: $ ssl_prefer_server_ciphers on; I've heard gzip can cause problems, should I disable it? Any help would be greatly appreciated! -
Register form in class based views
How to write the below function based view in Class Based View(CreateView) function based view def register(request): registered = False if request.method == 'POST': user_form = UserForm(data = request.POST) profile_form = UserProfileInfoForm(data = request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user if 'profile_pic' in request.FILES: profile.profile_pic = request.FILES['profile_pic'] profile.save() registered = True else: print(user_form.errors,profile_form.errors) else: user_form = UserForm() profile_form = UserProfileInfoForm() return render(request,'app_one/registration.html',{'user_form':user_form,'profile_form':profile_form,'registered':registered }) Class based VIew class register(CreateView): model = userinfo, UserProfileInfo form_class = Userinfoform, UserProfileInfoForm -
celery doesn't run simple print
I have a helloworld type function for celery: from celery import Celery import time app = Celery('test_celery', broker= 'amqp://celeryuser:pass@ip:5672/celeryvhost', ) @app.task def add(x, y): time.sleep(2) print('calculating something aaewsome --------------------') return x + y if __name__ == '__main__': result = add.delay(4, 4) print( result.get() ) I run the command to run the task: celery -A test_celery worker --loglevel=info I get the output: [tasks] . test_celery.add [2018-07-17 00:17:40,668: INFO/MainProcess] Connected to amqp://celeryuser:**@myip:5672/celeryvhost [2018-07-17 00:17:40,679: INFO/MainProcess] mingle: searching for neighbors [2018-07-17 00:17:41,705: INFO/MainProcess] mingle: sync with 1 nodes [2018-07-17 00:17:41,706: INFO/MainProcess] mingle: sync complete [2018-07-17 00:17:41,725: INFO/MainProcess] celery@www.mysite.com ready. In the logs it shows: [2018-07-17 00:17:40,698: INFO/MainProcess] sync with celery@mysite.com But no output prints. what am I doing wrong? -
Django DRF - Restrict Access to List View via Permissions
I have a DRF ViewSet to which I am adding the CanViewAndEditStaff permission. I want only certain users (user.access_level < 2) to be able to view the list of staff. In my Permissions class, how can I differentiate between a call to the list view and to the get item view. Here is my permissions class: class CanViewAndEditStaff(permissions.BasePermission): def has_permission(self, request, view): # IF THIS IS A LIST VIEW, CHECK ACCESS LEVEL if ( request.user.access_level < 3 ): return True # ELSE, CONTINUE ON TO OBJECT PERMISSIONS def has_object_permissions(self,request,view,account): # admin can do anything if ( request.user.access_level == 1 ): return True # view/edit/delete else: # users can view their own account if account == request.user: return True elif account.access_level >= request.user.access_level: return True return False -
choose warning when no radio button button is selected
I have created a short questionnaire with radio buttons using django. When no option is selected I get a warning saying "Please select one of these options" which is good. What I don't like is the fact that an arrow points at the first radio button and also creates a square around it.There is a chance that a person completing the questionnaire might get confused and choose the first option because of the warning. My question is, is it possible to alter the warning box? Maybe shift it to the right and remove the arrow so it seems like it's a warning corresponding to the whole set of radio buttons and not just the first one. My forms.py is: class ValueForm(forms.ModelForm): SN=forms.CharField(label='Please input your Student No',widget=forms.TextInput(attrs={'placeholder':'Student No'})) choice1=choice2=choice3=choice4=choice5=choice6=choice7=choice8=choice9=choice10=choice11=choice12=choice13=choice14=choice15=choice16=choice17=forms.ChoiceField( choices=options, widget=RadioSelect(),) and for html I couldn't manage to make a loop so I did it individually for each question: <div class="col-md-8 col-md-push-2"> <label>{{Questions.Q1}}</label> </div> <div class="col-md-4"> {% for radio in form.choice1 %} <label class="radio-inline">{{radio}}</label> {% endfor %} </div> </div> where Questions is a dictionairy I created in views I have searched quite a bit but couldn't find a solution anywhere. Thanks in advance -
A python framework use RestAPI as backend
our product has a list of Rest APIs. GET products/ GET product/ PUT product/ Post Auth/ one of the customer asking us to build a web site, simply 4 pages list all products view a single product edit a single product Python is the required Programming language, to avoid code the simple website from scrach, I looked at the Django cms, flask cms, but most of them uses a Database to store the date. and I don't wanto pull the data from the rest service and save into the database every 2 mins. Swagger seems suits our needs. but it doesn't render html, tables and paginations question is anyone know a decent python framework can quickly create CURD website based on a list of rest api? -
BeautifulSoup is messing my image tags?
I'm working on a Django/Wagtail project. At some point I have to transform some HTML through a custom filter. For that I'm using BeautifulSoup. My code goes like this: def custom_filter(html): tree = bs(html, "html.parser") # Do stuff on the tree... return tree.prettify() This returns everything ok, expect for the images, that somehow are transformed into this: <embed alt="something" embedtype="image" format="normal" id="4771"> I have no idea why this is happening. Some clarifications: The stuff I do in the filter have nothing to do, as I tried commenting all out and the same happens I also tried changing the html.parser to lxml and get the same result The HTML is correct, the image tags are there. I am pretty sure the problem is in: tree = bs(html, "html.parser") Any idea of what could be causing this? -
Django Invalid block tag on line 5: 'endfor'
Running through a beginner Django tutorial and ran into this TemplateSyntaxError and I'm not quite sure what's causing it: Invalid block tag on line 5: 'endfor', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag? Here's the template in question: {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} -
Why can't I add static files in my django project when other static files are available in sources?
I'm trying to build a Django app for Heroku and have gone through the Polls tutorial and Heroku documentation When serving the basic Django-heroku app with heroku local or python3 manage.py runserver I can see that some static files are loaded just fine (/static/lang-logo.png specifically). But when I add my main.css and run python3 manage.py collectstatic the css file never shows up and the import in my index.html never loads. I've ready that whitenoise is best for serving static files in a django app so I'm using that and have set my settings.py based on many of the responses to similar questions here. Collectstatic appears to be working (see below). I've been banging my head against this for literally days and have gone through dozens of related questions here and nothing seems to cut it. I have reached the end of the internet and now you are my only hope. My code is below and I'll update the question if I realize I've missed something relevant. Settings.py """ Django settings for gettingstarted project. Generated by 'django-admin startproject' using Django 2.0. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ … -
Add a textbox next to a checkbox in django
I want to add text field next to each of the checkboxes. I am using django: 2.0.2-3. I have also installed muliselectfield using 'pip install django-multiselectfield'. My expected result on the frontend should look something like this Choice 1 [textfield] Choice 2 [textfield] Choice 3 [textfield] Choice 4 [textfield] Choice 5 [textfield] Also entered value should be stored in the database. For example if I select choice 1 and choice 2 and provide value as ABC and XYZ in the text boxes respectively, then my result stored in the database should be Choice 1: ABC, Choice 2:XYZ I will also share the code that I have written so far for better understanding: 1) models.py from __future__ import unicode_literals from django.db import models from bokeh.themes import default from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import AbstractUser from multiselectfield import MultiSelectField # Create your models here. class MyModel(models.Model): CHOICES = ( ('Yes', 'Yes'), ('No', 'No'), ) CHOICES_CHECKBOX = ( ('Choice 1', 'Choice 1'), ('Choice 2', 'Choice 2'), ('Choice 3', 'Choice 3'), ('Choice 4', 'Choice 4'), ('Choice 5', 'Choice 5'), ) field1 = models.CharField(max_length=3, choices=CHOICES, blank=False, null=False) field2 = models.CharField(max_length=3, choices=CHOICES, blank=False, null=False) field3 = models.CharField(max_length=240, … -
Idiomatic Django URL namespacing
TL;DR: My code works, but I really think there are a few code smells here. I'm currently working on a Django project and trying to set up all the URL endpoints for an API. I currently have all the URLs configured so there will only need to be one given primary key in the URLs to shorten them. For example, to get posts from a campaign of a client: List URL: Standard Nested: api/v1/clients/<client-pk>/campaigns/<campaign-pk>/posts/ My Own: api/v1/clients/campaigns/<campaign-pk>/posts/ Detail URL: Standard Nested: api/v1/clients/<client-pk>/campaigns/<campaign-pk>/posts/<post-pk>/ My Own: api/v1/clients/campaigns/posts/<post-pk>/ To do this I had to set up each pattern manually using a ton of paths and a lot of includes. To show my problem I'll be primarily focusing on the client, campaign, and post urls. server/clients/urls.py from .views import ClientViewset from django.urls import include, path from server.campaigns.urls import campaign_list_urlpatterns, campaign_detail_urlpatterns from server.posts.urls import post_list_urlpatterns, post_detail_urlpatterns urlpatterns = [ path('clients/<str:pk>/', include([ path('', client_detail, name='client-detail'), path('', include(campaign_list_urlpatterns)), path('', include(post_list_urlpatterns)) ])), path('clients/', include([ path('', client_list, name='client-list'), path('', include(campaign_detail_urlpatterns)), path('', include(post_detail_urlpatterns)) ])), ] server/campaigns/urls.py from .views import CampaignViewset from django.urls import include, path from server.posts.urls import post_list_urlpatterns, post_detail_urlpatterns campaign_list_urlpatterns = [ path('campaigns/', campaign_list, name='campaign-list'), path('campaigns/counts/', campaign_counts, name='campaign-counts') ] campaign_detail_urlpatterns = [ path('campaigns/<str:pk>/', include([ path('', campaign_detail, name='campaign-detail'), path('', include(post_list_urlpatterns)) … -
can't trigger task in celery even with successful connection
I have 2 ec2 instances. 1 has django celery and my app installed. 2 has RabbitMQ installed. I recently switched from a configuration with celery and redis which connected and worked. On the celery side, the logs look like they are connected with messages: Connected to amqp://celeryuser:**@myip/celeryvhost mingle: searching for neighbors mingle: all alone worker1@myhost ready. On the rabbit server, the connection also looks good with following log messages: > accepting AMQP connection <0.507.0> (internalip:45564 -> > anotherinternalip:5672) connection <0.507.0> (internalip:45564 -> > anotherinternalip:5672): user 'celeryuser' authenticated and granted > access to vhost 'celeryvhost' My celery.py connection info looks like: app = Celery('myapp', broker='amqp://celeryuser:mypass@mypublicip:5672/celeryvhost', backend='amqp://celeryuser:mypass@mypublicip:5672/celeryvhost', include=['social.tasks'] ) I initiate the task with: new_comment_notification.apply_async((1), queue='lopri', countdown=5) And: from mysite.celery import app from django.conf import settings from django.core.mail import send_mail @app.task def new_comment_notification(post_id): print(post_id) send_mail( 'New Comment', 'New Comment', settings.DEFAULT_FROM_EMAIL, ['my@email.com'], fail_silently=False, ) I monitor the logs and they don't move when I fire new_comment_notification. There is no indication that a task has been generated like I was able to see previously with the redis implementation. What am I doing wrong? -
Field from database showing up as the word "None" on frontend template but exist in the database
I've encountered the weirdest thing while developing a django-python web app. I have a field in my database that I want to display on the frontend. The field is a MultiSelectField and the list is populated from a list models.py # Other service areas other_areas = MultiSelectField(choices = SERVICE_AREAS, max_length=360, default=None, null=True) I have a form from where I select the other "service areas" and everything is submitted to my database correctly (in pgadmin I see the correct values) proof of ok values in DB Then on the frontend side in my template i have this code to present the data: index.html <div class="email" style="padding-top: 10px;">{{c.service_area}}- {{c.service_area.said}} , Other SAID's: {{c.other_areas}}</div> The weird part about this is that when the data actually show on my screen it turns up as the word "None" as many times is there are comma seperated values in that field. (If there are 3 service areas it will come up as None, None, None, if 4 service areas: None, None, None, None etc.) The rest of my data shows up correctly in the template. I'm kinda stumped and any ideas are welcome. example output for the image I added above: I have two values in … -
Combing multiple rows with same ForeignKey fields through query
Current Model.objects.all() creates: FK Column Column1 Column2 Column3 Zone 1 19 23 67 Zone 2 45 12 76 Zone 1 23 98 34 Zone 2 12 56 23 Expected Results: FK Column Column1 Column2 Column3 Zone 1 42 101 111 Zone 2 57 68 99 The FKs are automatically combined into a single row. which query should I use exactly for achieving this? -
Mark the label of required fields when using Django ModelForm
When using the Django admin forms to create a new or modify an existing object, the <label> tags of mandatory model fields are declared with class attribute required, e.g. <div> <label class="required" for="id_title">Title:</label> <input class="vTextField" id="id_title" maxlength="255" name="title" type="text" required /> <p class="help">A title for this tool</p> </div> However, this is not the case when using Django ModelForm. The HTML code produced by the following piece of code in a template file <table> {{ toolForm.as_table }} </table> comes without any class attributes for the <label> tag that would help to style appropriately labels of fields which are required: <table> <tr> <th> <label for="id_title">Title:</label> </th> <td> <input id="id_title" maxlength="255" name="title" type="text" required /> <br /><span class="helptext">A title for this tool</span> </td> </tr> </table> Any ideas how to mark the label of mandatory fields in an efficient way? -
How to extract the response from button click( front end ) process it in back end and send it in return?
I am implementing a web app using Django/Python. To test the app, I need to click on the button so that the response will be sent to the back end and it is processed in views.py. Once it is processed the output response should be sent back to the front end and display on web page. I have explored every where but really didn't find anything that matches my requirement. I am new to Django and fighting on this issue for the last two days. Can anybody help me regarding this or share some direction on how to implement this. Any help would be appreciated. Thank you so much. Ha button in my home.html <input type="button" class="button" onclick="myFunction(value)" value="A" id = "sendtodjango" > And my js script looks like this <script> function myFunction(value) { //send value to views.py } </script> My intention is to send the value (which is a string) parameter to def process(): function in views.py and get it processed. After processing the def process(): should send the updated string to my js script which is home.html (Once the string is retrieved it will be displayed to a textarea ()disabled) #django #connectingmodules -
Keeping Django subview open between page reloads
I am trying to develop a popup messaging window that I would like to be persistent between all pages on my platform. Right now, the sub template that contains the html for the popup is being included in all pages on the website. Is there a way for me to redirect to another page but keep the information on the popup open on the reload? -
Json Web Token, Axios 401-Unauthorized, Django, Vue.js
Every time i do a GET request to API from FrontEnd or POSTMAN to secured (isAuthenticated) content, i get 401 error(Unauthorized). I have two servers: 1.Django, django-rest-framework, with Json Web Token.(API) 2.Vue.js api endpoints: Registration (AllowAny): http://holykrava.hopto.org:8002/user-api/register/ Login (AllowAny): http://holykrava.hopto.org:8002/user-api/get-token/ List of Users (IsAuthenticated): http://holykrava.hopto.org:8002/user-api/user-list/ Vue-Part <script> //import {HTTP} from './http-common'; import axios from 'axios' export default { created() { //let tokenOld = localStorage.getItem('token') let token = this.$store.state.token axios.get( 'http://holykrava.hopto.org:8002/user-api/user-list/', {headers: { authorization: token }} ) .then(response => { console.log(response); }) .catch(error => { console.log(error); }) } } </script> Chrome Dev Tool (Network-Logs) General-Headers: Request URL: http://holykrava.hopto.org:8002/user-api/user-list/ Request Method: GET Status Code: 401 Unauthorized Remote Address: 188.190.62.145:8002 Referrer Policy: no-referrer-when-downgrade Request-Headers: Provisional headers are shown Accept: application/json, text/plain, */* Authorization: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VybmFtZSI6Im11dGFwdXRhIiwiZXhwIjoxNTMxODUxODg0LCJlbWFpbCI6IiIsIm9yaWdfaWF0IjoxNTMxNzY1NDg0fQ.LGji_eCDVIvGpQ9xDEO2QAISEEW9FpHVcwRl6Oz9cCM Origin: http://localhost:8080 Referer: http://localhost:8080/? Response-Headers: Access-Control-Allow-Origin: * Allow: GET, HEAD, OPTIONS Content-Length: 58 Content-Type: application/json Date: Mon, 16 Jul 2018 19:34:45 GMT Server: WSGIServer/0.2 CPython/3.6.4 Vary: Accept WWW-Authenticate: JWT realm="api" X-Frame-Options: SAMEORIGIN IT Works in Terminal like this: get token: curl -X POST -d "username=userusername&password=userpassword" http://holykrava.hopto.org:8002/user-api/get-token/ pass token: curl -H "Authorization: JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjo0MCwidXNlcm5hbWUiOiJ1c2VydXNlcm5hbWUiLCJleHAiOjE1MzE4NDAxNTAsImVtYWlsIjoiIiwib3JpZ19pYXQiOjE1MzE3NTM3NTB9.SoITxagpmbviEFl_Iy086Jy0KgAUNV0WW-a3wMM_Fos" http://holykrava.hopto.org:8002/user-api/user-list/ corsheaders.middleware.CorsMiddleware, installed CORS_ORIGIN_ALLOW_ALL = True Default Authintication Class: 'rest_framework_jwt.authentication.JSONWebTokenAuthentication' i spend two days trying to figure out whats wrong, but failed looking for some1 who … -
nginx supervisor django gunicorn 404
I have been trying to deploy a django application through nginx following this tutorial: karzynski and here is my set up: supervisor: [program:eviotapro] command = /home/effect/Desktop/workspace/Eviota/gunicorn_start.bash; user = root ; User to run as stdout_logfile = /home/effect/Desktop/workspace/Eviota /logs/gunicorn_supervisor.log ; Where to write log messages redirect_stderr = true ; Save stderr in the same log environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8 ; Set UTF-8 as default encoding when I run the supervisor Everything seems ok and no problem is shown. Here is my nginx configuration which I can't say I fully understand upstream eviotapro_server { # fail_timeout=0 means we always retry an upstream even if it failed # to return a good HTTP response (in case the Unicorn master nukes a # single worker for timing out). server unix:/home/effect/Desktop/workspace/Eviota/run/gunicorn.sock fail_timeout=0; } server { listen 8005; server_name <ip address>; client_max_body_size 4G; access_log /home/effect/Desktop/workspace/Eviota/logs/nginx-access.log; error_log /home/effect/Desktop/workspace/Eviota/logs/nginx-error.log; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/effect/Desktop/workspace/Eviota/eviotapro/static/; } location /media/ { alias /home/effect/Desktop/workspace/Eviota/eviotapro/media/; } location / { # an HTTP header important enough to have its own Wikipedia entry: # http://en.wikipedia.org/wiki/X-Forwarded-For proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # enable this if and only if you use HTTPS, this helps Rack # set the proper protocol for doing redirects: … -
JSON, django, d3 error loading array
I am trying to create a histogram in d3 based on JSON data from my django app. However I keep getting an error. What can be the cause of this? The errors that I get are the following: Chrome: Cannot read property 'histogram' of undefined Safari: undefined is not an object (evaluating 'd3.layout.histogram') views.py: def chart(request): Chartdata = serializers.serialize('json', Projects.objects.all(),) return JsonResponse(Chartdata, safe=False) graphics.html: d3.json(/chart/, function(error, data) { var x = JSON.parse( data ); var map = x.map(function(i) { return parseInt(i.fields.Totaal); }); console.log(map); var histogram = d3.layout.histogram() .bins(25) (map) console.log(histogram) The console logs in chrome: (294) [18620730, 24783518, 1931623, 4169495, 4214153, 21594277, 15247677, 4465545, 46921993, 5504440, 4503094, etc. -
django Mezzanine creating custom content types
I am trying to learn how to create custom content types using the online documentation for mezzanine I have the following directory structure (the project is "sample"): /path/to/myproject /sample /sample admin.py models.py models.py from django.db import models from mezzanine.pages.models import Page # The members of Page will be inherited by the Author model, such # as title, slug, etc. For authors we can use the title field to # store the author's name. For our model definition, we just add # any extra fields that aren't part of the Page model, in this # case, date of birth. class Author(Page): dob = models.DateField("Date of birth") class Book(models.Model): author = models.ForeignKey("Author") cover = models.ImageField(upload_to="authors") admin.py from django.contrib import admin from mezzanine.pages.admin import PageAdmin from .models import Author admin.site.register(Author, PageAdmin) When I run python manage.py runserver the Author model does not appear in the admin page. Intially, I thought that was because I had not run makemigrations and migrate however, after running those two manage.py commands, the issue remains unresolved (models do not appear in admin page). How do I fix this so that my custom models appear in admin and I can use them in mezzanine? -
How to implement optional multiple same fields in django modelForm of a model?
I have the following model in django: class Profile(models.Model): name = models.CharField(max_length=100) address = models.TextField(blank=True) def __unicode__(self): return self.name and the model form: class ProfileForm(ModelForm): class Meta: model = Profile fields='__all__' Profile can have multiple addresses i.e, user should be able to add multiple addresses in a single form. How do I implement this? name: _______________ address: ______________ address: ______________ address: ______________ -
Taking any csv columns naming scheme into Django form
My code is currently hard coded to only accept csv files with the following naming scheme for its columns: first_name,last_name,phone,email,address,company However I would like users to be able to upload csv files that have any naming scheme or at least similar. for example: Email,LastName,FirstName,Company,phone_number,Address would be a valid naming scheme and would populate my django forms successfully. How would I go about doing that? Relevant code as follows: with open(tmp_file, 'r') as f: dr = csv.DictReader(f) for data_dict in dr: #adds to form try: form = AddContactForm(data_dict) if form.is_valid(): obj = form.save(commit=False) obj.owner = request.user.username first_name = form.cleaned_data.get(data_dict["first_name"]) last_name = form.cleaned_data.get(data_dict["last_name"]) phone = form.cleaned_data.get(data_dict["phone"]) email = form.cleaned_data.get(data_dict["email"]) address = form.cleaned_data.get(data_dict["address"]) company = form.cleaned_data.get(data_dict["company"]) obj.save() else: logging.getLogger("error_logger").error(form.errors.as_json()) return HttpResponse('<h2>CSV was not valid: please use header naming scheme: first_name,last_name,phone,email,address,company (can be in any order)</h2>') return HttpResponseRedirect(reverse("crm:importcsv")) except Exception as e: logging.getLogger("error_logger").error(repr(e)) pass -
Django search in a TextField
I'm trying to do a search for a query in Django, the icontains lookup works for the title(CharField) but not for the content(TextField). I want to search if the query exists in the title or content of a post. This is the code: from django.db.models import Q ... def get_queryset(self): qs = BlogPost.objects.all() query = self.request.GET.get('q') if query is not None: qs = qs.filter(Q(title__icontains=query) | Q(content__icontains=query)).distinct() return qs This is the error I get when making a query: Exception Type: FieldError Exception Value: Unsupported lookup 'icontains' for TextField or join on the field not permitted. -
Is There a Book or Books that can be used while building a project in Django 2.0
I prefer books over the tutorials that are available so I was wondering if there are any people that can suggest a book or book's that i can read while building a project. I prefer learn ,understand and implement approach..I found many suggestions but they seem to be very basic. I have a clear understanding of how Django Works i need to take it up a notch.