Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to uninstall an older django version from virtual environment?
I have created a virtual environment on my computer using conda . conda create --name myDjangoEnv django It installed django version 2.0.5 Then when I upgraded to a new django version(2.1) in the same environment , both of the django versions were showing up . I also tried uninstalling the old version using the pip command pip uninstall django==2.0.5 It is pointing to the new installation saying django 2.1 will be unistalled . How to remove the old version and use the new one ? -
Django crash - Segmentation fault: 11 on macOS
I'm installing an existing Django project on a new mac. I'm having troubles with a Segmentation Fault: 11, only on part of the project which implements i18n translations. The segfault is intermittent (segfault occurs after 1, 2 or 3 page loading, no consistancy) The project is running great in an other mac and on Debian. Python3.7, Django 2.1 Here's the log from OS X High Sierra, any ideas ? Process: python3.7 [2972] Path: /Users/USER/*/python3.7 Identifier: python3.7 Version: ??? Code Type: X86-64 (Native) Parent Process: bash [1020] Responsible: python3.7 [2972] User ID: 501 Date/Time: 2018-08-07 13:50:15.936 +0200 OS Version: Mac OS X 10.13.6 (17G2208) Report Version: 12 Bridge OS Version: 2.4.1 (15P6703) Anonymous UUID: 4319F0E9-1882-BC12-95FB-566093869996 Sleep/Wake UUID: DC145697-3583-415B-826B-FEEFC191ABE4 Time Awake Since Boot: 4100 seconds Time Since Wake: 3300 seconds System Integrity Protection: enabled Crashed Thread: 0 Dispatch queue: com.apple.main-thread Exception Type: EXC_CRASH (SIGSEGV) Exception Codes: 0x0000000000000000, 0x0000000000000000 Exception Note: EXC_CORPSE_NOTIFY Termination Signal: Segmentation fault: 11 Termination Reason: Namespace SIGNAL, Code 0xb Terminating Process: python3.7 [2972] Thread 0 Crashed:: Dispatch queue: com.apple.main-thread 0 libsystem_kernel.dylib 0x00007fff547d848a __kill + 10 1 org.python.python 0x000000010079580c os_kill + 57 2 org.python.python 0x00000001006bcf42 _PyMethodDef_RawFastCallKeywords + 525 3 org.python.python 0x00000001006bc4af _PyCFunction_FastCallKeywords + 44 4 org.python.python 0x000000010075310e call_function + 467 … -
Apache Error: No module named django
I'm getting the following error in my apache error log on a Django project (python 3.6). mod_wsgi (pid=25096): Target WSGI script '/var/www/statmetrix/africafa/wsgi.py' cannot be loaded as Python module. mod_wsgi (pid=25096): Exception occurred processing WSGI script '/var/www/statmetrix/africafa/wsgi.py'. Traceback (most recent call last): File "/var/www/statmetrix/africafa/wsgi.py", line 12, in <module> from django.core.wsgi import get_wsgi_application ImportError: No module named 'django' I've checked and django is definitely where I would expect it. This is my conf file: <VirtualHost *:80> ServerAdmin henry@hexiawebservices.co.uk ServerName statmetrix.hexiawebservices.co.uk ServerAlias www.statmetrix.hexiawebservices.co.uk DocumentRoot /var/www/statmetrix WSGIDaemonProcess stametric python-path=/var/www/statmetrix python-home=/var/www/statmetrix/env/lib/python3.6/site-packages WSGIProcessGroup statmetrix WSGIScriptAlias / /var/www/statmetrix/africafa/wsgi.py Alias /robots.txt /var/www/statmetrix/static/robots.txt Alias /favicon.ico /var/www/statmetrix/static/favicon.ico Alias /media/ /var/www/statmetrix/media/ Alias /static/ /var/www/statmetrix/static/ <Directory /var/www/statmetrix/static> Require all granted </Directory> <Directory /var/www/statmetrix/media> Require all granted </Directory> WSGIScriptAlias / /var/www/statmetrix/africafa/wsgi.py <Directory /var/www/statmetrix/africafa> <Files wsgi.py> Require all granted </Files> </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> This is a Ubuntu 16.04 VPS running Python3.5 while the project is 3.6 (I'm not sure if this could be the issue?). Any help, most welcome. -
Combine SAML mapping with Djangosaml2
I have at least 2 Django apps I'm using with a SAML SSO using simpleSAMLphp as IDP and Djangosaml2 as SP. In general auth is working, despite some issues not relevant for this issue. Both apps are using a different user model. This is the SAML mapping I use for one app: SAML_ATTRIBUTE_MAPPING = { 'uid': ('username', ), 'mail': ('email', ), 'givenName': ('first_name', ), 'sn': ('last_name', ), 'is_staff': ('is_staff', ), 'is_superuser': ('is_superuser', ), } And here for the other SAML_ATTRIBUTE_MAPPING = { 'mail': ('email', ), 'givenName': ('nick', ), 'sn': ('name', ), 'is_staff': ('is_staff', ), 'is_superuser': ('is_superuser', ), } This is working ok. But the fields are not what they are meant for. What I would like to achieve is to combine givenName and sn into a single value which I can save in the name field of the user model. Looking at the Djangosaml2 docs, it mentioned a signal which could be used for it from djangosaml2.signals import pre_user_save def custom_update_user(sender=User, instance, attributes, user_modified, **kargs) ... return True # I modified the user object But i don't know where this should go, and how to work with the data this signal receives. Or does anyone know a better way to … -
wagtail AbstractImage, ParentalManyToManyField and ClusterableModel
Using wagtail 2.1, django 2.0.3, python 3.6.4 I have the following (simplified) custom image model, linked to PhotoType and PhotoPlate via m2m relationships: from wagtail.images.models import AbstractImage from modelcluster.fields import ParentalManyToManyField from modelcluster.models import ClusterableModel class PhotoType(models.Model): title = models.CharField(verbose_name='Title', max_length=255, blank=False, null=False, default=None) class PhotoPlate(models.Model): plate= models.CharField(verbose_name='Title', max_length=255, blank=False, null=False, default=None) class Photo(AbstractImage): type = ParentalManyToManyField(PhotoType, help_text="Several are allowed.", blank=True) plate = ParentalManyToManyField(PhotoPlate, help_text="Several are allowed.", blank=True) class Meta: verbose_name = 'Photo' verbose_name_plural = 'Photos' The PhotoType and PhotoPlate models are referenced via modeladmin_register(CCAPhotoTypeModelAdmin) and modeladmin_register(CCAPhotoPlateModelAdmin) in the local wagtail_hooks.py file. All works fine after following the documentation. Except for one thing: no matter how many items are selected in the multiple choice dropdown that are rendered for the two fields type and plate, the corresponding m2m relationship is never saved. I found a few answers, but could get it to work by playing with the inheritance of the Photo class, for example: class CCAPhoto(ClusterableModel, AbstractImage). Is there anyway to add a ParentalManyToManyField to a custom image model? If so, what am I missing? -
How to handle if a user forgets its username django
Is there a way to implement a method that if a user forgot its username(since it is used for login) he can get it through email? I have seen ways to reset password but I do not want user to reset its username but only get that through email. -
Django Custom User with Foreign Key. How to display foreign key in form?
I have the following two models: class CustomUser(AbstractUser): objects = CustomUserManager() class Meta: ordering = ['nin'] verbose_name = 'User' verbose_name_plural = 'Users' username = None name = models.CharField(max_length=50) nin = models.CharField(verbose_name= 'National Insurance Number', max_length=9, unique=True, null=False, blank=False, validators=[RegexValidator(regex='^[a-zA-Z]{2}[0-9]{6}[a-zA-Z]{1}$', message='National Insurance Number consists of two letters, followed by six numbers, followed by one letter.')]) email = models.EmailField(verbose_name='E-Mail', unique=True) id_document = models.FileField(verbose_name='ID Document', upload_to='user_id_documents', help_text='E.G. Scan of passport, driving licence etc.') address_document = models.FileField(verbose_name='Proof Of Address', upload_to='user_address_documents', help_text='E.G. Utility bill etc.') is_validated = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name', 'nin', 'id_document', 'address_document', 'is_validated'] class UserAddress(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.PROTECT) name_num = models.CharField(max_length=30, null=False, unique=False, blank=False) street = models.CharField(max_length=30, null=False, unique=False, blank=False) postcode = models.CharField(max_length=10, null=False, unique=False, blank=False) And the following two forms: class CustomUser(AbstractUser): objects = CustomUserManager() class Meta: ordering = ['nin'] verbose_name = 'User' verbose_name_plural = 'Users' username = None name = models.CharField(max_length=50) nin = models.CharField(verbose_name= 'National Insurance Number', max_length=9, unique=True, null=False, blank=False, validators=[RegexValidator(regex='^[a-zA-Z]{2}[0-9]{6}[a-zA-Z]{1}$', message='National Insurance Number consists of two letters, followed by six numbers, followed by one letter.')]) email = models.EmailField(verbose_name='E-Mail', unique=True) id_document = models.FileField(verbose_name='ID Document', upload_to='user_id_documents', help_text='E.G. Scan of passport, driving licence etc.') address_document = models.FileField(verbose_name='Proof Of Address', upload_to='user_address_documents', help_text='E.G. Utility bill etc.') is_validated = models.BooleanField(default=False) USERNAME_FIELD … -
Implementation of Social Oauth2 rest-framework for combining Django and social accounts
I am currently working on a login mechanism for the web application. This is the separation of the frontend (Vue) + Django DRF backend. And I wanted to use the django-rest-framework-social-oauth2 library to implement something identical that we can see eg in the Evernote application. The user can choose to start an account from scratch or login via Google. Ok, it's great that if I create an account on the Evernote website, I can immediately connect them to the Google account. It is in this case how such communication would look on the side of Vue - Django if I wanted to do it from the beginning based on REST My plan was as follows The user establishes an account by completing the registration form In this way I get a login, password, etc. in my django User table After logging in to the account, he sees his website and the option to connect from Facebook. After choose this option and send a query curl -X POST -d "grant_type=convert_token&client_id=&client_secret=&backend=&token=" http://localhost:8000/auth/convert-token Reply: { "access_token": "c3JQjkkAOx8d0ZSyEgP6Hyh2hX3R66", "expires_in": 36000, "token_type": "Bearer", "scope": "read write", "refresh_token": "7qawsbmQHgOv5vYjzorAXOeA0d2vla" } Of course, before that, you get an access token from facebook using the JS SDK .. … -
How can i change expiry_in parameter of token in oauth2 with django rest
curl -X POST -d "grant_type=password&username=&password=" -u":" http://localhost:8000/o/token/ -
Django Social Auth Facebook Valid URL callback
Since facebook does not allow URL requests from insecure (http) site to access it . I added http://example.com/oauth/complete/twitter/ and same for google they worked just fine . Now i tried to do same for facebook . I have the ssl certificate for the my site. I referred some questions here but it left me more confused . -
Django Channels - constantly send data to client from server
Please take a look at this example. As you can see, some sort of event is constantly being sent to the client. I want to imitate this using Django-Channels, inside consumers.py. Here's a simplified version of what I have: class ChatConsumer(AsyncConsumer): async def ws_connect(self, event): self.send = get_db_object() .... await self.send({ "type": "websocket.accept" }) # I need to CONSTANTLY receive & send data async def ws_receive(self, event): obj = ...# query DB and get the newest object json_obj = { 'field_1': obj.field_1, 'field_2': obj.field_2, } await self.send({ "type": "websocket.send", "text": json.dumps(json_obj) }) @database_sync_to_async def get_db_object(self, **kwargs): return Some_Model.objects.get(**kwargs)[0] Here, I want my Django backend to constantly: Query DB Receive obj from DB Send the received obj to Front-End websocket as event How can I achieve this? The important thing is that I need to CONSTANTLY send data to client. Most of the Django-Channels resources on the internet covers only Chat Apps, which doesn't necessarily constantly send data to client. I couldn't find any working codes that does this job. Please, no more recommendation for redis or channels documentation... or some random 3rd party libraries that lacks good documentation.... It's easy to recommend but hard to implement. However, if there's an … -
WSGI Error in apache2 using Two different python version (Django App)
I am trying to set up two Django app on Apache2 server in ubuntu using different python version(2.7 and 3.5). apache conf: WSGIDaemonProcess site1 display-name=%{GROUP} WSGIScriptAlias /site1 /var/www/bigb/site1/site1/wsgi.py <Location /site1> WSGIProcessGroup site1 WSGIApplicationGroup %{GLOBAL} </Location> WSGIDaemonProcess vdms display-name=%{GROUP} WSGIScriptAlias /vdms /var/www/bigb/vdms/vdms/wsgi.py <Location /vdms> WSGIProcessGroup vdms WSGIApplicationGroup %{GLOBAL} </Location> <Location /site1> WSGIProcessGroup site1 WSGIApplicationGroup %{GLOBAL} </Location> <Directory /var/www/bigb/vdms/vdms> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /var/www/bigb/site1/site1> <Files wsgi.py> Require all granted </Files> </Directory> Wsgi.py file for site1: from django.core.wsgi import get_wsgi_application sys.path.append('/var/www/bigb/site1') sys.path.append('/var/www/bigb/site1/venv/lib/python3.6/site-packages') os.environ["DJANGO_SETTINGS_MODULE"]= "site1.settings" application = get_wsgi_application() Wsgi.py file for vdms: from django.core.wsgi import get_wsgi_application sys.path.append('/var/www/bigb/vdms') sys.path.append('/var/www/bigb/vdms/venv/lib/python2.7/site-packages') os.environ["DJANGO_SETTINGS_MODULE"]= "vdms.settings" application = get_wsgi_application() When i tried to run apache server i can able to access site1 , but when i tried to load vdms I get internal server error raise RuntimeError("populate() isn't reentrant") [Tue Aug 07 11:25:03.426115 2018] [wsgi:error] [pid 12920] [remote 192.168.1.14:57874] RuntimeError: populate() isn't reentrant [Tue Aug 07 11:25:03.426095 2018] [wsgi:error] [pid 12920] [remote 192.168.1.14:57874] apps.populate(settings.INSTALLED_APPS) [Tue Aug 07 11:25:03.426100 2018] [wsgi:error] [pid 12920] [remote 192.168.1.14:57874] File "/usr/local/lib/python3.5/dist-packages/django/apps/registry.py", line 81, in populate I have installed both libapache2-mod-wsgi-py3 and libapache2-mod-wsgi on my system and I have installed mod_wsgi in venv also. Is there any configuration error Do i made. … -
Case() in Django return a Type error
I'm trying to use a huge request to minimize the number of requests in my app. In my database I have some cards, each card has multiple amounts link to it, and each amount is linked to a category. I try to get the Sum of amounts for a category between 2 dates and the same thing for 2 previous dates (dates are in cards) compare them and get the percentage evolution. Everything works fine for all cases but one: If my sum for a category is 0 for the previous period, I have an error "Divide by 0" when I try to calculate the evolution. So I tried to get the evolution, only if the sum of the previous period is != 0, for this I use Case(When()). But I have an error and I'm not sure to understand why. Here my request: categories = Category.objects.filter( Q(amount__card__date__range=( start_day_compare, stop_day_compare )) | Q(amount__card__date__range=( previous_start_day_compare, previous_stop_day_compare )) ).annotate( somme=Sum( 'amount__amount', filter=Q( amount__card__date__range=( start_day_compare, stop_day_compare ) ) ), evolution=Case( When( Sum( 'amount__amount', filter=Q( amount__card__date__range=( previous_start_day_compare, previous_stop_day_compare ) ) ) != 0, then=Value( ( ( Sum( 'amount__amount', filter=Q( amount__card__date__range=( start_day_compare, stop_day_compare ) ) ) - Sum( 'amount__amount', filter=Q( amount__card__date__range=( previous_start_day_compare, previous_stop_day_compare ) ) … -
Count How much post User have
hey i've got little problem i want to count specific user how much post have i already tried this things here is my view.py def home(request): numb = Post.objects.filter(author=user).count() here is models.py class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=150) is there anything i need to write here more ? after it i am getting error message user is undefined -
how to get year from datefield at django?
i want to get year from birthday. so i use self.birthday.year but it make error. how do i fix it? best regards. class User(AbstractUser): # First Name and Last Name do not cover name patterns # around the globe. name = models.CharField(_("Name of User"), blank=True, max_length=255) #이름 gender = models.CharField(max_length=1, choices=CHOICES_GENDER) # 성 birthday = models.DateField(null=True) #생일 def calculate_age(self): import datetime return int((datetime.date.year - self.birthday.year) +1) age = property(calculate_age) #나이 -
Apache conf file for Django app not working
I have the following .conf file for an apache server to run a Django application. <VirtualHost _default_:443> ServerAdmin webmaster@hexiawebservices.co.uk ServerName statmetrix.hexiawebservices.co.uk ServerAlias www.statmetrix.hexiawebservices.co.uk DocumentRoot /var/www/statmetrix WSGIDaemonProcess statmetrix-ssl python-path=/var/www/statmetrix python-home=/var/www/statmetrix/env/lib/python3.6/site-packages WSGIProcessGroup statmetrix-ssl WSGIScriptAlias / /var/www/statmetrix/africafa/wsgi.py Alias /robots.txt /var/www/statmetrix/static/robots.txt Alias /favicon.ico /var/www/statmetrix/static/favicon.ico Alias /media/ /var/www/statmetrix/media/ Alias /static/ /var/www/statmetrix/static/ <Directory /var/www/statmetrix/static> Require all granted </Directory> <Directory /var/www/statmetrix/media> Require all granted </Directory> WSGIScriptAlias / /var/www/statmetrix/africafa/wsgi.py <Directory /var/www/statmetrix/africafa> <Files wsgi.py> Require all granted </Files> </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> I am just getting the Default Apache page. The Django application is in /var/www/statmetrix and the wsgi.py file is in the right place. I have run a2ensite and I'm using certbot for SSL. Why isn't it picking up the application? -
Django - Nothing happens when "submit" button is clicked in a ModelForm?
Ok, so I am making a project, where you can make new blogposts and edit existing blogposts in Python with Django, but when I want to make a new post on my website, the "submit" button in new_post.html does nothing when I press it. I fill in the 'title' field and I fill in the 'text' field from the ModelForm "BlogPostForm" and press the button. In the terminal there's no POST or GET request. I just don't know why? I'm using Python 3.6.4 and Django 2.1, installed in a virtual environment created by the "venv" module. models.py: from django.db import models class BlogPost(models.Model): """A blogpost on the Home Page.""" title = models.CharField(max_length=300) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Return a string representation of the model.""" return self.title forms.py: from django import forms from .models import BlogPost class BlogPostForm(forms.ModelForm): class Meta: model = BlogPost fields = ['title', 'text'] labels = {'title': '', 'text': ''} widgets = {'text': forms.Textarea(attrs={'cols': 80})} views.py: from django.shortcuts import render from django.http import HttpResponseRedirect from django.urls import reverse from .models import BlogPost from .forms import BlogPostForm def index(request): """The Home Page for Blogs.""" blogs = BlogPost.objects.order_by('title') context = {'blogs': blogs} return render(request, 'blogs/index.html', context) def … -
how to find the latest documents with some condtions in MongoDB in python3?
Im writing a program in python and i have a collection in my mongodb database with documents that each contains an id, a timestamp, an ip string and a status string like this : { "_id" : ObjectId("5b0edbb1094464505f1d2ce3"), "id" : 20, "ip" : "172.21.45.225", "port" : 300, "status" : "closed", "time" : ISODate("2018-05-30T17:13:21.308Z") } by the way im using pymongo and djongo plug-in to connect my Django code to the database... what i want to do is to select the records with status "open" for every diffrent ip which the record is the latest for that ip. i come up with this solotion with sql but dont know how to do it in python and mongodb.. sql equivalent : select r1.* from myRecords r1, myRecords r2 where r1.status = "open" and r1.ip = r2.ip and r1.time > r2.time -
Django Include() in urls.py with two apps
I believe this is a simple question but I am having a hard time figuring out why this is not working. I have a django project and I've added a second app (sales). Prior to the second app, my urls.py simply routed everything to the first app (chart) with the following: urlpatterns = [ path('admin/', admin.site.urls), path('', include('chart.urls')), ] and it worked fine. I have read the docs over and over a looked at many tutorials, so my impression is that I can simply amend the urls.py to include: urlpatterns = [ path('admin/', admin.site.urls), path('sales/', include('sales.urls')), path('', include('chart.urls')), ] and it should first look for a url with sales/ and if it finds that then it should route it to sales.urls, and if it doesn't find that then move on and route it to chart.urls. However, when I load this and type in 127.0.0.1:8000/sales, it returns the following error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/sales/ Raised by: chart.views.index which tells me that it is not routing my sales/ url to sales.urls but to chart.urls. When I change path('', include('chart.urls')), to path('', include('sales.urls')), it does route it to sales.urls so I know that my sales.urls file is … -
writing a for loop for each individual case of a models field using a queryset of models
So, basically in my program i have a cart, then payments which have a Foreign key of "cart" now my cart has a price and each payment has an amount, so a user can pay in multiple payments for a cart. I've been asked to write a page that totals up the amount of all payments which are linked to a specific order then display the carts that haven't been fully paid yet, so i need to write a for loop that is basically foreach unique cart_id in payments.cart_ids compare cart_id.price to sum(payments.amount where payments.cart_id = cart_id) any idea on how to actually go about this? -
Add hour and minute to a django DateTimeField already saved
Here is my model : futureEventDate = models.DateTimeField(null=True, blank=True) And now i'am setting futureEventDate : eventSub.futureEventDate = datetime.datetime.strptime( formEvent["futureEventDate"], "%m/%d/%Y" ).date() But now that it's done i would like to specify hour and minute to eventSub.futureEventDate. How to do that ? -
Js/Jquer: Trying to get data-price for multiselect input
I'm trying to get the price and the value of the selected options of a multiselect input using JavaScript and Jquery, and to display those in a list. PS: I'm using Django and Python to generate the options Here is my html code : <div class="form-group none" id="10"> <label for="others">Choose other options</label> <select class="form-control" id="others" name="others" multiple="true" data-live-search="true"> {% for other in others %} <option value="{{ other.name }}" data-id="{{ other.id }}" data-price="{{ other.price }}">{{ other.name }} + {{ other.price }}€</option> {% endfor %} </select> </div> <ul id="others_list"></ul> Here is what I've tried in Js/Jquery : function get_others_name(select) { var result = []; var options = select && select.options var opt; for (var i = 0, iLen=options.length; i<iLen; i++) { opt = options[i]; if (opt.selected) { result.push(opt.value) } } return result; } function get_price(value) { var el = document.querySelector("#others option[value='" + value + "']") var price = el.dataset.price return price; } var others = document.getElementById("others"); others.onchange = function() { cal_total() var list = $("#others_list") var select = document.getElementById("others") list.empty() var options = get_others_name(select) options.forEach((element, index, array) => { var other_price = get_price(element); console.log(other_price) list.append("<li style='list-style-type: none;'>" + element + " + " + other_price + "€" + "</li>") }); } Unfortunately, … -
Shapefile to PostGIS import generates django datetime error
Hi I'm trying to populate the PostGIS database of my Django application using a Shapefile. My models.py is the following : class Flow(models.Model): # Primary key flow_id = models.AutoField("ID, flow identifier", primary_key=True) # Other attributes stime = models.DateTimeField("Start time") stime_bc = models.IntegerField("Year of start time before Christ") stime_unc = models.DateTimeField("Start time uncertainty") etime = models.DateTimeField("End time") etime_bc = models.IntegerField("Year of end time before Christ") etime_unc = models.DateTimeField("End time uncertainty") final_vers = models.BooleanField("1 if it's the final version, else 0", default=False) com = models.CharField("Comments", max_length=255) loaddate = models.DateTimeField("Load date, the date the data was entered " "(in UTC)") pubdate = models.DateTimeField("Publish date, the date the data become " "public") cb_ids = models.ManyToManyField(Bibliographic) # Foreign key(s) fissure_id = models.ForeignKey(Fissure, null=True, related_name='flow_fissure_id', on_delete=models.CASCADE) cc_load_id = models.ForeignKey(Contact, null=True, related_name='flow_cc_id_load', on_delete=models.CASCADE) cc_pub_id = models.ForeignKey(Contact, null=True, related_name='flow_cc_id_pub', on_delete=models.CASCADE) # Override default table name class Meta: db_table = 'flow' I want to add the features of my coulees.shp Shapefile into my database (more precisely in the flow table). The attribute table looks like this: Atribute table To do so I use the Django Layer Mapping: import os from django.contrib.gis.utils import LayerMapping from .models import Flow mapping = {'stime':'stime', 'stime_bc':'stime_bc', 'stime_unc':'stime_unc', 'etime':'etime', 'etime_bc':'etime_bc', 'etime_unc':'etime_unc', 'com':'com', 'loaddate':'loaddate', 'pubdate':'pubdate', 'geometry':'geometry'} … -
No module named 'pyrebase' in heroku python app
I'm trying to upload my django website to heroku platform but i got error: no module named pyrebase I'm trying to connect my django app with firebase API wrapper which "pyrebase". Everything is wroking well locally but when i upload it to my app on heroku it show me that message and when tried to see what is really inside python3.6/site-packages there was no such package. By the way, i'm already using requirement.txt in my project directory to install a 3rd party as packages in python and also pyrebase 3.* is included in this file but when i navigatei got that error!. Is there is a way i can install pyrebase to site-package directory in heroku python app? You can check it by yourself here: https://thegate1.herokuapp.com Thanks in advance.. -
Reverse smallest currency unit
In order to use stripe with my Django application, I am using the following code snippet to transform e.g. 523.34 USD into 52334 CENTS. Currently, I have to handle a webhook sent from Stripe and therefore I have to reverse this. Meaning 52334 CENTS into 523.34 USD. I am a bit stuck with that and wonder if anyone could help me how I can reverse this calculation with my funciton: def smallest_currency_unit(large_currency_amount, iso_code): iso_code = iso_code.upper() exponent = iso4217.Currency(iso_code).exponent if exponent == 0: # 0 signals unused/nonexistent minor currency return int(large_currency_amount) return int(large_currency_amount * (10 ** exponent))