Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How To Convert ISOFormated date to Python datetime?
I have a datetime string in the format 2017-08-30T10:21:45.337312+00:00 send from django server using timezone.localtime(timezone.now()).isoformat() I need to parse it back to a timezone object. How to do it? I tried the following but its not working kolkatta_tz = pytz.timezone("Asia/Kolkata") kolkatta_tz.localize(datetime.strptime(product_list[index][5], '%Y-%m-%dT%H:%M:%S.%fZ')) -
Django and formsets
I try to understand how the internal of Django formsets work. After a formset class is created by formset_factory function, inheriting/getting attributes from BaseFormSet, a object of the new created class is initialize, example: ArticleFormSet = formset_factory(ArticleFormA, extra=2) formset = ArticleFormSet() If I check with dir(formset) both form and forms attributes are available, but if I try to print forms nothing is printed, I suppose this is related to the decorator @cached_property(but when is called ?) In the initialization of the formset object there are no operations related to forms attribute. So, I suppose is called when {{formset}} or {{formset.as_p}} etc is called. The method has: forms = ' '.join(form.as_p() for form in self) Why in self, I don't understand, because form based on dir() is just a class, and self is the formset object. What is the logic behind ? (PS I understand what is doing going to every form), but is not form in forms, besides the fact forms is now populated And after that, the fields are created using management_form that before. return mark_safe('\n'.join([six.text_type(self.management_form), forms])) -
Getting no result when using cursor from django.db.connections
I'm basically trying to run the following query. In a custom sql statement. CREATE TEMPORARY TABLE input ( id serial, certified boolean ); INSERT INTO input (id, certified) VALUES (DEFAULT, True), (DEFAULT, False), (DEFAULT, True), (DEFAULT, False), (DEFAULT, True), (DEFAULT, False); CREATE OR REPLACE FUNCTION update_record(_input input) RETURNS input AS $$ UPDATE "tests_person" SET certified=_input.certified WHERE certified=_input.certified RETURNING _input.id, _input.certified $$ LANGUAGE SQL; WITH new_updated AS ( SELECT upd.* FROM input, update_record(input) as upd WHERE upd.id is not NULL ), except_updated AS ( SELECT * FROM input EXCEPT ALL SELECT * FROM new_updated ) SELECT id, certified FROM except_updated; The code for that looks like the following. from django.db import connections sql = '''the above sql code''' with connection.cursor() as cursor: cursor.execute(sql) row = cursor.fetchone() The sql throws no errors at all. But when trying to fetch a row I get no result at even though there should be results. I have the same sql in a fiddle here: http://sqlfiddle.com/#!17/48a30/75 In the fiddle I get some results from the last select statement: SELECT id, certified FROM except_updated; So not really sure why things get different when I try this out in django. For the record, I'm using postgres 9.6 and … -
Archive widget using CBV in django
I'm new to django and I do not know good practices. My problem is how to make a widget where I can select (dropdown) the month and year in which events will appear for that time? I care about doing this without using external packages and using CBV. I will be grateful for every hint. -
render() takes exactly 2 arguments (3 given) Django view while I want to pass varibale
I want to pass a variable to template when I get this error. I saw many stackoverflow answers but it tells , Django send Self by default that's why It saying I am sending 3 arguments. But whats the solution of it I am not getting Url.py url(r'^(?P<lid>\d+)/labels/$' , login_required(LayerView.as_view('ImportLabelView')), name='mapport.maps.layers.importlabel') view.py return self.render('mapport/maps/layers/Labels_detail.html' , {'lid': self.layer.id}) So how can I enable my 3rd argument to pass ? -
How can I build 'location auto-complete' like Facebook in Django?
How can I build 'location auto-complete' like Facebook? Should I send Ajax request everytime the user type a letter? For example, if user type 'atlanta', then how does Facebook check and find 'Atlanta, GA'? And How can I build the exact same thing in Django??? Thank you so much! -
django model manager or django queryset
I was reading django docs and these two classes seemed similar, here is the sample from django docs: class PersonQuerySet(models.QuerySet): def authors(self): return self.filter(role='A') def editors(self): return self.filter(role='E') class PersonManager(models.Manager): def get_queryset(self): return PersonQuerySet(self.model, using=self._db) def authors(self): return self.get_queryset().authors() def editors(self): return self.get_queryset().editors() class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) role = models.CharField(max_length=1, choices=(('A', _('Author')), ('E', _('Editor')))) people = PersonManager() In the sample code as you can see code in PersonQuerySet can be moved to PersonManager (or move manager to query set) - my point is I can merge one to another without any problem) so what is the difference between manager and queryset? do they have different use cases? or should I simply use one of them and ignore existance of the other one? -
Using PyMongo as Django backend
I'm writing an application with django and I want to use mongoDB as my database. I have searched around a lot and found mongoengine and Pymongo as possible choices. I have decided to got with PyMongo for the time being. But the thing is that I am unable to connect my app to mongoDB. I have tried following so far: from pymongo import MongoClient client = MongoClient() db = client['user_central'] But it doesn't work as it should. Something has to be put in the DATABASES django variable and that's where I'm caught up. How can I connect my django app to mongoDB and use mongo as my Django Backend?? Any help would be appreciated. -
Django MemoryError if degug = True
I am getting the following error when I make queries to my app throught custom forms: Environment: Request Method: GET Request URL: http://34.212.77.49/anagrafiche/insolventi/?anno=2010 Django Version: 1.11.4 Python Version: 3.5.2 Installed Applications: ['django_jinja', 'rest_framework', 'quotemanage', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'debug_toolbar'] Installed Middleware: ['debug_toolbar.middleware.DebugToolbarMiddleware', 'django.middleware.security.SecurityMiddleware', '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', 'quotemanage.middleware.customMiddleware.NavMenuMiddleware'] Traceback: File "/var/www/appWSGI/env/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/var/www/appWSGI/env/lib/python3.5/site-packages/django/utils/deprecation.py" in __call__ 142. response = self.process_response(request, response) File "/var/www/appWSGI/env/lib/python3.5/site-packages/debug_toolbar/middleware.py" in process_response 132. panel.generate_stats(request, response) File "/var/www/appWSGI/env/lib/python3.5/site-packages/debug_toolbar/panels/sql/panel.py" in generate_stats 192. query['sql'] = reformat_sql(query['sql']) File "/var/www/appWSGI/env/lib/python3.5/site-packages/debug_toolbar/panels/sql/utils.py" in reformat_sql 27. return swap_fields(''.join(stack.run(sql))) File "/var/www/appWSGI/env/lib/python3.5/site-packages/sqlparse/engine/filter_stack.py" in run 34. for stmt in stream: File "/var/www/appWSGI/env/lib/python3.5/site-packages/sqlparse/engine/statement_splitter.py" in process 82. for ttype, value in stream: File "/var/www/appWSGI/env/lib/python3.5/site-packages/debug_toolbar/panels/sql/utils.py" in process 14. for token_type, value in stream: File "/var/www/appWSGI/env/lib/python3.5/site-packages/sqlparse/lexer.py" in get_tokens 60. m = rexmatch(text, pos) Exception Type: MemoryError at /anagrafiche/insolventi/ Exception Value: I do not know if it is caused by an error somewhere in my code, however the Traceback is not giving me any idea! In my settins.py if a set DEBUG = False this error no longer exist. I have no idea what to do, I sure need to have my Debug option set to True. -
Can not add bootstrap class with button using Django and Python
I am trying to add bootstrap class in button using Django and Python but it could not added at all. I am explaining my code below. control.html: {% extends 'base.html' %} {% block content %} <center><h1>Welcome</h1> <div class="boxwidthdiv"> <form method="post" action="{% url 'plantsave' %}"> {% csrf_token %} <div class="boxwidthinnerdiv"> Nuclear Mini Plant <br /><br /> <select name="react"> <option value="Reactor1">Reactor 1</option> <option value="Reactor2">Reactor 2</option> <option value="Reactor3">Reactor 3</option> </select> <br /><br /><br /><br /> <button class="buttondiv" name="strt" type="submit" class="btn btn-success">Start</button> <button class="buttondiv" name="shutbt" type="submit" class="btn btn-danger">Shut Down</button> <button class="buttondiv" name="susbtn" type="submit" class="btn btn-info">Suspend</button> </div> </form> </div> {% endblock %} base.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> {% load static %} <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <script type="text/javascript" src="{% static 'js/bootstrap.min.js' %}"></script> </head> <body> <header> <h1>Nuclear Reactor</h1> {% if count > 0 %} <b>Hi, {{ user.username }}</b> <a href="{% url 'home' %}">Home</a> <a href="{% url 'view_reactor' %}">View Reactor status</a> <a href="{% url 'logout' %}">logout</a> {% else %} <a href="{% url 'login' %}">login</a> / <a href="{% url 'signup' %}">signup</a> {% endif %} <hr> </header> <main> {% block content %} {% endblock %} </main> </body> </html> Here I could not added the classes at all. Please help me to resolve … -
Django website with Wordpress
I have a website developed with Django. I want to add a blog to the website. If I choose Wordpress for the blog, can I unify the Wordpress blog with the Django website ? If yes, how ? The Wordpress blog can be access with this url : www.website-adress.com/blog ? Can be share the Django database with the Wordpress blog ? I read this : https://www.reddit.com/r/django/comments/39fzgc/wordpress_and_django_coexisting/ and someone speaking about configuration in nginx/apache level... (I am using Webfaction for the webhosting) Thank you ! -
Converting image data string (str) back into bytes
inputFile gets the image data from a image file input <input type="file"> and converts the data into a string (str) to be used in sessions. createView converts the image data string back into image data (bytes) so it can be saved. However when trying to convert the image data string back into image data bytes: session_data = request.session.get('img_data') data = base64.b64encode(bytes(session_data, 'utf-8')) data2 = base64.decodestring(data) It changes the original image data, img_data = request.FILES.get('image').read() witch raises an error when trying to save the image to a ImageField: cannot identify image file <django.core.files.temp.TemporaryFile object at 0x0074B110> so my question is how do i convert the image data string session_data = request.session.get('img_data') back into the original image data (bytes) without altering the data. And i know i could have saved the image using one view that would make it a lot simpler, but createView needs to use this image data in multiple places / forms. i tried doing it this way but i could only use the image data in one form. import base64 def inputFile(request): form = InputFile(request.POST or None, request.FILES or None) if form.is_valid(): img_data = request.FILES.get('image').read() request.session['img_data'] = str(img_data) return redirect('picxs:create') def createView(request): session_data = request.session.get('img_data') data = base64.b64encode(bytes(session_data, … -
queryset django for last value of column if another column is equal to a value
I have a django video model and i want to get the last value of "nameoriginalvideo" if owner id is equal to the current user id. This is my mysql table equivalent to the model: This is what i tried but it didn't work: def teste(request): originalvideo = Videounwtm.objects.values('nameoriginalvideo').filter(owner_id = request.user.id).first().last() vle = originalvideo['nameoriginalvideo'] return render(request, 'teste.html', {'vle': vle}) Thank you in advance. -
How can i edit the content on my django website pages?
I'm a newbie to django and i have worked on a few projects and in all of them i used the django admin interface to manage the content, which obviously is the content from my models.My main concern is how or rather is there a way i can edit the content in areas like the about section or on my home page without changing the actual html on my code? -
Send weekly emails for a limited time after sign up in django
The Goal: Once a user has signed up they start a challenge. Once they've started the challenge I'd like to be able to send users weekly emails for 12 weeks (Or however long the challenge lasts for). Bearing in mind, one user may sign up today and one may sign up in three months time. Each week, the email will be different and be specific to that week. So I don't want the week one email being sent alongside week 2 for 12 weeks. Should I add 12 boolean fields inside the extended User model, then run checks against them and set the value to True once that week gas passed? Assuming this is the case. Would i then need to setup a cron task which runs every week, and compares the users sign up date to todays date and then checks off the week one boolean? Then use the post_save signal to run a check to see which week has been completed and send the 'week one' email? I hope that makes sense and i'm trying to get my head around the logic. I'm comfortable with sending email now. It's trying to put together an automated process as currently … -
Nginx, WSGI, Django - setting up web server
I'm quite new to setting up a web server and have been following these guides: http://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html https://gist.github.com/evildmp/3094281 Since I'm working off a mac, I installed nginx through Homebrew: brew install nginx. I have been struggling to get my nginx server to serve my Django static file. I have followed the guides and have copied their mysite_nginx.conf and changed it according to my project paths: # mysite_nginx.conf # the upstream component nginx needs to connect to upstream django { # server unix:///path/to/your/mysite/mysite.sock; # for a file socket server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server { # the port your site will be served on listen 8000; # the domain name it will serve for server_name .example.com; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Django media location /media { alias /Users/Simon/Documents/WebServer/uwsgi-tutorial/mysite/media; # your Django project's media files - amend as required } location /static { alias /Users/Simon/Documents/WebServer/uwsgi-tutorial/mysite/static; # your Django project's static files - amend as required } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass django; include /Users/Simon/Documents/WebServer/uwsgi-tutorial/mysite/uwsgi_params; # … -
how to filter a django query set by a foreign key in restful framework?
i met a problem when using django + restful framework. here is my intention: there are many chapters, each chapter has many words, each word has many expand explanations, these explanations are offered by users, so some of them are invaild, in the backend i can set these expands' field is_alive to False. in the views.py, currently i send all these data to frontend, i tried many ways to filter these invaild data out, but failed. here are codes: models.py class Chapter(models.Model): chap = models.IntegerField('chaptername') class Word(models.Model): chapter = models.ForeignKey('Chapter', related_name='voca') word = models.CharField('name', max_length=255) class Expand(models.Model): belong = models.ForeignKey('Word', related_name='expand') explansion = models.TextField('description') is_alive = models.BooleanField('status', default=True) serializers.py class ExpandSerializer(serializers.ModelSerializer): class Meta: model = Expand fields = ('explansion', ) class WordSerializer(serializers.ModelSerializer): expand = ExpandSerializer(many=True) class Meta: model = Word fields = ('id', 'word', 'expand') class ChapterSerializer(serializers.ModelSerializer): voca = WordSerializer(many=True) class Meta: model = Chapter fields = ('id', 'chap', 'voca') views.py def getChapter(request): if request.method == 'GET': chapter = Chapter.objects.get(pk=1) serializer_c = ChapterSerializer(chapter) return JsonResponse(serializer_c.data) -
Database modeling for products and store with better category of products
I am planning to develop a virtual shopping mall where stores of any kind can be registered, such as in a physical shopping mall. First I want to develop an efficient and effective database modeling for products and stores only. I wanted it be very flexible and user friendly. Here is the model design for Product and Store. How can I improve the database design? My primary concern is for the categories be user friendly. For example Men -> Clothing -> Shirts as a category. If you wish, you can help me to improve the design as well, I would appreciate all recommendations. I am using Python 3 and Django 1.11. DAY = (( 'Sun', 'Sunday'), ( 'Mon', 'Monday'), ( 'Tue', 'Tuesday'), ( 'Wed', 'Wednesday'), ( 'Thu', 'Thursday'), ( 'Fri', 'Friday'), ( 'Sat', 'Saturday') ) class OpeningHours(models.Model): store = models.ForeignKey('Store', related_name="opening_hour") weekday = models.CharField(choices=DAY, max_length=12) opening_hour = models.TimeField() closing_hour = models.TimeField() class Meta: verbose_name = 'Opening Hour' verbose_name_plural = 'Opening Hours' def ___str__(self): return '{} {} - {}'.format(self.weekday, str(self.opening_hour), str(self.closing_hour)) class Store(models.Model): merchant = models.ForeignKey(User, blank=True, null=False) token = models.CharField(default=token_generator, max_length=20, unique=True, editable=False) name_of_legal_entity = models.CharField(max_length=250, blank=False, null=False) pan_number = models.CharField(max_length=20, blank=False, null=False) registered_office_address = models.CharField(max_length=200) name_of_store = models.CharField(max_length=100) email … -
AJAX call returns CSRF Failed
Iam doing an ajax call in Typescript which calls an internal Webservice. All endpoints whit "GET" are working, but whit "POST" it says "403 Forbidden" - "detail: CSRF Failed: CSRF cookie not set" Things i tried to fix the issue: Followed https://docs.djangoproject.com/ko/1.11/ref/csrf/ Tryed to delete 'django.middleware.csrf.CsrfViewMiddleware' Tryed @csrf_exempt Nothing of this has worked, everytime still the same error occurs. Here is my code in Typescript: sendMessage(message, receiverId){ let self = this; var message_obj = "{\"id\":\""+ GUID.generateGUID() +"\",\"message\":\""+ message +"\",\"receiverId\":\""+ receiverId + "\",\"moddate\":\""+ Date.now() +"\"}"; var message_json = JSON.parse(message_obj); $.ajax({ type: "POST", url: "/chat/message/", data:{"message_object":message_json}, credentials: 'same-origin', success: function (response) { alert(response); }, error: function (jqXHR, textStatus, errorThrown) { alert(errorThrown); } }) } This is an example of an working ajax call: getMessages(){ let self = this; $.ajax({ type: "GET", url: "/chat/message/", dataType: "json", success: function (response) { response = JSON.stringify(response); alert(response); }, error: function(jqXHR, textStatus, errorThrown){ alert(errorThrown); } }) } I really hope someone can help me! -
Django authentication override not working
I created a file "authentication.py" at the same level as the "settings.py" file in my django project. The content of this file is: from django.contrib.auth.models import User class SettingsBackend(object): def authenticate(self, request, username=None, password=None): user_name = 'user_name' user_password = 'user_pass' login_valid = (user_name == username) pwd_valid = (password == user_password) if login_valid and pwd_valid: try: user = User.objects.get(username=username) except User.DoesNotExist: user = User(username=username) user.is_staff = True user.is_superuser = True user.save() return user return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None Then I added the following line in the "settings.py" file: AUTHENTICATION_BACKENDS = ('myProject.authentication.SettingsBackend',) However, the login doesn't work. It was working before these 2 modification when the user's credentials where stored in the database. I don't know how I can debug this. Any idea ? Here are some pieces of my settings file: INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'default', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ["templates/"], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = … -
Django queryset grouped by count of values in Postgres JSONField
My model: from django.contrib.postgres.fields import JSONField class Image(models.Model): tags = JSONField(null=False, blank=True, default={}) tags field value can be empty, or something like: [ {"tag": "xxx"}, {"tag": "yyy"}, {"tag": "zzz"} ] The number or dicts may vary (from 0 to N). I need to make a query that counts Images grouped by number of tags. Something like: { "0": "345", "1": "1223", "2": "220", ... "N": "23" } where the key is the number of tags, and the value is the count of Image objects that contains this number of tags. How can i do that? Thank you for your help! -
dj-stripe / djstripe not using my config vars for heroku deployment
I am on my way to installing djstripe, however, i get following error when doing pip install -r requirements.txt: CRITICALS: ?: (djstripe.C001) Could not find a Stripe API key. HINT: Add STRIPE_TEST_SECRET_KEY and STRIPE_LIVE_SECRET_KEY to your settings. In my settings.py i have used following code: STRIPE_LIVE_PUBLIC_KEY = os.environ.get('STRIPE_LIVE_PUBLIC_KEY') STRIPE_LIVE_SECRET_KEY = os.environ.get('STRIPE_LIVE_SECRET_KEY') STRIPE_TEST_PUBLIC_KEY = os.environ.get('STRIPE_TEST_PUBLIC_KEY') STRIPE_TEST_SECRET_KEY = os.environ.get('STRIPE_TEST_SECRET_KEY') STRIPE_LIVE_MODE = os.environ.get('STRIPE_LIVE_MODE') # True or False As I am working on heroku, i use an .env file in which I have following code: STRIPE_LIVE_PUBLIC_KEY = 'pk_test_xxxxxxxxxxxxxxxxxxxxxxxx' STRIPE_LIVE_SECRET_KEY = 'sk_test_xxxxxxxxxxxxxxxxxxxxxxxx' STRIPE_TEST_PUBLIC_KEY = 'pk_test_xxxxxxxxxxxxxxxxxxxxxxxx' STRIPE_TEST_SECRET_KEY = 'sk_test_xxxxxxxxxxxxxxxxxxxxxxxx' STRIPE_LIVE_MODE = 'False' Things should work, but somehow, I think my .env file is not taken into account while running. When I use the following format in my settings.py, things work out, but this means I am putting my keys in my code, which i would prefer not to do. STRIPE_LIVE_PUBLIC_KEY = os.environ.get('STRIPE_LIVE_PUBLIC_KEY', 'pk_test_xxxxxxxxxxxxxxxxxxxxxxxx') I had a similar issue with celery not migrating my settings.py. I solved this by putting following code inside my celery.py file: os.environ['DJANGO_SETTINGS_MODULE'] = 'myprogram.settings' probably a similar issue, but where would I have to put this? -
Slicing pandas dataframe using Django template tag 'slice'?
I have a pandas dataframe which I passed into Django HTML. I would like to subset the dataframe when printing it out using Django's template filter 'slice'. Slice works for list and django's object QuerySet but somehow it does not work when used with pandas dataframe. I would like to know WHY and HOW this can work. I slice for 1 rows in the example below but when my code run, it displays all 3 rows. Sample code: in views.py: ## Libraries from django.shortcuts import render from django.http import HttpResponse import pandas as pd def dataframe_view(request): ## Creating pandas dataframe d = {'alphabet': ['a','b','c'], 'num':[1,2,3]} df = pd.DataFrame(d) return render(request, 'dataframe.html', {'df':df}) in dataframe.html <html> <body> ... <table> <thead> <tr> <th>{{ df.columns.0 }} </td> <th>{{ df.columns.1 }} </td> <tr> </thead> <tbody> {% for index, row in df1.iterrows|slice:":1" %} <tr> <td> {{row.0}} </td> <td> {{row.1}} </td> </tr> </tbody> </table> </body> </html> -
Shopify Django Auth With Multiple Store
Am using Django Shopify Auth And I have a problem while login with multiple stores within the same browser. I found some issue of session. It store the same session for all the store. Below is my sample code : @login_required def home(request, *args, **kwargs): # Get a list of the user's products. with request.user.session: # shopify.ShopifyResource.clear_session() orders = shopify.Order.find(financial_status='paid') data = { "orders": orders } return render(request, "home.html", data) And While I run Shopify.ShopifyResource.clear_session() it's not clear the current session also. So please help me. Thanks in advance. -
How to create a randomly generated user profile within a city boundary in Geodjango?
Disclaimer: I have limited knowledge in python.I asked this question in gis.stackexchange, but was voted "unclear what you are asking", may be because it is a programming question, not gis? I have used randomly generate users python script from this source , while the command creates a postgis table, it does not create the randomly generate user profile (the table is empty). What is missing in creating the random user profile in the postgis table? from django.core.management.base import BaseCommand from django.contrib.gis.geos import Point import random import uuid import numpy as np from mymap_app.models import LoveFinderUser class Command(BaseCommand): help = 'generate 1M users for Addis_Ababa with random sex, age, radius, location' def handle(self, *args, **options): Addis_Ababa__lat__min = 8.834544 Addis_Ababa__lat__max = 9.099231 Addis_Ababa__lng__min = 38.640241 Addis_Ababa__lng__max = 38.907086 for i in xrange(10**5): new_random_lat = random.uniform(Addis_Ababa__lat__min, Addis_Ababa__lat__max) new_random_lng = random.uniform(Addis_Ababa__lng__min, Addis_Ababa__lng__max) user_age = random.randrange(18, 55) user_delta_plus = random.choice([1, 2, 3, 5, 8, 13]) user_delta_minus = random.choice([1, 2, 3, 5, 8, 13]) user_sex = random.choice(['F', 'M']) user_prefered_sex=random.choice(['F', 'M']) new_user=LoveFinderUser.objects.create( nickname=str(uuid.uuid4()), age=user_age, sex=user_sex, prefered_sex=user_prefered_sex, prefered_age_min=(user_age-user_delta_minus), prefered_age_max=(user_age+user_delta_plus), last_location=Point(float(new_random_lng), float(new_random_lat)), prefered_radius=random.choice([5, 10, 15, 20, 25, 30]) ) new_user.save()