Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 2.0 page not found, url patterns did not match
I just upgraded my django project from 1.8.5 to 2.0.6 version. I am able to go into the index page, but any other link gives me a 404 page. enter image description here. What are the problems? Great thanks beforehand. Here is part of my urls.py from django.conf.urls import * from django.contrib import admin from django.contrib.admin.views.decorators import staff_member_required from . import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^historicalbackground/', views.historicalbackground, name="historicalbackground"), url(r'^organizations/$', views.organizations, name="Organizations page"), ] And here is the views.py from django.views.generic.base import TemplateView from django.http import HttpResponse, Http404, HttpResponseRedirect from django.template import RequestContext, loader, Context from django.template.loader import get_template from django.shortcuts import render, render_to_response, redirect from django.core import management, serializers from .models import Person, Place, Org, Relationship, Page, Manuscript, PendingTranscription from html.parser import HTMLParser from tempfile import * from .forms import ContactForm, ImportXMLForm, TranscribeForm from django.core.mail import EmailMessage, send_mail from django.views.generic import ListView, DetailView from django.urls import reverse def historicalbackground (request): return render(request, 'historicalbackground.html') def organizations(request): return render(request, 'organizations.html') -
Django restrict access to media files if user is not logged in
hello i have a website with user pictures and documents in there my question is how can i restrict access to the media files if user is not logged in if i visit that url ill get the user's profile pic. How to restrict that access? http://0.0.0.0:8000/media/img/1_profilepic.jpg -
Can't access project absolute url from inside Django Docker instance
I have a project started with cookiecutter-django and I'm currently adding WeasyPrint to serve some views as PDF files. This is working fine on development. cookiecutter-django is using Caddy as the HTTP server. I'm having errors on production due I can't access to files through its absolute URL. From inside the Django docker instance: curl https://myowndomain.com is not working. Output: curl: (7) Failed to connect to myowndomain.com port 443: Connection timed out curl https://www.google.com is working OK From outside the Django docker instance both curl commands are working OK, including. Is there something I need to set? Am I missing something? Thanks in advance! -
Django: Return array in subquery
I have a model Application that has many Judge objects assigned to it via ForeignKey. Each Judge will grade the Application. I want to return a list of Applications in a QuerySet along with an array of each of the score values. Here's how I"m trying to accomplish that: total_scores = Subquery( Judge.objects .filter( application=OuterRef('pk') ) .values_list( 'total_score', flat=True ) ) applications = Application.objects \ .annotate( score_array=total_scores ) But I get this error: more than one row returned by a subquery used as an expression The values_list should return an array of values, so i'm not sure why multiple rows are being returned from my subquery. Any pointers? Thanks. -
angularjs 6 python django rest framework crossdomain api call issue
I have configured django rest framework with python 3. And the API is working fine in postman. But am facing a cross domain issue, when I call this api through my angualar 6 project. OS: Mac OS I have included oauth2 for authentication. It works well with postman API Url: http://127.0.0.1:7777/api/v1/token/ Angular 6 website url: http://localhost:5000/#/login When I called this with angualrjs it shows the following error. Mozilla: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:7777/api/v1/token/. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Safari: Failed to load resource: Origin http://localhost:5000 is not allowed by Access-Control-Allow-Origin. XMLHttpRequest cannot load http://127.0.0.1:7777/api/v1/token/. Origin http://localhost:5000 is not allowed by Access-Control-Allow-Origin. Chrome: Failed to load http://127.0.0.1:7777/api/v1/token/: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:5000' is therefore not allowed access. python settings.py cors related parts: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.flatpages', 'widget_tweaks', 'rest_framework', 'oauth2_provider', 'corsheaders', ] + get_core_apps() SITE_ID = 1 ALLOWED_HOSTS = ['127.0.0.1'] CORS_ORIGIN_WHITELIST = ('localhost:5000') CORS_ORIGIN_ALLOW_ALL = True MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] I have also installed oscarcommerce, oauth2, django rest framework. I have configured three … -
How to improve the performance of a Django application across different geographic regions?
I have a Django application that is hosted on an AWS box located in the us-east-1 geographic region using Nginx and django-channels. Recently, I have had some users in the ap-southeast-1 region complain that my app is not very responsive. The app runs fine for me as I am using us-east-1. How can I detect poor performance in a region is happening before a user complains? What can I do to improve the app performance and user experience in the ap-southeast-1 timezone? Is there any way to test the performance in another geographic region as part of unit-testing or something similar? I have a feeling the answer for #2 will have something to do with: (A) Adding another web server in ap-southeast-1 and (B) caching, but I'm keen to hear if there are additional things I should be doing. However, I have no clue how to detect slow performance for other regions is happening in the first place or to test to ensure it does not happen again in the future. -
IOError: [Errno 2] The error does not go away
https://github.com/blobmon/simplechan I installed the above anonymous bulletin board and thought about making thread, but the following Ehler does not come out. Traceback (most recent call last): File "/home/user/simplechan/simplechan/venv/lib/python2.7/site-packages/flask/app.py", line 1997, in call return self.wsgi_app(environ, start_response) File "/home/user/simplechan/simplechan/venv/lib/python2.7/site-packages/flask/app.py", line 1985, in wsgi_app response = self.handle_exception(e) File "/home/user/simplechan/simplechan/venv/lib/python2.7/site-packages/flask/app.py", line 1540, in handle_exception reraise(exc_type, exc_value, tb) File "/home/user/simplechan/simplechan/venv/lib/python2.7/site-packages/flask/app.py", line 1982, in wsgi_app response = self.full_dispatch_request() File "/home/user/simplechan/simplechan/venv/lib/python2.7/site-packages/flask/app.py", line 1614, in full_dispatch_request rv = self.handle_user_exception(e) File "/home/user/simplechan/simplechan/venv/lib/python2.7/site-packages/flask/app.py", line 1517, in handle_user_exception reraise(exc_type, exc_value, tb) File "/home/user/simplechan/simplechan/venv/lib/python2.7/site-packages/flask/app.py", line 1612, in full_dispatch_request rv = self.dispatch_request() File "/home/user/simplechan/simplechan/venv/lib/python2.7/site-packages/flask/app.py", line 1598, in dispatch_request return self.view_functionsrule.endpoint File "/home/user/simplechan/simplechan/app/app/init.py", line 70, in start_thread return handler.handle_start_thread() File "/home/user/simplechan/simplechan/app/app/handler.py", line 252, in handle_start_thread img_verify_result = blob_handler.verify(app.config['UPLOAD_FOLDER']) File "/home/user/simplechan/simplechan/app/app/blobHandler.py", line 35, in verify verify_image_res = self.verify_image() File "/home/user/simplechan/simplechan/app/app/blobHandler.py", line 193, in verify_image self.filesize = BlobHandler.bytes_2_human_readable( self.save_tmp_image_and_return_img_size() ) File "/home/user/simplechan/simplechan/app/app/blobHandler.py", line 202, in save_tmp_image_and_return_img_size self.blob_file.save( savepath_tmp ) File "/home/user/simplechan/simplechan/venv/lib/python2.7/site-packages/werkzeug/datastructures.py", line 2725, in save dst = open(dst, 'wb') IOError: [Errno 2] No such file or directory: '/user/home/simplechan/simplechan/app/app/images/tmp_1518974296579073.gif' Most of the work is done, update proper UPLOAD_PATH, DB_NAME, DB_ROLE, and hash values as required. I did not know how to edit the upper part, but edited the UPLOAD_PATH part of the appconfig part as follows. #Max … -
Heroku caching api responses [django/restframework]
Heroku seams to be caching api responses from my Django/RestFramework app. I have no caching mechanism enabled on restframework. Looking at the logs, I can see a error response (400) caused by a object not found, and, right before, the python stacktrace. Then I populate the object table and here happens the issue. On next requests, que error doesn't happen anymore, but the response is exactly the same 400 as before! Eventually, I get alternate 200/400 responses. The log with error: 2018-06-29T11:34:45.991094+00:00 app[web.1]: INFO 2018-06-29 08:34:45,990 dados: 1 [1/1] 6.34 Kb AGUARDANDO: importação síncrona iniciada 2018-06-29T11:34:46.044547+00:00 app[web.1]: UF Destino AC 2018-06-29T11:34:46.048998+00:00 app[web.1]: ERROR 2018-06-29 08:34:46,046 importacao_erp: Arquivo "1 [1/1] 6.34 Kb PROCESSANDO": icms[0]: objeto referenciado não existe (Uf matching query does not exist.) 2018-06-29T11:34:46.049002+00:00 app[web.1]: Traceback (most recent call last): 2018-06-29T11:34:46.049004+00:00 app[web.1]: File "/app/core/importacao_erp.py", line 123, in importacao 2018-06-29T11:34:46.049006+00:00 app[web.1]: method_save(dict(dados)) 2018-06-29T11:34:46.049008+00:00 app[web.1]: File "/app/core/importacao_erp.py", line 282, in save_icms 2018-06-29T11:34:46.049009+00:00 app[web.1]: uf_destino=Uf.objects.get(sigla=dados['uf_destino']), 2018-06-29T11:34:46.049011+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method 2018-06-29T11:34:46.049013+00:00 app[web.1]: return getattr(self.get_queryset(), name)(*args, **kwargs) 2018-06-29T11:34:46.049015+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 403, in get 2018-06-29T11:34:46.049016+00:00 app[web.1]: self.model._meta.object_name 2018-06-29T11:34:46.049022+00:00 app[web.1]: core.models.uf.DoesNotExist: Uf matching query does not exist. 2018-06-29T11:34:46.311674+00:00 app[web.1]: ERROR 2018-06-29 08:34:46,311 importacao_erp: Arquivo "1 [1/1] 6.34 Kb PROCESSANDO": clientes[0]: objeto … -
mongoengine default timeout configuration
I have a django project running on top of MongoDB via mongoengine. After I got inconsistent results for list querysets (object.filter() etc.) I've set the queryset to run without a timeout - by calling queryset.timeout(False) - and that seemed to solve the issue. My questions are: 1. What is the default timeout settings for mongoengine? 2. Is there a way to control the timeout configuration for mongoengine? -
How to properly serve my Angular application static files from a Django project on Heroku?
I am trying to deploy on Heroku my app built with Django 2, DRF and Angular 6, and struggling to get the static files of my Angular app served. I am using WhitheNoise for both development environment and on Heroku. The structure of the project is as follows: my_project/ |-frontend/ | |- dist/ | |- ... |-myproject/ | |-settings/ | | |- __init.py | | |- base.py | | |- prod.py | | |- dev.py | |- __init__.py | |- urls.py | |- views.py | |- wsgi.py |-other_app1/ | |- ... |-other_app2/ | |- ... |-staticfiles/ | |-.... |-manage.py |-Procfile |-requirements.txt I have configured Heroku in such a way that every time my app is deployed, my angular app is built, so the static files are generated in frontend/dist/, then collectstatic is run and copies them to my static files folder in the root of my project. My settings are: ANGULAR_APP_DIR = os.path.join(BASE_DIR, 'frontend/dist') STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = [ ('frontend', os.path.join(ANGULAR_APP_DIR)), ] This works fine and collects all the files of my angular app inside staticfiles/ withing a folder called frontend/ My problem is that now I am trying to serve the index.html file that … -
Wagtail CMS as backend for Single Page Application (SPA) - examples
Could you please provide some examples of successful implementation of Wagtail CMS as backend for Single Page Application (SPA)? Or perhaps there are none as this combination is simply inviable? My research so far was fruitless. With this little information it is ineffective to draw any solid conclusion. -
Encryption IV - C and Python equivalent
I have problems regarding initializing equivalent "initialization vectors" for the encryption of my message. I have an ESP32 (microcontroller) sending Data via JSON to a Django Server. On the ESP32 I use the Arduino IDE, so the code on the ESP32 is written in C/C++. Django of course is using Python. My encryption works so far if I intialiaze the IV like this on both sides: ESP32: unsigned char iv[16] = {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'}; Django: iv = b'0000000000000000' The library of the ESP32 has an encryption function which expects an unsigned char array. I have to pay attention that the array is not null-terminated ('\0' at the end) or i get different results. That are the background informations. you need. Now to my specific problem: I want to use counter mode in my encryption. I want to copy an integer-counter to the last 4 bytes of the IV on both sides: On the ESP32 I do: int msg_counter = 15 //15 just as an example memcpy(iv+12, &msg_counter, sizeof(msg_counter)); On Django I do: counter = (int) 15; iv = counter.to_bytes(16, byteorder = 'big') If I print out the variable "iv" I get this on Django: b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0f' The decryption fails. I dont get the … -
Django: After logging out if i press the back button will go back to the web page
here is my logout view since its redirecting to my home page, after clicking on the browser's back button will generate the page that was visited before. How can i prevent that from happening? def logout_page(request): logout(request) messages.success(request, msg_from_db('goodbye')) return HttpResponseRedirect('/') -
MYSQL query to access only column- header names
I want to display only my column names of a table, and not the other information. I tried the suggestions on other answers, but it didn't seem to work for me. The table is dynamic hence I can't access the fields beforehand. I am using a MYSQL database and my Django execute command is as follows: with connection.cursor() as cursor: cursor.execute('SHOW COLUMNS FROM %s' % table_name) column = cursor.fetchall() Can someone please help me figure out the change required to get only the column-header names, and not the entire information of the table. Help will be greatly appreciated. -
Object detection Django
My question is how i can detect objects in video after upload to django site and add data to sql database For example: If the video is anime it should store the video type to anime if the video is music it should store the video type to music -
Group By using Timestamp in Django Queryset
I have one model where each entry is stored and its created time is stored. The time is not a datetime object a timestamp. Timestamp field of model is shown below : logged_at = models.CharField(_('log time'), max_length=128, default=time.time) If above field is datetime field then I can write an query which can group by records using datetime field like : MyModel.objects.filter(type_='in').annotate(in_time=RawSQL('(date(logged_at))', [])).values('in_time', 'name').annotate(count=Count('name')) But I am not able to query the timesatmp field in same way , It gives me the error date/time field value out of range I have also tried to use functions like to_timestamp nut still no success MyModel.objects.filter(type_='in').annotate(in_time=RawSQL('(date(to_timestamp(logged_at)))', [])).values('in_time', 'name').annotate(count=Count('name')) Error : function to_timestamp(character varying) does not exist Database I am using is Postgres -
Django model to admin, integer fields and textfield are not visible in admin section
class Student(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) father_name = models.CharField(max_length=60) age = models.SmallIntegerField created = models.DateTimeField(auto_now=False, auto_now_add=True) modified = models.DateTimeField(auto_now=True, auto_now_add=False) address = models.TextField email = models.EmailField(default="") id = models.AutoField std = models.SmallIntegerField remarks = models.TextField I have created a model called Student and added it to Django admin and migrated it. There was no problem with migration. When I tried to add a new student via admin page, I am only getting following fields, How can I get integer fields like age in UI? -
Web interface for existing database
I am in a student bioinformatics internship now and I am in the last part of it: building a mySQL database and making a web interface for some users. I have three weeks to make the web interface. In the database, there is a lot of data (more than 100 millions), the user will have some filters to select and then, the interface should display the desired results. It should be simple, but I don't know what to use. Django ? R ? PHP ? There is no tools that pug the database in a simple interface ? Anyone can help please ? -
Why coverage is not showing error for generic views?
I am using coverage to check which unit tests to write. I'm checking in accounts/views.py, for which I haven't written in tests, but why it not showing in tests missing case? I expect around 50+ statements to be in error stage, excluding imports to write tests. But it's like 50% doesn't need any tests! coverage html for views -
How can I set the ForeignKey value in the view
My User registration form contains a ForeignKeyField and I am trying to set the value of this ForeignKeyField in the view. As can be seen in the code below, I am passing a parameter "pk" to the view and this parameter is for setting the ForeignKeyField value before the form is rendered, but this doesn't seem to work. After posting the form I get this error "(1048, "Column 'package_id' cannot be null")". Here is my View. def subscribe_view(request, billing_cycle, pk): if request.method == 'POST': userRegForm = CustomUserForm(request.POST) companyForm = CompanyProfileForm(request.POST) if userRegForm.is_valid() and companyForm.is_valid(): user = userRegForm.save() compProfile = companyForm.save(commit=False) if compProfile.user_id is None: compProfile.user_id = user.id compProfile.save() selected_provinces = companyForm.cleaned_data['provinces'] selected_cats = companyForm.cleaned_data['tenderCategory'] selected_package = companyForm.cleaned_data['package'] for province_item in selected_provinces: compProfile.provinces.add(province_item) for cat_item in selected_cats: compProfile.tenderCategory.add(cat_item) keyword_ids_str = companyForm.cleaned_data['keywordListItem'] if keyword_ids_str is not '' or keyword_ids_str is not None: keyword_ids = keyword_ids_str.split(',')[:-1] for keyword_id in keyword_ids: keywordObj = Keywords.objects.get(id=int(keyword_id.strip())) compProfile.keywords.add(keywordObj) compProfile.package(selected_package) return HttpResponseRedirect('/user_account/dashboard') else: return HttpResponseRedirect(request.path) else: packageOption = Packages.objects.get(id=pk) if billing_cycle == '1' or billing_cycle == '0': b_cycle = billing_cycle else: b_cycle = '0' userRegForm = CustomUserForm() companyProfileForm = CompanyProfileForm(initial={'package': packageOption.id}) bankingDetailsForm = BankingDetailsForm() #companyProfileForm.fields["package"].initial = packageOption.id args = {'userRegForm': userRegForm, 'package': packageOption, 'billing_cycle': b_cycle, 'companyProfileForm': companyProfileForm, 'bankingDetailsForm': … -
What for select_for_update in transaction atomic
Assuming there is already transaction.atomic(), what for do I need select_for_update. Is it would be enough simple update() \ save() like this: with transaction.atomic(): obj = MyModel.objects.get(value=value) obj.value += 10 obj.save() because it already IN transaction, why should I use select_for_update? -
Convert Html to PDF Python/Django
I’m working on a functionality where I need to convert a huge html file (size more than 1 mb) into pdf. I’ve tried below two open-source python libraries. 1. Xhtml2pdf (Pisa) 2. Weasyprint But none of them solves my problem as they take around 4-5 mins in generating 1 MB PDF file (around 500 pages) causing my app server’s worker process (Gunicorn and Nginx) to get down and throwing ‘GATEWAY TIMEOUT ERROR’ on browser. CPU utilization also goes up to 100% while PDF conversion is in process. If anybody is having any idea which API/library will be a best suit for large html files. -
How can i check dictionary value is available in list of dictionary in python?
I want to check whether the value of a exists in the value b or not a = [{ "shopid": "store4400013","prd_category": "Chicken","product_id":"4359197","prd_name":"Chicken chilli","prod_type":"Non_Veg","prd_amt":"100.0"}] b = [{'shopid': 'store4400013', 'prd_category': 'Chicken', 'product_id': 4359197, 'prd_name': 'Chicken chilli', 'prod_type': 'Non_Veg', 'prd_amt': 100.0, 'image': '/media/abhishek/e/Moneypay/merchant/mxuserimage/menu_3418906783.png'}, {'shopid': 'store4400013', 'prd_category': 'Chicken', 'product_id': 6911213, 'prd_name': 'Chicken kadai', 'prod_type': 'Non_Veg', 'prd_amt': 250.0, 'image': '/media/abhishek/e/Moneypay/merchant/mxuserimage/menu_3890935432.png'}] -
Django, translating field names in context of exceptions
I have a model with field that is called phone. In russian it will look like this: телефон Sometimes when I try to make queries application will throw me that kind of error messages: User with field phone already exists If I set LANGUAGE_CODE in settings to ru-RU, then I have add Meta class which has proper verbose name, previous exception will now throw that kind of message: Пользователь с таким телефон уже существует Which is not right. In context of this message the field phone should be called телефоном. It has extra letters in the end. In some languages, like russian, words will have different endings depending on context of sentence. I'm trying to use gettext and generated po file where it has these lines of code: #: .\main\models\users.py:77 msgid "phone" msgstr "" However, I don't know how to write multiple cases of translation in this code. Is it possible to make different cases of translation of field names? Is it possible to override not found error specially for this model? -
Django Error while trying to migrate model on Postgre DB
I'm still learning to use Django and I have an issue while trying to create a model. Here's my models.py class Identifiants(models.Model): id = models.AutoField(primary_key=True) taxon = models.IntegerField(unique=True) noms = models.TextField(blank=True, null=True) fiche = models.IntegerField(blank=True, null=True) comestible = models.TextField(blank=True, null=True) sms = models.NullBooleanField() a_imprimer = models.NullBooleanField() lieu = models.TextField(blank=True, null=True) apparition = models.TextField() class Meta: managed = True db_table = 'identifiants' The makemigrations command works with no issues but the migrate one is where I have problems Running migrations: Applying app.0001_initial...Traceback (most recent call last): File "/usr/lib/python3.5/site-packages/django/db/backends/utils.py", line 83, in _execute return self.cursor.execute(sql) psycopg2.DataError: NUMERIC precision 65535 must be between 1 and 1000 LINE 1: ...iants" ("id" serial NOT NULL PRIMARY KEY, "taxon" numeric(65... I'm using IntegerField method so I can't see why there is an issue ... Can anyone help me ? Thanks