Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Social Auth, Google, and refresh token
In a personal project, I am trying to use Django as my front end and then allow data entered by users in a particular form to be copied to google sheets. Google's own docs recommend using https://github.com/google/oauth2client which is now deprecated, and the docs have not been updated. With this, I have started attempting to use Python Social Auth and Gspread. For Gspread to be able to function correctly, I need to be able to pass it not only an access token but also a refresh token. Python Social Auth however is not persisting the refresh token along with the rest of the "extra data". Looking at the data preserved and the URLs routed to, it seems to me more like somewhere it is routing through Google+. I have the following configurations in my Django settings files: AUTHENTICATION_BACKENDS = ( 'social_core.backends.google.GoogleOAuth2', 'django.contrib.auth.backends.ModelBackend', ) SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', 'social_core.pipeline.social_auth.associate_by_email', ) SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '...' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '...' SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = ['https://www.googleapis.com/auth/spreadsheets'] Is there a better way to access a google sheet? Am I correct that PSA or google is redirecting me into a Google+ auth flow instead of the Google Oauth2? If not, what must change … -
is there a way to use Pytion3, django2.0.2 and MySql together on ubuntu?
I searched alot to install python3.6 and django2.0.2 with MySql server, but I got nothing because django2.0.2 framework doesn't support MySqldb yet. -
Djando ManagementForm error when using custom intermediate page and changeform_view()
I'm using changeform_view to catch saves and only add an intermediate page conditionally. Inside the admin class I have: @csrf_protect_m @transaction.atomic def changeform_view(self, request, object_id=None, form_url='', extra_context=None): survey = Survey.objects.get(pk=object_id) check_against = ['incomplete', 'submitted', 'completed'] if not request.POST.get('confirmed'): if request.method == 'POST' and survey.status == 'in-market' and any(s in request.POST.get('status') for s in check_against): context = { 'title': _('Change in-market survey?'), 'is_popup': False, 'opts': self.model._meta, 'app_label': self.model._meta.app_label, 'object': survey, } return TemplateResponse( request, 'admin/survey/status_from_inmarket_confirmation.html', context) return super(SurveyAdmin, self).changeform_view(request, object_id, form_url, extra_context) My template looks like: {% extends "admin/base_site.html" %} {% load i18n admin_urls %} {% block breadcrumbs %} <div id="grp-context-navigation"> <nav id="grp-breadcrumbs" class=""> <header style="display:none"><h1>Breadcrumbs</h1></header> <ul> <li><a href="{% url 'admin:index' %}">{% trans 'Home' %}</a></li> <li><a href="{% url 'admin:app_list' app_label=opts.app_label %}">{{ app_label|capfirst }}</a></li> <li><a href="{% url opts|admin_urlname:'changelist' %}">{{ opts.verbose_name_plural|capfirst|escape }}</a></li> <li><a href="{% url opts|admin_urlname:'change' object.pk|admin_urlquote %}">{{ object|truncatewords:"18" }}</a></li> <li>{% trans 'Make Live' %}</li> </ul> </nav> </div> {% endblock %} {% block content %} {% if not perms_lacking and not protected %} <p>{% blocktrans with escaped_object=object %}Are you sure you want to switch this status {{ object_name }} "{{ escaped_object }}"?{% endblocktrans %}</p> <form action="" method="post">{% csrf_token %} <div> <input type="hidden" name="confirmed" value="yes" /> <input type="submit" value="{% trans "Yes, I'm sure" %}" … -
Opengraph tags (og:tags) in Django template not scraped by Facebook
I've been trying to get opengraph tags work for my django website. I use "www.somewebsite.com" as website url during this question. I used the following static code in the header: <meta property="og:title" content="websitename" /> <meta property="og:type" content="website" /> <meta property="og:url" content="https://www.somewebsite.com/" /> <meta property="og:description" content="Some description."/> <meta property="og:image" content="https://www.somewebsite.com/static/image.png" /> This did not work, so I've installed django-meta (http://django-meta.readthedocs.io/en/latest/installation.html) and implemented the following code at my landing page view, so the meta data is added dynamically on the server: # basic page view class BasicView(View): template_name = 'landing/landing.html' # get request def get(self, request): context = { "meta": Meta( title="Websitename", description='Some description.', type='website', url='https://www.somewebsite.com/', image='https://www.somewebsite.com/static/image.png', use_title_tag=True, use_facebook=True, use_og=True, ), } return render(request, self.template_name, context) With the following template: <head {% meta_namespaces %}> {% include 'meta/meta.html' %} </head> This results in: <head prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb#"> <meta name="description" content="Some description."> <title>Websitename</title> <meta property="og:title" content="Websitename"> <meta property="og:url" content="https://www.somewebsite.com/"> <meta property="og:description" content="The easiest way of making digital music."> <meta property="og:image" content="https://www.judgemysound.com/static/image.png"> </head> When fetching new scrape information in the facebook debugger tool (https://developers.facebook.com/tools/debug/og/object/) it gives the following information (image): Meta data scraped from my website with facebook sharing debugger The strange thing is; The information which are in my og tags are not … -
How to name python function by seeing the code
Recently I have been playing with some python code. I am trying to name the function by seeing the code. what would be the possible or proper name to function "h" in the code below. import functools from tasks.models import Task, TaskStatus from tasks.exceptions import DuplicateExecution def h(func): @functools.wraps(func) def wrapped(*args, **kwargs): if Task.objects.filter( status_id=TaskStatus.STARTED task_type=kwargs['task_type'} ).count() > 0: raise DuplicateExecution( "cannot run more than one {} task simultaneously" .format(kwargs['task_type'])) return func(*args, **kwargs) return wrapped -
How to serve WSGI Django app under Apache mod-alias directive
I have a website like mydomain.com in PHP, served under Apache. Now I'd like to add a Python-Django app under a specific URL: mydomain.com //PHP mydomain.com/about //PHP mydomain.com/python-app //PYTHON In Apache and PHP I normally use mod_alias for this kind of task: <Virtualhost *:80> ServerName mydomain.com ... Alias /another-app /var/www/another-app #PHP </Virtualhost> Using Python I need to use mod_wsgi, adding additional parameters like: Alias /static /var/www/py_app/static WSGIDaemonProcess py_app python-home=/home/user/.virtualenvs/py_app python-path=/var/www/py_app WSGIProcessGroup py_app How can I scope that directives under my alias? I'd need a vhost scoped to a specific url or something like this: <Alias /python-app> Alias /static /var/www/py_app/static #use this alias only if in that sub-url ... WSGI DIRECTIVES ... </Alias> I hope to have clarified the problem (a Python app under an Apache alias with scoped settings), how can I accomplish that? Thank you, Francesco -
Searching for keywords and creating links automatically in Django
I am creating an information web application (in Django) that often uses some medical terms. The medical terms and their explanations are stored in a separate model/database. As of now, I am manually creating links to description pages for each medical term. I was wondering if there is a way to get the code automatically search a page contents for medical terms, and automatically create links (or popovers) to their description pages. All the pages are dynamic, and the medical terms are stored in their own separate model. So far, the medical terms model does not have a relationship with any other models Any thoughts if this can be done, and if so, how to go about it? Thanks for your time and assistance. -
opencv error file cannot be opened for reading cv::face::FaceRecognizer::read windows
i have been trying to run a django application (attendance system with face recognition). i'm using python with opencv=3.2 and after installing both opencv-python and opencv-contrib-python using pip on anaconda framework ,i still get error like this "opencv error file cannot be opened for reading cv::face::FaceRecognizer::read". file c:\projects\opencv-python\opencv_contrib\modules\face\src\facerec.cpp line 61. i'm new to using opencv and django so any suggentions are welcome -
django-rules Row-Level Permissions on a Model
I have a django project with two models: class Project(models.Model): name = models.CharField(primary_key=True, max_length=12) team = models.CharField(max_length=10) class Task(models.Model): name = models.CharField(max_length=10) project = models.ForeignKey(Project) I would like to control which rows in these models each user can access. My groups in auth_group correspond to team in the Project model. How would I use django-rules to restrict user access to Task rows based on Project team? Let's say there is Team X, and John Smith has been placed in group Team X. How should django-rules be used to only allow John Smith to see tasks that are tied to projects for Team X? I'm not sure how to access Team in order to compare it to the groups the user is a part of. Unsure to the point where I don't have any workable code to show for it. -
NoReverseMatch at /accounts/password/reset/ django registration redux
I'm trying to use django-registration-redux for my authentication in my project, but when testing out the password reset, I come up with an error containing the following traceback Internal Server Error: /accounts/password/reset/ Traceback (most recent call last): File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/utils/decorators.py", line 67, in _wrapper return bound_func(*args, **kwargs) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/utils/decorators.py", line 149, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/utils/decorators.py", line 63, in bound_func return func.__get__(self, type(self))(*args2, **kwargs2) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/contrib/auth/views.py", line 418, in dispatch return super(PasswordResetView, self).dispatch(*args, **kwargs) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/views/generic/base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/views/generic/edit.py", line 183, in post return self.form_valid(form) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/contrib/auth/views.py", line 431, in form_valid form.save(**opts) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/contrib/auth/forms.py", line 289, in save email, html_email_template_name=html_email_template_name, File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/contrib/auth/forms.py", line 236, in send_mail body = loader.render_to_string(email_template_name, context) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/template/loader.py", line 68, in render_to_string return template.render(context, request) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/template/backends/django.py", line 66, in render return self.template.render(context) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/template/base.py", line 207, in render return self._render(context) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/template/base.py", line 199, in _render return self.nodelist.render(context) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/template/base.py", line 990, in render bit … -
Ajax Django Cart Not Displaying Data Correctly
I am working on a Django Ajax cart where I am stuck with JS to add the products to the cart. I think I have the Ajax part broadly working but it seems to add/remove multiple items in one go. The bit I am struggling with is one the $.each section. For instance if am adding a particular item to the cart it will re-add everything already in the cart. $(document).ready(function(){ var productForm = $(".form-product-ajax") // #form-product-ajax productForm.submit(function(event){ event.preventDefault(); // console.log("Form is not sending") var thisForm = $(this) //var actionEndpoint = thisForm.attr("action"); var actionEndpoint = thisForm.attr("data-endpoint"); var httpMethod = thisForm.attr("method"); var formData = thisForm.serialize(); $.ajax({ url: actionEndpoint, method: httpMethod, data: formData, success: function(data){ var submitSpan = thisForm.find(".submit-span") if (data.added){ submitSpan.html("In cart <button type='submit' class='btn btn-link'>Remove?</button>") } else { submitSpan.html("<button type='submit' class='btn btn-success'>Add to cart</button>") } var currentPath = window.location.href if (currentPath.indexOf("") != -1) { refreshCart() } }, error: function(errorData){ console.log("error") console.log(errorData) } }) }) function refreshCart(){ console.log("in current cart") var cartTable = $(".cart-table") var cartBody = cartTable.find(".cart-body") var productRows = cartBody.find(".cart-product") var currentUrl = window.location.href var refreshCartUrl = '/api/cart/' var refreshCartMethod = "GET"; var data = {}; $.ajax ({ url: refreshCartUrl, method: refreshCartMethod, data: data, success: function(data) { console.log("success") console.log(data) … -
How to properly name python functions
What should be the proper function to name "w" in the below code def w(a_list): return list(set(a_list)) What should be the proper function to name "b" in the below code def b(a_list, item): first = 0 last = len(a_list) - 1 if len(a_list) == 0: return None else: i = (first + last) //2 if item == a_list[i] return i elif a_list[i] < item: return b(a_list[i+1:], item) else: return b(a_list[:i], item) what should be the proper function to name "h" in the below code import functools from tasks.models import Task, TaskStatus from tasks.exceptions import DuplicateExecution def h(func): @functools.wraps(func) def wrapped(*args, **kwargs): if Task.objects.filter( status_id=TaskStatus.STARTED task_type=kwargs['task_type'} ).count() > 0: raise DuplicateExecution( "cannot run more than one {} task simultaneously" .format(kwargs['task_type'])) return func(*args, **kwargs) return wrapped -
Where to find origin or Gunicorn import errors?
When I run gunicorn --log-file=- onbytes.wsgi:application on my remote DigitalOcean Django server I get the following error, here's the full traceback: Traceback (most recent call last): File "/home/james/postr/env/lib/python3.5/site-packages/gunicorn/arbiter.py", line 578, in spawn_worker worker.init_process() File "/home/james/postr/env/lib/python3.5/site-packages/gunicorn/workers/base.py", line 126, in init_process self.load_wsgi() File "/home/james/postr/env/lib/python3.5/site-packages/gunicorn/workers/base.py", line 135, in load_wsgi self.wsgi = self.app.wsgi() File "/home/james/postr/env/lib/python3.5/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/home/james/postr/env/lib/python3.5/site-packages/gunicorn/app/wsgiapp.py", line 65, in load return self.load_wsgiapp() File "/home/james/postr/env/lib/python3.5/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp return util.import_app(self.app_uri) File "/home/james/postr/env/lib/python3.5/site-packages/gunicorn/util.py", line 352, in import_app __import__(module) ImportError: No module named 'onbytes' When I look in /home/james/postr/env/lib/python3.5/site-packages/gunicorn/util.py line 352 to find onbytes, it's not there, it just shows the dynamic import error code: def import_app(module): parts = module.split(":", 1) if len(parts) == 1: module, obj = module, "application" else: module, obj = parts[0], parts[1] try: __import__(module) except ImportError: if module.endswith(".py") and os.path.exists(module): msg = "Failed to find application, did you mean '%s:%s'?" raise ImportError(msg % (module.rsplit(".", 1)[0], obj)) else: raise mod = sys.modules[module] is_debug = logging.root.level == logging.DEBUG try: app = eval(obj, vars(mod)) except NameError: if is_debug: traceback.print_exception(*sys.exc_info()) raise AppImportError("Failed to find application: %r" % module) if app is None: raise AppImportError("Failed to find application object: %r" % obj) if not callable(app): raise AppImportError("Application object must … -
Connecting Angular-formly to Django
I am trying to create a web application using Angular-formly on the front end and a Django framework on the back end. Have a couple of questions regarding this: How do I send data from front to back and vice versa? How do I create a file upload button using angular formly. Thank you -
openshift django multiple sqlite databases set up
I have three sqlite3 databases for my django project. Now, I want to know what's the correct set up for all three databases. My application runs perfectly from my localhost. However, openshift can't detect my other databases and therefore I keep getting a server error. I'm struggling to find a perfect answer. #settings.py import os DJ_PROJECT_DIR = os.path.dirname(__file__) BASE_DIR = os.path.dirname(DJ_PROJECT_DIR) WSGI_DIR = os.path.dirname(BASE_DIR) REPO_DIR = os.path.dirname(WSGI_DIR) DATA_DIR = os.environ.get('OPENSHIFT_DATA_DIR', BASE_DIR) import sys sys.path.append(os.path.join(REPO_DIR, 'libs')) import json try: with open(os.path.join(DATA_DIR, 'secrets.json')) as handle: SECRETS = json.load(handle) except IOError: SECRETS = { 'secret_key': 'a' } .... DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # GETTING-STARTED: change 'db.sqlite3' to your sqlite3 database: 'NAME': os.path.join(DATA_DIR, 'db.sqlite3'), }, 'db2': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(DATA_DIR, 'db2.sqlite3'), }, 'db3': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(DATA_DIR, 'db3.sqlite3'), } } -
Django database advanced interactions
Imagine that you have some users in a database. Those users can upload objects, and every object has a value(objects are saved in another datebase). Also those users can take part of one or more user's object. That's my code: from django.contrib.auth.models import User class Upload(model.Models): name = models.Charfield(max:length=200) value = models.IntegerField(default=0) disponibility = models.IntegerField(default=100)#Percentage uploader = models.ForeingKey(User, on_delete=models.CASCADE) class UserProfile(models.Models): user = models.OneToOneField(User,on_delete=models.CASCADE) user_objects = models.ManyToManyField('Upload') def create_profile(sender, **kwargs): if kwargs['created']: user_profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) My problem is that i can't see the uploader in the UserProfile DB, and all uploads are automaticly being associated to all UserPofile's objects. (Probably my code is completly wrong, i'm just a novice with django). -
How to install the hstore extension on the template1 database using a Django migration?
According to http://djangonauts.github.io/django-hstore/#_limitations, in order to install PostgreSQL's hstore extension on the template1 database one must run psql -d template1 -c 'create extension hstore;' as an initial setup step. I'd prefer to have this automatically done by Django, however; it seems I can use the CreateExtension operation for this. However, if I try to do this by modifying the 0001_initial.py migration as follows, from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion from django.contrib.postgres.operations import CreateExtension class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ CreateExtension(name='hstore'), ... ] I still run into a type "hstore" does not exist error when I try to python manage.py migrate. This particular stack trace is from the Aptible PaaS, which is provisioned with a 'default' PostgreSQL database without hstore installed: remote: INFO -- : WAITING FOR: Run before_release commands from .aptible.yml: python3 manage.py migrate remote: INFO -- : (0.001) SELECT typarray FROM pg_type WHERE typname = 'citext'; args=None remote: INFO -- : (0.002) remote: INFO -- : SELECT c.relname, c.relkind remote: INFO -- : FROM pg_catalog.pg_class c remote: INFO -- : LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace remote: INFO -- : WHERE c.relkind IN ('r', 'v') remote: … -
Django listview showing only id and no other field in template
I'm new to Django. I added a database I created from data I got from a movie database to my Django project. I am using Django's generic.ListView to display its fields. However, only the id of each movie shows. Template: <body> The movies include: <br/> {% for movie in movies_list %} {{ movie.id }} {{ movie.title }} <br/> {{ movie.original_language }} <br/> {{ movie.overview }} {% endfor %} </body> Despite movie.title, movie.original_language, and movie.overview in the code, django-debug-toolbar shows only one query was made when I loaded the page: SELECT "movies"."id" FROM "movies". models.py in the app directory: from django.db import models class Movies(models.Model): class Meta: app_label = "myapp" db_table = "movies" managed = False views.py in the app directory: from django.views import generic from .models import Movies class MoviesListView(generic.ListView): model = Movies template_name = r'myproject/theme/templates/myapp/myapp.html' I tried adding the following to class MoviesListView(generic.ListView) above but it merely doubled the SQL queries for movie.id: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['movies_list'] = Movies.objects.all() return context urls.py in the same directory as settings.py: from django.contrib import admin from django.urls import path from django.conf import settings from myapp import views as myapp_views urlpatterns = [ path('admin/', admin.site.urls), path('myapp/', myapp_views.MoviesListView.as_view(), name='movie_list'), ] Here … -
Python Django - Not 'object' attribute on scaffolded model
I'm only a newbie in Python and Django. I'm working with a MySQL database, I have created the model with the command: python manage.py inspectdb > /app/models/model.py. And it works wonderfully. model.py from __future__ import unicode_literals from django.db import models class Account(models.Model): id = models.BigAutoField(primary_key=True) login = models.CharField(unique=True, max_length=30) lang = models.CharField(max_length=4) forum_name = models.CharField(max_length=80) hwid = models.CharField(max_length=255, blank=True, null=True) use_allowed_hwids = models.IntegerField(blank=True, null=True) password = models.CharField(max_length=45) social_id = models.CharField(max_length=13) email = models.CharField(max_length=64) create_time = models.DateTimeField(blank=True, null=True) status = models.CharField(max_length=8) reason = models.CharField(max_length=255, blank=True, null=True) securitycode = models.CharField(max_length=192, blank=True, null=True) newsletter = models.IntegerField(blank=True, null=True) empire = models.IntegerField() name_checked = models.IntegerField() availdt = models.DateTimeField(db_column='availDt', blank=True, null=True) # Field name made lowercase. mileage = models.IntegerField() cash = models.IntegerField() gold_expire = models.DateTimeField() silver_expire = models.DateTimeField() safebox_expire = models.DateTimeField() autoloot_expire = models.DateTimeField() fish_mind_expire = models.DateTimeField() marriage_fast_expire = models.DateTimeField() money_drop_rate_expire = models.DateTimeField() shop_double_up_expire = models.DateTimeField() total_cash = models.IntegerField() total_mileage = models.IntegerField() ip = models.CharField(max_length=255, blank=True, null=True) last_pw_change = models.DateTimeField(blank=True, null=True) web_admin = models.IntegerField() web_ip = models.CharField(max_length=15) web_aktiviert = models.CharField(max_length=32) real_name = models.CharField(max_length=32, blank=True, null=True) question1 = models.CharField(max_length=64, blank=True, null=True) answer1 = models.CharField(max_length=64, blank=True, null=True) last_vote = models.DateTimeField(blank=True, null=True) lostpw_token = models.CharField(max_length=64, blank=True, null=True) last_play = models.DateTimeField(blank=True, null=True) remember_token = models.TextField(blank=True, null=True) class Meta: managed = … -
How to pass database queryset objects from class based views to templates in Django 2.0
I am building a web app.I am trying to pass a queryset from a class based view to templates as variables in Django 2.0. But the variables were not displayed at http://localhost:8000/joblist/. Other text are displayed on this url routing, but the queryset objects are not displayed as variables on the page. The models.py and the database work fine, and the database is populated with ~10k records. What am i missing? I would also like to know the advantages of class based views over function based views in simple words. Thank you. My views.py: from django.http import HttpResponse from django.template.response import TemplateResponse from django.views.generic import ListView,DetailView from joblist.models import Jobs def index(request): context = {} html = TemplateResponse(request,'welcome.html',context) return HttpResponse(html.render()) class JobList(ListView): model=Job context_object_name = 'job_title' queryset=Job.objects.all() template_name = 'job_list.html' class JobDetail(DetailView): model = Job context_object_name = 'job_detail' queryset = Job.objects.all() template_name = 'job_detail.html' My template: joblist.html {% extends 'welcome.html' %} <h1> Job Title </h1> <ul> {% for job in object_list %} <li>{{ job_title }}</li> {% endfor %} </ul> -
django content from git files
I'm running a small blog which is currently served with django + postgresql. It has some features, which requires dynamic generation of pages. From the other hand I really love the idea of static sites generation (like pelican or Jekyll). The most interesting idea I see (and willing to use) is content stored and served from git repo of the project itself. Most of the content I have in django is articles, which easily can be managed like a separate git pages. And I would really love to move it there and use my favorite text editor instead of django admin. However I can't migrate completely to static site, as I still need a dynamic part of pages. Now the question: is there any kind of existing "pelican-like" tool for django which would allow to sync content from git to database backend and serve it in a normal way or that's a very specific task which I had to develop myself from scratch? -
django full text search: how to do with accent text
I am using Django 2.0 and postgres (PostgreSQL) 9.6.1 I am having the below model with headline and body_text: class Entry(models.Model): title = models.CharField(max_length=255) description = models.TextField() def __str__(self): return self.title The below is my content headline: Dhṛtarāṣṭra inquired from Sañjaya, body_text: Prabhupāda: So Dhṛtarāṣṭra inquired from Sañjaya, kim akurvata: "After my sons and my brother's sons assembled together for fighting, what did they do?" This was the inquiry. So to encourage him... Because Sañjaya could understand the feelings of his master that he wanted the fight, no compromise, kṣatriya spirit, "Let my sons and my brother's sons fight..." That is kṣatriya spirit. Also i have installed unaccent extension in the following way: # Generated by Django 2.0 on 2018-02-06 22:34 from django.db import migrations from django.contrib.postgres.operations import UnaccentExtension, TrigramExtension class Migration(migrations.Migration): dependencies = [ ('articles', '0012_auto_20180205_2234'), ] operations = [ UnaccentExtension(), TrigramExtension() ] Extension got installed successfully. Now i want to search for accented word Dhṛtarāṣṭra. So i am trying the following: from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector vector = SearchVector('title__unaccent', weight='A') + SearchVector('description__unaccent', weight='B') query = SearchQuery('Dhrtarastra') Article.objects.annotate(rank=SearchRank(vector, query)).filter(rank__gte=0.3).order_by('rank') : Cannot resolve keyword 'unaccent' into field. Join on 'title' not permitted. I have read here: Using unaccent with … -
Application error deploying Django app on heroku
I'm trying to launch a Django web api on Heroku. But I'm gettting 'Application error'. I'm new to heroku and Django, so I'm not able to understand the logs properly. I tried a lot of solutions that were online but it didn't work and I couldn't understand that well either. I tried setting DISABLE_COLLECTSTATIC = 1 but that didn't help. heroku logs: 2018-02-07T18:20:09.896112+00:00 app[api]: Release v9 created by user bhavesh.misri@gmail.com 2018-02-07T18:20:09.896112+00:00 app[api]: Remove DISABLE_COLLECTSTATIC config vars by user bhavesh.misri@gmail.com 2018-02-07T18:20:11.340335+00:00 heroku[web.1]: Restarting 2018-02-07T18:20:14.194086+00:00 heroku[web.1]: Starting process with command `gunicorn --pythonpath expense_manager wsgi` 2018-02-07T18:20:15.661997+00:00 heroku[web.1]: Process exited with status 127 2018-02-07T18:20:15.610040+00:00 app[web.1]: bash: gunicorn: command not found 2018-02-07T18:20:17.778414+00:00 heroku[web.1]: Starting process with command `gunicorn --pythonpath expense_manager wsgi` 2018-02-07T18:20:19.402652+00:00 heroku[web.1]: Process exited with status 127 2018-02-07T18:20:19.356758+00:00 app[web.1]: bash: gunicorn: command not found 2018-02-07T18:20:19.416979+00:00 heroku[web.1]: State changed from starting to crashed 2018-02-07T18:20:50.607341+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=shielded-lake-72150.herokuapp.com request_id=bc0dccbc-c496-4404-b4ef-b9cef89c5373 fwd="49.177.121.42" dyno= connect= service= status=503 bytes= protocol=https 2018-02-07T18:27:53.000000+00:00 app[api]: Build started by user bhavesh.misri@gmail.com 2018-02-07T18:27:53.000000+00:00 app[api]: Build failed -- check your build logs 2018-02-07T18:30:59.000000+00:00 app[api]: Build started by user bhavesh.misri@gmail.com 2018-02-07T18:30:59.000000+00:00 app[api]: Build failed -- check your build logs 2018-02-07T18:32:41.000000+00:00 app[api]: Build started by user bhavesh.misri@gmail.com 2018-02-07T18:32:41.000000+00:00 app[api]: Build failed -- check … -
What AWS service can help speed up slow Django view functions
I have a Django application with a Postgres DB that has kind of run away from my client as the database has millions of records. That being said there are some view functions that make several database queries, and because of that, it is glacier slow. Here is an example of one of my view functions It is kind of messy because I was playing around with things to look for query optimizations, my apologies. def get_filters(request): try: post_data = request.body.decode("utf-8") post_data = json.loads(post_data) except Exception as e: logging.error('There was an issue getting filter post data') logging.error(e) return HttpResponse( json.dumps({'filters': {'makes': [], 'models': [], 'years': [], 'transmissions': [], 'fuel_types': []}}), content_type='application/json') dealer = post_data['dealer'] if 'dealer' in post_data else None make_ids = post_data['make_ids'] if 'make_ids' in post_data else [] model_ids = post_data['model_ids'] if 'model_ids' in post_data else [] years = post_data['years'] if 'years' in post_data else [] condition = post_data['condition'] if 'condition' in post_data else None price_min = post_data['price_min'] if 'price_min' in post_data else 0 price_max = post_data['price_max'] if 'price_max' in post_data else 10000000 # Catch Critical Error Where There Is No Dealer if not dealer: logging.error('Unable to find a Dealer') return HttpResponse( json.dumps({'filters': {'makes': [], 'models': [], 'years': [], … -
Django "ValueErrror: could not find common ancestor of {migrations}"
I'm trying to follow the documentation in https://docs.djangoproject.com/en/2.0/ref/contrib/postgres/operations/ to create a migration which will essentially perform the SQL statement CREATE EXTENSION IF NOT EXISTS hstore; on the database. I've tried adding the following file, called create_extension_hstore.py, to the migrations directory: from django.db import migrations from django.contrib.postgres.operations import CreateExtension class Migration(migrations.Migration): operations = [CreateExtension(name='hstore')] My 'mental model' of this is that since Django infer the order of the migrations from their dependencies and this one has none, it should be run first. However, I'm getting the error when I try to run python manage.py makemigrations --merge: (venv) Kurts-MacBook-Pro:lucy-web kurtpeek$ python manage.py makemigrations --merge (0.000) SELECT typarray FROM pg_type WHERE typname = 'citext'; args=None (0.003) SELECT c.relname, c.relkind FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind IN ('r', 'v') AND n.nspname NOT IN ('pg_catalog', 'pg_toast') AND pg_catalog.pg_table_is_visible(c.oid); args=None (0.001) SELECT "django_migrations"."app", "django_migrations"."name" FROM "django_migrations"; args=() Traceback (most recent call last): File "manage.py", line 29, in <module> execute_from_command_line(sys.argv) File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/core/management/commands/makemigrations.py", line 142, in handle return self.handle_merge(loader, …