Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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, … -
Django Rest Framework: Serializing a model and grouping by a foreign key for other data
I have the following three models: class Package(models.Model): name = models.CharField() class Part(models.Model): name = models.CharField() sku = models.IntegerField() class Member(models.Model): name = models.CharField() class MemberPurchase(models.Model): member = models.ForeignKey(Member) package = model.ForeignKey(Package) part = models.ForeignKey(Part) purchase_date = models.DateField() I want to serialize MemberPurchase model for an API so that I can have all the information I need as below: { "name": "John Doe", "id": 123, "purchases": [ { "name": "Package Silver", "parts": [ { "name": "Part Silver 1", "sku": "12345", }, { "name": "Part Silver 2", "sku": "145678", } ] }, { "name": "Package Gold", "parts": [ { "name": "Part Gold 1", "sku": "1010101", } ] } ] } I am not exactly sure how to build the serializer to give me the result above. I can write a serializer that will serialize a queryset from MemberPurchase but that will have a lot of repeated data. I am guessing this needs multiple serializers: class MemberSerializer(serializers.ModelSerilaizer): purchases = MemberPurchaseSerializer(source='memberpurchase_set', many=True) class Meta: model = Member fields = ['name', 'id'] class MemberPurchaseSerializer(serializers.Serializer): name = serializers.SerializerMethodField('get_package_name') parts = PackagePartSerializer(many=True) def get_pacakage_name(self, instance): return instance.package.name class PackagePartSerializer(serializers.Serializer): name = serializers.SerializerMethodField('get_part_name') sku = serializers.SerializerMethodField('get_part_sku') def get_part_name(self, instance): return instance.part.name def get_part_sku(self, instance): return instance.part.sku I … -
Django,python pip install mysqlclient not work
I am working with Django and trying to install mysqlclient but haven't had any success in doing so. I keep getting an error when I run python manage.py makemigrations. Here's the error I'm seeing: Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/private/var/folders/w8/tfy1yzhd74502cs1_2thbkl00000gn/T/pip-build-yYQxRD/mysqlclient/setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record /var/folders/w8/tfy1yzhd74502cs1_2thbkl00000gn/T/pip-DGru8k-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /private/var/folders/w8/tfy1yzhd74502cs1_2thbkl00000gn/T/pip-build-yYQxRD/mysqlclient/ -
Send data from Django to java script(in Chrome extension)
I have developed a chrome extension and I am inserting json data in mysql through django service. I want to send data from django to java script which is in chrome extension. popup.js: document.addEventListener('DOMContentLoaded', documentEvents, false); function myAction(fname,femail,fpassword) { var str = "name="+ fname.value + "&email=" + femail.value + "&password=" + fpassword.value; var xmlhttp = new XMLHttpRequest(); alert(str); var theUrl = "http://127.0.0.1:8000/polls/?"; xmlhttp.open("POST", theUrl, true); xmlhttp.onreadystatechange = function() { //alert(xmlhttp.readyState + " " + xmlhttp.status); if (xmlhttp.readyState == 4){ alert("entered"); } else{ alert("not entered"); } }; xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8"); xmlhttp.send(str); } function loadDoc() { var xhttp = new XMLHttpRequest(); var theUrl = "http://127.0.0.1:8000/polls/?"; xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("output").innerHTML = this.responseText; } }; xhttp.open("GET",theUrl,true); xhttp.send(); } function documentEvents() { var submitButton = document.getElementById('submit') submitButton.addEventListener('click', function(event) { var formId = document.getElementById('test'); var name = document.getElementById('name'); var email = document.getElementById('email'); var password = document.getElementById('password'); myAction(name,email,password); }); } views.py : from django.http import HttpResponse from django.http import HttpResponseRedirect, HttpResponse from .models import UserProfile from django.views.decorators.csrf import csrf_exempt @csrf_exempt def index(request): req = request.method t = request.GET print(req) name = request.POST.get('name') email = request.POST.get('email') password = request.POST.get('password') savedata = UserProfile(name=name,email=email,password=password) savedata.save() print('Hello %s %s %s' % (name, email, … -
Django timezone same day diff is not 0
test function from django.utils import timezone def date_diff_now(date): print(date) print(timezone.now()) print(date - timezone.now()) print((date - timezone.now()).days) Result 2018-02-07 17:46:36.442314+00:00 2018-02-07 17:47:32.084900+00:00 -1 day, 23:59:04.357374 -1 Why the difference between 2 datetime on the same day does not return 0 ? -
Load Unknown Number of Charts with Django Chartit
I have a script that generates multiple charts that are passed to the datachart variable in my chart.html. I'd like to have each chart in it's own <div>. It is easy enough to iterate through datachart and create the amount of <div> required, but the problem I'm facing is that the number of charts in datachart varies. In the example below there are 12 charts generated and I have to manually pass datachart|loadchart:"p1,p2,...". Is there a way to iterate though the charts or a way to construct the datachart|loadchart:"p1,p2,..." dynamically based on the length of the datachart array? Snippet from chart.html Template <head> <!-- code to include the highcharts and jQuery libraries goes here --> <!-- load_charts filter takes a comma-separated list of id's where --> <!-- the charts need to be rendered to --> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script> <script src="http://code.highcharts.com/highcharts.js" type="text/javascript"></script> <script src="/highcharts.js" type="text/javascript"></script> {% load chartit %} {{ datachart|load_charts:"p1,p2,p3,p4,p5,p6,p7,p8,p9,p10,p11,p12" }} </head> <center> {% for c in datachart %} <div id='p{{forloop.counter}}' style="height: 40%; width: 80%"> </div> {% endfor %} </center> -
Django - list items based on a foreign key
I am a new to python, Django (and programming in general). I have spend over 10 hours on this problem, but I seem to be missing something. I have two models in Django - articles and categories, and I am using ListView and DetailsView in my views.py file. On the articles_details page, I am trying to list all the articles that are in the same category as the current article. I have tried a million things, but to no avail. I am thinking that I could define a function using __exact to filter the categories database, based on the current value of articles.category (the category of the current article). I am not sure how to do so, though, and how to call such a function in my template. Could someone please assist? Thank you, in advance. P.S.: Not sure if part of the problem is using ListView and DetailsView. Here is my code: Views.py from django.shortcuts import render from web import models from web.models import Main, Series_rh, Articles_rh from django.views.generic import View,TemplateView,ListView,DetailView class IndexView(TemplateView): template_name = 'web/index.html' class CategoriesView(ListView): model = models.Series_rh template_name = 'web/series.html' context_object_name = 'Categories_rh_list' class CategoriesView(DetailView): model = models.Series_rh template_name = 'web/series.html' context_object_name = 'Categories_rh_details' class … -
How to dynamically specify the name of a static file?
I have a report.html template in which I need to dynamically change the name of images. I've done a lot of research and trial and error. But I just can't get the URLs for the images to be correct. The images are in /templates/users/reports/rptemplate/images. After researching static images, I also copied the images to: /static/images. Here's my latest html: <?xml version="1.0" encoding="UTF-8"?> {% load staticfiles %} <html> ... <img alt="" src="static/images/{{img_vision}}"> ... This is my report view: class UserReportView(LoginRequiredMixin, TemplateView): model = User template_name = 'users/reports/rptemplate/report.html' def get_context_data(self, **kwargs): #context = super(DisplayTaskView, self).get_context_data(kwargs) #TODO: retrieve the actual data context = {'sid': 519893, 'church_name': 'Lakeview Bible', 'report_date': '5 Feb 2018', 'responses': 57, 'img_vision': 'image1.png', 'img_leadership': 'image1.png', 'img_mobilization': 'image1.png', 'img_stewardship': 'image1.png', 'img_context': 'image1.png', 'img_evangelism': 'image1.png', 'img_discipleship': 'image1.png', 'img_service': 'image1.png', 'img_fellowship': 'image1.png', 'img_worship': 'image1.png', 'img_category': 'image1.png', 'img_radar': 'image1.png' } return context And this is my user/url.py: from django.conf.urls import url from django.views.generic import TemplateView from django.contrib.staticfiles.urls import staticfiles_urlpatterns from . import views urlpatterns = [ url( regex=r'^$', view=views.UserListView.as_view(), name='list' ), url( regex=r'^~redirect/$', view=views.UserRedirectView.as_view(), name='redirect' ), url( regex=r'^(?P<username>[\w.@+-]+)/$', view=views.UserDetailView.as_view(), name='detail' ), url( regex=r'^~update/$', view=views.UserUpdateView.as_view(), name='update' ), url( regex=r'^reports/rptemplate/$', view=views.UserReportView.as_view(), name='report' ), ] urlpatterns += staticfiles_urlpatterns() So where is my mistake? How do I dynamically … -
Django: NoReverseMatch in html
I am always getting this error in detail.html Reverse for 'vote' with arguments '('',)' not found. 1 pattern(s) tried: ['polls\\/(?P<question_id>[0-9]+)\\/$'] the detail.html is <h1>{{ question.question_text }}</h1> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'detail' question.id%} " method="post"> {% csrf_token %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br /> {% endfor %} <input type="submit" value="Vote" /> </form> and my polls.url.py is urlpatterns = [ path('', views.index, name='index'), path('<int:question_id>/', views.detail, name='detail'), path('<int:question_id>/results/', views.results, name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] The issue is that I have a similar code <a href = "{% url 'vote' question.id %}"> in index.html, it will work. The project directory is here enter image description here -
Celery task blocked in Django view with a AWS SQS broker
I am trying to run a celery task in a Django view using my_task.delay(). However, the task is never executed and the code is blocked on that line and the view never renders. I am using AWS SQS as a broker with an IAM user with full access to SQS. What am I doing wrong? Running celery and Django I am running celery like this: celery -A app worker -l info And I am starting my Django server locally in another terminal using: python manage.py runserver The celery command outputs: -------------- celery@LAPTOP-02019EM6 v4.1.0 (latentcall) ---- **** ----- --- * *** * -- Windows-10-10.0.16299 2018-02-07 13:48:18 -- * - **** --- - ** ---------- [config] - ** ---------- .> app: app:0x6372c18 - ** ---------- .> transport: sqs://**redacted**:**@localhost// - ** ---------- .> results: disabled:// - *** --- * --- .> concurrency: 4 (prefork) -- ******* ---- .> task events: OFF --- ***** ----- -------------- [queues] .> my-queue exchange=my-queue(direct) key=my-queue [tasks] . app.celery.debug_task . counter.tasks.my_task [2018-02-07 13:48:19,262: INFO/MainProcess] Starting new HTTPS connection (1): sa-east-1.queue.amazonaws.com [2018-02-07 13:48:19,868: INFO/SpawnPoolWorker-1] child process 20196 calling self.run() [2018-02-07 13:48:19,918: INFO/SpawnPoolWorker-4] child process 19984 calling self.run() [2018-02-07 13:48:19,947: INFO/SpawnPoolWorker-3] child process 16024 calling self.run() [2018-02-07 13:48:20,004: INFO/SpawnPoolWorker-2] child process … -
Why won't save_model override allow HttpResponseRedirect()?
I'm trying to add an intermediate confirmation page while saving a model that is conditional based on variables of the object being saved. ex, if object status is draft and the change will be to live, trigger confirmation. Else any other status, just save with no intermediate confirmation. I added admin.ModelAdmin to my models admin class: class SurveyAdmin(SimpleHistoryAdmin, admin.ModelAdmin): And I'm trying to override save_model to test conditions and add confirmation if need: @csrf_protect_m @transaction.atomic def save_model(self, request, object_id=None, form_url='', extra_context=None): survey = Survey.objects.get(pk=object_id.id) def response_add(self, request, obj, post_url_continue=None): if request.method == 'POST' and 'confirm' in request.POST: # do the thing return HttpResponseRedirect(reverse('admin:survey_change', args=(survey.pk,))) else: context = { 'title': _('Make live'), 'is_popup': False, 'opts': self.model._meta, 'app_label': self.model._meta.app_label, 'object': survey, } return TemplateResponse( request, 'admin/survey/make_live_confirmation.html', context) The problem: It seems save_model ignores my HttpResponseRedirect AND my TemplateResponse returns. I have this exact process working on other methods inside admin.py, but they are not overrides, they are custom definitions. Any ideas why save_model won't let me take control of the returns? -
Difference between reverse() and reverse_lazy() in Django
I understand that we can use reverse() in FBV and reverse_lazy() in CBV. I understand that we have to use reverse_lazy() in CBV as the urls are not loaded when the file is imported. Ref: Reverse_lazy and URL Loading? What I don't understand is - How are urls are loaded when we call reverse from the FBV? As when we import the views at the top of the urls.py in django app, urlpatterns list is yet to be evaluated. How does reverse() for FBV work but not for CBV? Does my question makes sense?? :P Thanks in advance. Regards. -
Uploading files POST urls raise 404 when deploy
I'm deploying a django app on a host with apache and cPanel. I think I did all the steps that django needs to deploy. Everything works fine except some posts urls. When I'm sending a form via post, and one of its fields is a File that will be uploaded to a directory, the server responses me 404, even from the admin add urls. Some info: Python 3.5, Django 1.11.9 Error: 404 Not Found When: sending any post form containing a Choose File field, even if the file isn't mandatory. The forms without files in their fields work fine. In production everything works perfect. I have a symlink in the public_html folder to my media and static folders and yes, I wrote multipart in the form and I guess admin app did it to. This is my code: urls.py urlpatterns = i18n_patterns( url(r'^admin/', admin.site.urls), url(r'^i18n/', include('django.conf.urls.i18n')), url(r'^', include('myapp.urls')), prefix_default_language=False) settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' This is my first time hosting a website, so, sorry if I'm asking a dummy question, but I couldn't find any solution, even here. Also, sorry for my English. Thanks for the future answers -
Django: best practice to minify HTML to improve page speed loading
Its about results in https://developers.google.com/speed/pagespeed/insights/ Probably it is pretty much to just globally wrap whole HTML with {% spaceless %} tag? Or it is not safe and there are some better ways?